const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-ec3qAj_Q.js","assets/useLeadSiteSearchSuggestions-DnlrtIXD.js","assets/CityPagesModule-Ax_r21jD.js","assets/imageOptimization-D_YRwPcx.js","assets/LeadSiteLuxuryHome-DrnzzQEg.js","assets/LeadSiteLandRanchHome-7jEZ9ezW.js","assets/LeadSiteSearch-CrwVeaPd.js","assets/SaveSearchButton-Dc4U4LFW.js","assets/LeadSiteMap-Z85TmgNu.js","assets/LeadSiteLuxurySearch-7Ea0kAGE.js","assets/LeadSiteListingDetail-Dz9FwDP1.js","assets/ListingVideoTour-CPkibcjB.js","assets/useListingVideos-DY_Y2uwN.js","assets/LeadSiteLuxuryListingDetail-LpgCCRWo.js","assets/LeadSiteCityPage-C1Ttrb3-.js","assets/LeadSiteSubdivisionPage-7VxqiHOy.js","assets/PostcardManager-Dutj7F7U.js","assets/usePostcardZones-BkewZejP.js","assets/DirectMail-BmHF7HyL.js","assets/jspdf.es.min-CvAyz13_.js","assets/LeadSiteEditor-B5vcK_eH.js","assets/ImageUrlField-Cz5RNV2U.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-Dwc8m5Jx.js","assets/MLSListingDetail-Ci1vqvES.js","assets/EmailCampaignComposer-NMhLeBFJ.js","assets/EditorModeSelector-D6jY9M5R.js","assets/SharedCampaignTemplates-BJuCbX3t.js","assets/TemplateEditorDialog-DuOMqSvO.js","assets/AgentTemplates-Br8Gij7T.js","assets/TheLocalMoveHome-U_R8zEnV.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-C-IihBo_.js"])))=>i.map(i=>d[i]); var jbt=Object.defineProperty;var BPe=s=>{throw TypeError(s)};var Nbt=(s,t,r)=>t in s?jbt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r;var Gn=(s,t,r)=>Nbt(s,typeof t!="symbol"?t+"":t,r),m0e=(s,t,r)=>t.has(s)||BPe("Cannot "+r);var Ss=(s,t,r)=>(m0e(s,t,"read from private field"),r?r.call(s):t.get(s)),Ja=(s,t,r)=>t.has(s)?BPe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,r),na=(s,t,r,n)=>(m0e(s,t,"write to private field"),n?n.call(s,r):t.set(s,r),r),Zi=(s,t,r)=>(m0e(s,t,"access private method"),r);var u9=(s,t,r,n)=>({set _(a){na(s,t,a,r)},get _(){return Ss(s,t,n)}});function kbt(s,t){for(var r=0;rn[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"]'))n(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"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(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 n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();const Sbt="modulepreload",Cbt=function(s){return"/"+s},zPe={},ti=function(t,r,n){let a=Promise.resolve();if(r&&r.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(r.map(c=>{if(c=Cbt(c),c in zPe)return;zPe[c]=!0;const d=c.endsWith(".css"),h=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const m=document.createElement("link");if(m.rel=d?"stylesheet":Sbt,d||(m.as="script"),m.crossOrigin="",m.href=c,o&&m.setAttribute("nonce",o),document.head.appendChild(m),d)return new Promise((x,y)=>{m.addEventListener("load",x),m.addEventListener("error",()=>y(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 Zd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ao(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Tbt(s){if(s.__esModule)return s;var t=s.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(s).forEach(function(n){var a=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(r,n,a.get?a:{enumerable:!0,get:function(){return s[n]}})}),r}var EGe={exports:{}},xme={},AGe={exports:{}},xo={};/** * @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 PF=Symbol.for("react.element"),Ebt=Symbol.for("react.portal"),Abt=Symbol.for("react.fragment"),Mbt=Symbol.for("react.strict_mode"),Ibt=Symbol.for("react.profiler"),Lbt=Symbol.for("react.provider"),Pbt=Symbol.for("react.context"),Dbt=Symbol.for("react.forward_ref"),Rbt=Symbol.for("react.suspense"),Obt=Symbol.for("react.memo"),Fbt=Symbol.for("react.lazy"),$Pe=Symbol.iterator;function Bbt(s){return s===null||typeof s!="object"?null:(s=$Pe&&s[$Pe]||s["@@iterator"],typeof s=="function"?s:null)}var MGe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},IGe=Object.assign,LGe={};function CI(s,t,r){this.props=s,this.context=t,this.refs=LGe,this.updater=r||MGe}CI.prototype.isReactComponent={};CI.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")};CI.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function PGe(){}PGe.prototype=CI.prototype;function iSe(s,t,r){this.props=s,this.context=t,this.refs=LGe,this.updater=r||MGe}var oSe=iSe.prototype=new PGe;oSe.constructor=iSe;IGe(oSe,CI.prototype);oSe.isPureReactComponent=!0;var UPe=Array.isArray,DGe=Object.prototype.hasOwnProperty,lSe={current:null},RGe={key:!0,ref:!0,__self:!0,__source:!0};function OGe(s,t,r){var n,a={},i=null,l=null;if(t!=null)for(n in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)DGe.call(t,n)&&!RGe.hasOwnProperty(n)&&(a[n]=t[n]);var o=arguments.length-2;if(o===1)a.children=r;else if(1>>1,ve=ne[ce];if(0>>1;cea(Be,ye))Dea(Ae,Be)?(ne[ce]=Ae,ne[De]=ye,ce=De):(ne[ce]=Be,ne[Ue]=ye,ce=Ue);else if(Dea(Ae,ye))ne[ce]=Ae,ne[De]=ye,ce=De;else break e}}return ie}function a(ne,ie){var ye=ne.sortIndex-ie.sortIndex;return ye!==0?ye:ne.id-ie.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=[],h=1,m=null,x=3,y=!1,v=!1,w=!1,b=typeof setTimeout=="function"?setTimeout:null,N=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function T(ne){for(var ie=r(d);ie!==null;){if(ie.callback===null)n(d);else if(ie.startTime<=ne)n(d),ie.sortIndex=ie.expirationTime,t(c,ie);else break;ie=r(d)}}function A(ne){if(w=!1,T(ne),!v)if(r(c)!==null)v=!0,le(I);else{var ie=r(d);ie!==null&&oe(A,ie.startTime-ne)}}function I(ne,ie){v=!1,w&&(w=!1,N($),$=-1),y=!0;var ye=x;try{for(T(ie),m=r(c);m!==null&&(!(m.expirationTime>ie)||ne&&!Q());){var ce=m.callback;if(typeof ce=="function"){m.callback=null,x=m.priorityLevel;var ve=ce(m.expirationTime<=ie);ie=s.unstable_now(),typeof ve=="function"?m.callback=ve:m===r(c)&&n(c),T(ie)}else n(c);m=r(c)}if(m!==null)var be=!0;else{var Ue=r(d);Ue!==null&&oe(A,Ue.startTime-ie),be=!1}return be}finally{m=null,x=ye,y=!1}}var D=!1,R=null,$=-1,F=5,z=-1;function Q(){return!(s.unstable_now()-zne||125ce?(ne.sortIndex=ye,t(d,ne),r(c)===null&&ne===r(d)&&(w?(N($),$=-1):w=!0,oe(A,ye-ce))):(ne.sortIndex=ve,t(c,ne),v||y||(v=!0,le(I))),ne},s.unstable_shouldYield=Q,s.unstable_wrapCallback=function(ne){var ie=x;return function(){var ye=x;x=ie;try{return ne.apply(this,arguments)}finally{x=ye}}}})(UGe);$Ge.exports=UGe;var Zbt=$Ge.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 Xbt=k,tx=Zbt;function gn(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),u_e=Object.prototype.hasOwnProperty,Qbt=/^[: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]*$/,VPe={},HPe={};function Jbt(s){return u_e.call(HPe,s)?!0:u_e.call(VPe,s)?!1:Qbt.test(s)?HPe[s]=!0:(VPe[s]=!0,!1)}function e_t(s,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function t_t(s,t,r,n){if(t===null||typeof t>"u"||e_t(s,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.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 wf(s,t,r,n,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=s,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var rm={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){rm[s]=new wf(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];rm[t]=new wf(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){rm[s]=new wf(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){rm[s]=new wf(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){rm[s]=new wf(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){rm[s]=new wf(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){rm[s]=new wf(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){rm[s]=new wf(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){rm[s]=new wf(s,5,!1,s.toLowerCase(),null,!1,!1)});var uSe=/[\-:]([a-z])/g;function hSe(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(uSe,hSe);rm[t]=new wf(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(uSe,hSe);rm[t]=new wf(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(uSe,hSe);rm[t]=new wf(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){rm[s]=new wf(s,1,!1,s.toLowerCase(),null,!1,!1)});rm.xlinkHref=new wf("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){rm[s]=new wf(s,1,!1,s.toLowerCase(),null,!0,!0)});function mSe(s,t,r,n){var a=rm.hasOwnProperty(t)?rm[t]:null;(a!==null?a.type!==0:n||!(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{x0e=!1,Error.prepareStackTrace=r}return(s=s?s.displayName||s.name:"")?ND(s):""}function s_t(s){switch(s.tag){case 5:return ND(s.type);case 16:return ND("Lazy");case 13:return ND("Suspense");case 19:return ND("SuspenseList");case 0:case 2:case 15:return s=g0e(s.type,!1),s;case 11:return s=g0e(s.type.render,!1),s;case 1:return s=g0e(s.type,!0),s;default:return""}}function p_e(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 AE:return"Fragment";case EE:return"Portal";case h_e:return"Profiler";case fSe:return"StrictMode";case m_e:return"Suspense";case f_e:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case HGe:return(s.displayName||"Context")+".Consumer";case VGe:return(s._context.displayName||"Context")+".Provider";case pSe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case xSe:return t=s.displayName||null,t!==null?t:p_e(s.type)||"Memo";case J_:t=s._payload,s=s._init;try{return p_e(s(t))}catch{}}return null}function r_t(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 p_e(t);case 8:return t===fSe?"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 jj(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function WGe(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n_t(s){var t=WGe(s)?"checked":"value",r=Object.getOwnPropertyDescriptor(s.constructor.prototype,t),n=""+s[t];if(!s.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,i=r.set;return Object.defineProperty(s,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){n=""+l,i.call(this,l)}}),Object.defineProperty(s,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(l){n=""+l},stopTracking:function(){s._valueTracker=null,delete s[t]}}}}function f9(s){s._valueTracker||(s._valueTracker=n_t(s))}function KGe(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return s&&(n=WGe(s)?s.checked?"true":"false":s.value),s=n,s!==r?(t.setValue(s),!0):!1}function Oce(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 x_e(s,t){var r=t.checked;return fd({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??s._wrapperState.initialChecked})}function WPe(s,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=jj(t.value!=null?t.value:r),s._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function YGe(s,t){t=t.checked,t!=null&&mSe(s,"checked",t,!1)}function g_e(s,t){YGe(s,t);var r=jj(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&s.value===""||s.value!=r)&&(s.value=""+r):s.value!==""+r&&(s.value=""+r);else if(n==="submit"||n==="reset"){s.removeAttribute("value");return}t.hasOwnProperty("value")?y_e(s,t.type,r):t.hasOwnProperty("defaultValue")&&y_e(s,t.type,jj(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function KPe(s,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+s._wrapperState.initialValue,r||t===s.value||(s.value=t),s.defaultValue=t}r=s.name,r!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,r!==""&&(s.name=r)}function y_e(s,t,r){(t!=="number"||Oce(s.ownerDocument)!==s)&&(r==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+r&&(s.defaultValue=""+r))}var kD=Array.isArray;function sA(s,t,r,n){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=p9.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function $O(s,t){if(t){var r=s.firstChild;if(r&&r===s.lastChild&&r.nodeType===3){r.nodeValue=t;return}}s.textContent=t}var HD={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},a_t=["Webkit","ms","Moz","O"];Object.keys(HD).forEach(function(s){a_t.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),HD[t]=HD[s]})});function JGe(s,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||HD.hasOwnProperty(s)&&HD[s]?(""+t).trim():t+"px"}function eWe(s,t){s=s.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,a=JGe(r,t[r],n);r==="float"&&(r="cssFloat"),n?s.setProperty(r,a):s[r]=a}}var i_t=fd({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 __e(s,t){if(t){if(i_t[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(gn(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(gn(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(gn(61))}if(t.style!=null&&typeof t.style!="object")throw Error(gn(62))}}function w_e(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 j_e=null;function gSe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var N_e=null,rA=null,nA=null;function XPe(s){if(s=OF(s)){if(typeof N_e!="function")throw Error(gn(280));var t=s.stateNode;t&&(t=_me(t),N_e(s.stateNode,s.type,t))}}function tWe(s){rA?nA?nA.push(s):nA=[s]:rA=s}function sWe(){if(rA){var s=rA,t=nA;if(nA=rA=null,XPe(s),t)for(s=0;s>>=0,s===0?32:31-(g_t(s)/y_t|0)|0}var x9=64,g9=4194304;function SD(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 $ce(s,t){var r=s.pendingLanes;if(r===0)return 0;var n=0,a=s.suspendedLanes,i=s.pingedLanes,l=r&268435455;if(l!==0){var o=l&~a;o!==0?n=SD(o):(i&=l,i!==0&&(n=SD(i)))}else l=r&~a,l!==0?n=SD(l):i!==0&&(n=SD(i));if(n===0)return 0;if(t!==0&&t!==n&&!(t&a)&&(a=n&-n,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(n&4&&(n|=r&16),t=s.entangledLanes,t!==0)for(s=s.entanglements,t&=n;0r;r++)t.push(s);return t}function DF(s,t,r){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-wy(t),s[t]=r}function w_t(s,t){var r=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 n=s.eventTimes;for(s=s.expirationTimes;0=WD),i6e=" ",o6e=!1;function wWe(s,t){switch(s){case"keyup":return Z_t.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jWe(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var ME=!1;function Q_t(s,t){switch(s){case"compositionend":return jWe(t);case"keypress":return t.which!==32?null:(o6e=!0,i6e);case"textInput":return s=t.data,s===i6e&&o6e?null:s;default:return null}}function J_t(s,t){if(ME)return s==="compositionend"||!kSe&&wWe(s,t)?(s=bWe(),vU=wSe=Mw=null,ME=!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:r,offset:t-s};s=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=u6e(r)}}function CWe(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?CWe(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function TWe(){for(var s=window,t=Oce();t instanceof s.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)s=t.contentWindow;else break;t=Oce(s.document)}return t}function SSe(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 lwt(s){var t=TWe(),r=s.focusedElem,n=s.selectionRange;if(t!==r&&r&&r.ownerDocument&&CWe(r.ownerDocument.documentElement,r)){if(n!==null&&SSe(r)){if(t=n.start,s=n.end,s===void 0&&(s=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(s,r.value.length);else if(s=(t=r.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=r.textContent.length,i=Math.min(n.start,a);n=n.end===void 0?i:Math.min(n.end,a),!s.extend&&i>n&&(a=n,n=i,i=a),a=h6e(r,i);var l=h6e(r,n);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>n?(s.addRange(t),s.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),s.addRange(t)))}}for(t=[],s=r;s=s.parentNode;)s.nodeType===1&&t.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,IE=null,A_e=null,YD=null,M_e=!1;function m6e(s,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;M_e||IE==null||IE!==Oce(n)||(n=IE,"selectionStart"in n&&SSe(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),YD&&WO(YD,n)||(YD=n,n=Vce(A_e,"onSelect"),0DE||(s.current=O_e[DE],O_e[DE]=null,DE--)}function uc(s,t){DE++,O_e[DE]=s.current,s.current=t}var Nj={},wm=qj(Nj),Kf=qj(!1),b3=Nj;function fM(s,t){var r=s.type.contextTypes;if(!r)return Nj;var n=s.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in r)a[i]=t[i];return n&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=t,s.__reactInternalMemoizedMaskedChildContext=a),a}function Yf(s){return s=s.childContextTypes,s!=null}function Gce(){Tc(Kf),Tc(wm)}function b6e(s,t,r){if(wm.current!==Nj)throw Error(gn(168));uc(wm,t),uc(Kf,r)}function OWe(s,t,r){var n=s.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var a in n)if(!(a in t))throw Error(gn(108,r_t(s)||"Unknown",a));return fd({},r,n)}function Wce(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||Nj,b3=wm.current,uc(wm,s),uc(Kf,Kf.current),!0}function _6e(s,t,r){var n=s.stateNode;if(!n)throw Error(gn(169));r?(s=OWe(s,t,b3),n.__reactInternalMemoizedMergedChildContext=s,Tc(Kf),Tc(wm),uc(wm,s)):Tc(Kf),uc(Kf,r)}var H1=null,wme=!1,M0e=!1;function FWe(s){H1===null?H1=[s]:H1.push(s)}function bwt(s){wme=!0,FWe(s)}function Vj(){if(!M0e&&H1!==null){M0e=!0;var s=0,t=Ml;try{var r=H1;for(Ml=1;s>=l,a-=l,tb=1<<32-wy(t)+a|r<$?(F=R,R=null):F=R.sibling;var z=x(N,R,T[$],A);if(z===null){R===null&&(R=F);break}s&&R&&z.alternate===null&&t(N,R),S=i(z,S,$),D===null?I=z:D.sibling=z,D=z,R=F}if($===T.length)return r(N,R),Uc&&EN(N,$),I;if(R===null){for(;$$?(F=R,R=null):F=R.sibling;var Q=x(N,R,z.value,A);if(Q===null){R===null&&(R=F);break}s&&R&&Q.alternate===null&&t(N,R),S=i(Q,S,$),D===null?I=Q:D.sibling=Q,D=Q,R=F}if(z.done)return r(N,R),Uc&&EN(N,$),I;if(R===null){for(;!z.done;$++,z=T.next())z=m(N,z.value,A),z!==null&&(S=i(z,S,$),D===null?I=z:D.sibling=z,D=z);return Uc&&EN(N,$),I}for(R=n(N,R);!z.done;$++,z=T.next())z=y(R,N,$,z.value,A),z!==null&&(s&&z.alternate!==null&&R.delete(z.key===null?$:z.key),S=i(z,S,$),D===null?I=z:D.sibling=z,D=z);return s&&R.forEach(function(K){return t(N,K)}),Uc&&EN(N,$),I}function b(N,S,T,A){if(typeof T=="object"&&T!==null&&T.type===AE&&T.key===null&&(T=T.props.children),typeof T=="object"&&T!==null){switch(T.$$typeof){case m9:e:{for(var I=T.key,D=S;D!==null;){if(D.key===I){if(I=T.type,I===AE){if(D.tag===7){r(N,D.sibling),S=a(D,T.props.children),S.return=N,N=S;break e}}else if(D.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===J_&&N6e(I)===D.type){r(N,D.sibling),S=a(D,T.props),S.ref=z6(N,D,T),S.return=N,N=S;break e}r(N,D);break}else t(N,D);D=D.sibling}T.type===AE?(S=C4(T.props.children,N.mode,A,T.key),S.return=N,N=S):(A=CU(T.type,T.key,T.props,null,N.mode,A),A.ref=z6(N,S,T),A.return=N,N=A)}return l(N);case EE:e:{for(D=T.key;S!==null;){if(S.key===D)if(S.tag===4&&S.stateNode.containerInfo===T.containerInfo&&S.stateNode.implementation===T.implementation){r(N,S.sibling),S=a(S,T.children||[]),S.return=N,N=S;break e}else{r(N,S);break}else t(N,S);S=S.sibling}S=B0e(T,N.mode,A),S.return=N,N=S}return l(N);case J_:return D=T._init,b(N,S,D(T._payload),A)}if(kD(T))return v(N,S,T,A);if(D6(T))return w(N,S,T,A);N9(N,T)}return typeof T=="string"&&T!==""||typeof T=="number"?(T=""+T,S!==null&&S.tag===6?(r(N,S.sibling),S=a(S,T),S.return=N,N=S):(r(N,S),S=F0e(T,N.mode,A),S.return=N,N=S),l(N)):r(N,S)}return b}var xM=UWe(!0),qWe=UWe(!1),Zce=qj(null),Xce=null,FE=null,ASe=null;function MSe(){ASe=FE=Xce=null}function ISe(s){var t=Zce.current;Tc(Zce),s._currentValue=t}function z_e(s,t,r){for(;s!==null;){var n=s.alternate;if((s.childLanes&t)!==t?(s.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),s===r)break;s=s.return}}function iA(s,t){Xce=s,ASe=FE=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(qf=!0),s.firstContext=null)}function mg(s){var t=s._currentValue;if(ASe!==s)if(s={context:s,memoizedValue:t,next:null},FE===null){if(Xce===null)throw Error(gn(308));FE=s,Xce.dependencies={lanes:0,firstContext:s}}else FE=FE.next=s;return t}var QC=null;function LSe(s){QC===null?QC=[s]:QC.push(s)}function VWe(s,t,r,n){var a=t.interleaved;return a===null?(r.next=r,LSe(t)):(r.next=a.next,a.next=r),t.interleaved=r,Cb(s,n)}function Cb(s,t){s.lanes|=t;var r=s.alternate;for(r!==null&&(r.lanes|=t),r=s,s=s.return;s!==null;)s.childLanes|=t,r=s.alternate,r!==null&&(r.childLanes|=t),r=s,s=s.return;return r.tag===3?r.stateNode:null}var ew=!1;function PSe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function HWe(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 db(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function Vw(s,t,r){var n=s.updateQueue;if(n===null)return null;if(n=n.shared,Wo&2){var a=n.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),n.pending=t,Cb(s,r)}return a=n.interleaved,a===null?(t.next=t,LSe(n)):(t.next=a.next,a.next=t),n.interleaved=t,Cb(s,r)}function _U(s,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,vSe(s,r)}}function k6e(s,t){var r=s.updateQueue,n=s.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var a=null,i=null;if(r=r.firstBaseUpdate,r!==null){do{var l={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};i===null?a=i=l:i=i.next=l,r=r.next}while(r!==null);i===null?a=i=t:i=i.next=t}else a=i=t;r={baseState:n.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:n.shared,effects:n.effects},s.updateQueue=r;return}s=r.lastBaseUpdate,s===null?r.firstBaseUpdate=t:s.next=t,r.lastBaseUpdate=t}function Qce(s,t,r,n){var a=s.updateQueue;ew=!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 h=s.alternate;h!==null&&(h=h.updateQueue,o=h.lastBaseUpdate,o!==l&&(o===null?h.firstBaseUpdate=d:o.next=d,h.lastBaseUpdate=c))}if(i!==null){var m=a.baseState;l=0,h=d=c=null,o=i;do{var x=o.lane,y=o.eventTime;if((n&x)===x){h!==null&&(h=h.next={eventTime:y,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var v=s,w=o;switch(x=t,y=r,w.tag){case 1:if(v=w.payload,typeof v=="function"){m=v.call(y,m,x);break e}m=v;break e;case 3:v.flags=v.flags&-65537|128;case 0:if(v=w.payload,x=typeof v=="function"?v.call(y,m,x):v,x==null)break e;m=fd({},m,x);break e;case 2:ew=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,x=a.effects,x===null?a.effects=[o]:x.push(o))}else y={eventTime:y,lane:x,tag:o.tag,payload:o.payload,callback:o.callback,next:null},h===null?(d=h=y,c=m):h=h.next=y,l|=x;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;x=o,o=x.next,x.next=null,a.lastBaseUpdate=x,a.shared.pending=null}}while(!0);if(h===null&&(c=m),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=h,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);j3|=l,s.lanes=l,s.memoizedState=m}}function S6e(s,t,r){if(s=t.effects,t.effects=null,s!==null)for(t=0;tr?r:4,s(!0);var n=L0e.transition;L0e.transition={};try{s(!1),t()}finally{Ml=r,L0e.transition=n}}function lKe(){return fg().memoizedState}function Nwt(s,t,r){var n=Gw(s);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},cKe(s))dKe(t,r);else if(r=VWe(s,t,r,n),r!==null){var a=pf();jy(r,s,n,a),uKe(r,t,n)}}function kwt(s,t,r){var n=Gw(s),a={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(cKe(s))dKe(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,r);if(a.hasEagerState=!0,a.eagerState=o,Py(o,l)){var c=t.interleaved;c===null?(a.next=a,LSe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}r=VWe(s,t,a,n),r!==null&&(a=pf(),jy(r,s,n,a),uKe(r,t,n))}}function cKe(s){var t=s.alternate;return s===ud||t!==null&&t===ud}function dKe(s,t){ZD=ede=!0;var r=s.pending;r===null?t.next=t:(t.next=r.next,r.next=t),s.pending=t}function uKe(s,t,r){if(r&4194240){var n=t.lanes;n&=s.pendingLanes,r|=n,t.lanes=r,vSe(s,r)}}var tde={readContext:mg,useCallback:um,useContext:um,useEffect:um,useImperativeHandle:um,useInsertionEffect:um,useLayoutEffect:um,useMemo:um,useReducer:um,useRef:um,useState:um,useDebugValue:um,useDeferredValue:um,useTransition:um,useMutableSource:um,useSyncExternalStore:um,useId:um,unstable_isNewReconciler:!1},Swt={readContext:mg,useCallback:function(s,t){return k0().memoizedState=[s,t===void 0?null:t],s},useContext:mg,useEffect:T6e,useImperativeHandle:function(s,t,r){return r=r!=null?r.concat([s]):null,jU(4194308,4,rKe.bind(null,t,s),r)},useLayoutEffect:function(s,t){return jU(4194308,4,s,t)},useInsertionEffect:function(s,t){return jU(4,2,s,t)},useMemo:function(s,t){var r=k0();return t=t===void 0?null:t,s=s(),r.memoizedState=[s,t],s},useReducer:function(s,t,r){var n=k0();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:t},n.queue=s,s=s.dispatch=Nwt.bind(null,ud,s),[n.memoizedState,s]},useRef:function(s){var t=k0();return s={current:s},t.memoizedState=s},useState:C6e,useDebugValue:USe,useDeferredValue:function(s){return k0().memoizedState=s},useTransition:function(){var s=C6e(!1),t=s[0];return s=jwt.bind(null,s[1]),k0().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,r){var n=ud,a=k0();if(Uc){if(r===void 0)throw Error(gn(407));r=r()}else{if(r=t(),yh===null)throw Error(gn(349));w3&30||YWe(n,t,r)}a.memoizedState=r;var i={value:r,getSnapshot:t};return a.queue=i,T6e(XWe.bind(null,n,i,s),[s]),n.flags|=2048,t8(9,ZWe.bind(null,n,i,r,t),void 0,null),r},useId:function(){var s=k0(),t=yh.identifierPrefix;if(Uc){var r=sb,n=tb;r=(n&~(1<<32-wy(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=JO++,0<\/script>",s=s.removeChild(s.firstChild)):typeof n.is=="string"?s=l.createElement(r,{is:n.is}):(s=l.createElement(r),r==="select"&&(l=s,n.multiple?l.multiple=!0:n.size&&(l.size=n.size))):s=l.createElementNS(s,r),s[B0]=t,s[ZO]=n,_Ke(s,t,!1,!1),t.stateNode=s;e:{switch(l=w_e(r,n),r){case"dialog":wc("cancel",s),wc("close",s),a=n;break;case"iframe":case"object":case"embed":wc("load",s),a=n;break;case"video":case"audio":for(a=0;avM&&(t.flags|=128,n=!0,$6(i,!1),t.lanes=4194304)}else{if(!n)if(s=Jce(l),s!==null){if(t.flags|=128,n=!0,r=s.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),$6(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Uc)return hm(t),null}else 2*Kd()-i.renderingStartTime>vM&&r!==1073741824&&(t.flags|=128,n=!0,$6(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(r=i.last,r!==null?r.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Kd(),t.sibling=null,r=ad.current,uc(ad,n?r&1|2:r&1),t):(hm(t),null);case 22:case 23:return KSe(),n=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Ap&1073741824&&(hm(t),t.subtreeFlags&6&&(t.flags|=8192)):hm(t),null;case 24:return null;case 25:return null}throw Error(gn(156,t.tag))}function Pwt(s,t){switch(TSe(t),t.tag){case 1:return Yf(t.type)&&Gce(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return gM(),Tc(Kf),Tc(wm),OSe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return RSe(t),null;case 13:if(Tc(ad),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(gn(340));pM()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Tc(ad),null;case 4:return gM(),null;case 10:return ISe(t.type._context),null;case 22:case 23:return KSe(),null;case 24:return null;default:return null}}var S9=!1,gm=!1,Dwt=typeof WeakSet=="function"?WeakSet:Set,pa=null;function BE(s,t){var r=s.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Nd(s,t,n)}else r.current=null}function Y_e(s,t,r){try{r()}catch(n){Nd(s,t,n)}}var B6e=!1;function Rwt(s,t){if(I_e=Uce,s=TWe(),SSe(s)){if("selectionStart"in s)var r={start:s.selectionStart,end:s.selectionEnd};else e:{r=(r=s.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var a=n.anchorOffset,i=n.focusNode;n=n.focusOffset;try{r.nodeType,i.nodeType}catch{r=null;break e}var l=0,o=-1,c=-1,d=0,h=0,m=s,x=null;t:for(;;){for(var y;m!==r||a!==0&&m.nodeType!==3||(o=l+a),m!==i||n!==0&&m.nodeType!==3||(c=l+n),m.nodeType===3&&(l+=m.nodeValue.length),(y=m.firstChild)!==null;)x=m,m=y;for(;;){if(m===s)break t;if(x===r&&++d===a&&(o=l),x===i&&++h===n&&(c=l),(y=m.nextSibling)!==null)break;m=x,x=m.parentNode}m=y}r=o===-1||c===-1?null:{start:o,end:c}}else r=null}r=r||{start:0,end:0}}else r=null;for(L_e={focusedElem:s,selectionRange:r},Uce=!1,pa=t;pa!==null;)if(t=pa,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,pa=s;else for(;pa!==null;){t=pa;try{var v=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(v!==null){var w=v.memoizedProps,b=v.memoizedState,N=t.stateNode,S=N.getSnapshotBeforeUpdate(t.elementType===t.type?w:ay(t.type,w),b);N.__reactInternalSnapshotBeforeUpdate=S}break;case 3:var T=t.stateNode.containerInfo;T.nodeType===1?T.textContent="":T.nodeType===9&&T.documentElement&&T.removeChild(T.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(gn(163))}}catch(A){Nd(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,pa=s;break}pa=t.return}return v=B6e,B6e=!1,v}function XD(s,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var a=n=n.next;do{if((a.tag&s)===s){var i=a.destroy;a.destroy=void 0,i!==void 0&&Y_e(t,r,i)}a=a.next}while(a!==n)}}function kme(s,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&s)===s){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function Z_e(s){var t=s.ref;if(t!==null){var r=s.stateNode;switch(s.tag){case 5:s=r;break;default:s=r}typeof t=="function"?t(s):t.current=s}}function NKe(s){var t=s.alternate;t!==null&&(s.alternate=null,NKe(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[B0],delete t[ZO],delete t[R_e],delete t[ywt],delete t[vwt])),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 kKe(s){return s.tag===5||s.tag===3||s.tag===4}function z6e(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||kKe(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 X_e(s,t,r){var n=s.tag;if(n===5||n===6)s=s.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(s,t):r.insertBefore(s,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(s,r)):(t=r,t.appendChild(s)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Hce));else if(n!==4&&(s=s.child,s!==null))for(X_e(s,t,r),s=s.sibling;s!==null;)X_e(s,t,r),s=s.sibling}function Q_e(s,t,r){var n=s.tag;if(n===5||n===6)s=s.stateNode,t?r.insertBefore(s,t):r.appendChild(s);else if(n!==4&&(s=s.child,s!==null))for(Q_e(s,t,r),s=s.sibling;s!==null;)Q_e(s,t,r),s=s.sibling}var Bh=null,ly=!1;function I_(s,t,r){for(r=r.child;r!==null;)SKe(s,t,r),r=r.sibling}function SKe(s,t,r){if(Q0&&typeof Q0.onCommitFiberUnmount=="function")try{Q0.onCommitFiberUnmount(gme,r)}catch{}switch(r.tag){case 5:gm||BE(r,t);case 6:var n=Bh,a=ly;Bh=null,I_(s,t,r),Bh=n,ly=a,Bh!==null&&(ly?(s=Bh,r=r.stateNode,s.nodeType===8?s.parentNode.removeChild(r):s.removeChild(r)):Bh.removeChild(r.stateNode));break;case 18:Bh!==null&&(ly?(s=Bh,r=r.stateNode,s.nodeType===8?A0e(s.parentNode,r):s.nodeType===1&&A0e(s,r),HO(s)):A0e(Bh,r.stateNode));break;case 4:n=Bh,a=ly,Bh=r.stateNode.containerInfo,ly=!0,I_(s,t,r),Bh=n,ly=a;break;case 0:case 11:case 14:case 15:if(!gm&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){a=n=n.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&Y_e(r,t,l),a=a.next}while(a!==n)}I_(s,t,r);break;case 1:if(!gm&&(BE(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(o){Nd(r,t,o)}I_(s,t,r);break;case 21:I_(s,t,r);break;case 22:r.mode&1?(gm=(n=gm)||r.memoizedState!==null,I_(s,t,r),gm=n):I_(s,t,r);break;default:I_(s,t,r)}}function $6e(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var r=s.stateNode;r===null&&(r=s.stateNode=new Dwt),t.forEach(function(n){var a=Hwt.bind(null,s,n);r.has(n)||(r.add(n),n.then(a,a))})}}function Zg(s,t){var r=t.deletions;if(r!==null)for(var n=0;na&&(a=l),n&=~i}if(n=a,n=Kd()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*Fwt(n/1960))-n,10s?16:s,Iw===null)var n=!1;else{if(s=Iw,Iw=null,nde=0,Wo&6)throw Error(gn(331));var a=Wo;for(Wo|=4,pa=s.current;pa!==null;){var i=pa,l=i.child;if(pa.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cKd()-GSe?S4(s,0):HSe|=r),Zf(s,t)}function PKe(s,t){t===0&&(s.mode&1?(t=g9,g9<<=1,!(g9&130023424)&&(g9=4194304)):t=1);var r=pf();s=Cb(s,t),s!==null&&(DF(s,t,r),Zf(s,r))}function Vwt(s){var t=s.memoizedState,r=0;t!==null&&(r=t.retryLane),PKe(s,r)}function Hwt(s,t){var r=0;switch(s.tag){case 13:var n=s.stateNode,a=s.memoizedState;a!==null&&(r=a.retryLane);break;case 19:n=s.stateNode;break;default:throw Error(gn(314))}n!==null&&n.delete(t),PKe(s,r)}var DKe;DKe=function(s,t,r){if(s!==null)if(s.memoizedProps!==t.pendingProps||Kf.current)qf=!0;else{if(!(s.lanes&r)&&!(t.flags&128))return qf=!1,Iwt(s,t,r);qf=!!(s.flags&131072)}else qf=!1,Uc&&t.flags&1048576&&BWe(t,Yce,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;NU(s,t),s=t.pendingProps;var a=fM(t,wm.current);iA(t,r),a=BSe(null,t,n,s,a,r);var i=zSe();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,Yf(n)?(i=!0,Wce(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,PSe(t),a.updater=Nme,t.stateNode=a,a._reactInternals=t,U_e(t,n,s,r),t=H_e(null,t,n,!0,i,r)):(t.tag=0,Uc&&i&&CSe(t),ef(null,t,a,r),t=t.child),t;case 16:n=t.elementType;e:{switch(NU(s,t),s=t.pendingProps,a=n._init,n=a(n._payload),t.type=n,a=t.tag=Wwt(n),s=ay(n,s),a){case 0:t=V_e(null,t,n,s,r);break e;case 1:t=R6e(null,t,n,s,r);break e;case 11:t=P6e(null,t,n,s,r);break e;case 14:t=D6e(null,t,n,ay(n.type,s),r);break e}throw Error(gn(306,n,""))}return t;case 0:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ay(n,a),V_e(s,t,n,a,r);case 1:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ay(n,a),R6e(s,t,n,a,r);case 3:e:{if(yKe(t),s===null)throw Error(gn(387));n=t.pendingProps,i=t.memoizedState,a=i.element,HWe(s,t),Qce(t,n,null,r);var l=t.memoizedState;if(n=l.element,i.isDehydrated)if(i={element:n,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=yM(Error(gn(423)),t),t=O6e(s,t,n,r,a);break e}else if(n!==a){a=yM(Error(gn(424)),t),t=O6e(s,t,n,r,a);break e}else for(zp=qw(t.stateNode.containerInfo.firstChild),Up=t,Uc=!0,my=null,r=qWe(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(pM(),n===a){t=Tb(s,t,r);break e}ef(s,t,n,r)}t=t.child}return t;case 5:return GWe(t),s===null&&B_e(t),n=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,P_e(n,a)?l=null:i!==null&&P_e(n,i)&&(t.flags|=32),gKe(s,t),ef(s,t,l,r),t.child;case 6:return s===null&&B_e(t),null;case 13:return vKe(s,t,r);case 4:return DSe(t,t.stateNode.containerInfo),n=t.pendingProps,s===null?t.child=xM(t,null,n,r):ef(s,t,n,r),t.child;case 11:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ay(n,a),P6e(s,t,n,a,r);case 7:return ef(s,t,t.pendingProps,r),t.child;case 8:return ef(s,t,t.pendingProps.children,r),t.child;case 12:return ef(s,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,uc(Zce,n._currentValue),n._currentValue=l,i!==null)if(Py(i.value,l)){if(i.children===a.children&&!Kf.current){t=Tb(s,t,r);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===n){if(i.tag===1){c=db(-1,r&-r),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?c.next=c:(c.next=h.next,h.next=c),d.pending=c}}i.lanes|=r,c=i.alternate,c!==null&&(c.lanes|=r),z_e(i.return,r,t),o.lanes|=r;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(gn(341));l.lanes|=r,o=l.alternate,o!==null&&(o.lanes|=r),z_e(l,r,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}ef(s,t,a.children,r),t=t.child}return t;case 9:return a=t.type,n=t.pendingProps.children,iA(t,r),a=mg(a),n=n(a),t.flags|=1,ef(s,t,n,r),t.child;case 14:return n=t.type,a=ay(n,t.pendingProps),a=ay(n.type,a),D6e(s,t,n,a,r);case 15:return pKe(s,t,t.type,t.pendingProps,r);case 17:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:ay(n,a),NU(s,t),t.tag=1,Yf(n)?(s=!0,Wce(t)):s=!1,iA(t,r),hKe(t,n,a),U_e(t,n,a,r),H_e(null,t,n,!0,s,r);case 19:return bKe(s,t,r);case 22:return xKe(s,t,r)}throw Error(gn(156,t.tag))};function RKe(s,t){return cWe(s,t)}function Gwt(s,t,r,n){this.tag=s,this.key=r,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=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function eg(s,t,r,n){return new Gwt(s,t,r,n)}function ZSe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Wwt(s){if(typeof s=="function")return ZSe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===pSe)return 11;if(s===xSe)return 14}return 2}function Ww(s,t){var r=s.alternate;return r===null?(r=eg(s.tag,t,s.key,s.mode),r.elementType=s.elementType,r.type=s.type,r.stateNode=s.stateNode,r.alternate=s,s.alternate=r):(r.pendingProps=t,r.type=s.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=s.flags&14680064,r.childLanes=s.childLanes,r.lanes=s.lanes,r.child=s.child,r.memoizedProps=s.memoizedProps,r.memoizedState=s.memoizedState,r.updateQueue=s.updateQueue,t=s.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=s.sibling,r.index=s.index,r.ref=s.ref,r}function CU(s,t,r,n,a,i){var l=2;if(n=s,typeof s=="function")ZSe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case AE:return C4(r.children,a,i,t);case fSe:l=8,a|=8;break;case h_e:return s=eg(12,r,t,a|2),s.elementType=h_e,s.lanes=i,s;case m_e:return s=eg(13,r,t,a),s.elementType=m_e,s.lanes=i,s;case f_e:return s=eg(19,r,t,a),s.elementType=f_e,s.lanes=i,s;case GGe:return Cme(r,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case VGe:l=10;break e;case HGe:l=9;break e;case pSe:l=11;break e;case xSe:l=14;break e;case J_:l=16,n=null;break e}throw Error(gn(130,s==null?s:typeof s,""))}return t=eg(l,r,t,a),t.elementType=s,t.type=n,t.lanes=i,t}function C4(s,t,r,n){return s=eg(7,s,n,t),s.lanes=r,s}function Cme(s,t,r,n){return s=eg(22,s,n,t),s.elementType=GGe,s.lanes=r,s.stateNode={isHidden:!1},s}function F0e(s,t,r){return s=eg(6,s,null,t),s.lanes=r,s}function B0e(s,t,r){return t=eg(4,s.children!==null?s.children:[],s.key,t),t.lanes=r,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function Kwt(s,t,r,n,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=v0e(0),this.expirationTimes=v0e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=v0e(0),this.identifierPrefix=n,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function XSe(s,t,r,n,a,i,l,o,c){return s=new Kwt(s,t,r,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=eg(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},PSe(i),s}function Ywt(s,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(zKe)}catch(s){console.error(s)}}zKe(),zGe.exports=hx;var Vf=zGe.exports;const tCe=Ao(Vf);var $Ke,Y6e=Vf;$Ke=Y6e.createRoot,Y6e.hydrateRoot;const ejt=1,tjt=1e6;let z0e=0;function sjt(){return z0e=(z0e+1)%Number.MAX_SAFE_INTEGER,z0e.toString()}const $0e=new Map,Z6e=s=>{if($0e.has(s))return;const t=setTimeout(()=>{$0e.delete(s),eR({type:"REMOVE_TOAST",toastId:s})},tjt);$0e.set(s,t)},rjt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,ejt)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(r=>r.id===t.toast.id?{...r,...t.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=t;return r?Z6e(r):s.toasts.forEach(n=>{Z6e(n.id)}),{...s,toasts:s.toasts.map(n=>n.id===r||r===void 0?{...n,open:!1}:n)}}case"REMOVE_TOAST":return t.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(r=>r.id!==t.toastId)}}},TU=[];let EU={toasts:[]};function eR(s){EU=rjt(EU,s),TU.forEach(t=>{t(EU)})}function cn({...s}){const t=sjt(),r=a=>eR({type:"UPDATE_TOAST",toast:{...a,id:t}}),n=()=>eR({type:"DISMISS_TOAST",toastId:t});return eR({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||n()}}}),{id:t,dismiss:n,update:r}}function Ma(){const[s,t]=k.useState(EU);return k.useEffect(()=>(TU.push(t),()=>{const r=TU.indexOf(t);r>-1&&TU.splice(r,1)}),[s]),{...s,toast:cn,dismiss:r=>eR({type:"DISMISS_TOAST",toastId:r})}}function Vr(s,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(s==null||s(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function X6e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function Eb(...s){return t=>{let r=!1;const n=s.map(a=>{const i=X6e(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{children:l,...o}=i,c=k.useMemo(()=>o,Object.values(o));return e.jsx(r.Provider,{value:c,children:l})};n.displayName=s+"Provider";function a(i){const l=k.useContext(r);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[n,a]}function pd(s,t=[]){let r=[];function n(i,l){const o=k.createContext(l),c=r.length;r=[...r,l];const d=m=>{var N;const{scope:x,children:y,...v}=m,w=((N=x==null?void 0:x[s])==null?void 0:N[c])||o,b=k.useMemo(()=>v,Object.values(v));return e.jsx(w.Provider,{value:b,children:y})};d.displayName=i+"Provider";function h(m,x){var w;const y=((w=x==null?void 0:x[s])==null?void 0:w[c])||o,v=k.useContext(y);if(v)return v;if(l!==void 0)return l;throw new Error(`\`${m}\` must be used within \`${i}\``)}return[d,h]}const a=()=>{const i=r.map(l=>k.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return k.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[n,ajt(a,...t)]}function ajt(...s){const t=s[0];if(s.length===1)return t;const r=()=>{const n=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=n.reduce((o,{useScope:c,scopeName:d})=>{const m=c(i)[`__scope${d}`];return{...o,...m}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return r.scopeName=t.scopeName,r}function kj(s){const t=ijt(s),r=k.forwardRef((n,a)=>{const{children:i,...l}=n,o=k.Children.toArray(i),c=o.find(ojt);if(c){const d=c.props.children,h=o.map(m=>m===c?k.Children.count(d)>1?k.Children.only(null):k.isValidElement(d)?d.props.children:null:m);return e.jsx(t,{...l,ref:a,children:k.isValidElement(d)?k.cloneElement(d,void 0,h):null})}return e.jsx(t,{...l,ref:a,children:i})});return r.displayName=`${s}.Slot`,r}var sCe=kj("Slot");function ijt(s){const t=k.forwardRef((r,n)=>{const{children:a,...i}=r;if(k.isValidElement(a)){const l=cjt(a),o=ljt(i,a.props);return a.type!==k.Fragment&&(o.ref=n?Eb(n,l):l),k.cloneElement(a,o)}return k.Children.count(a)>1?k.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var UKe=Symbol("radix.slottable");function qKe(s){const t=({children:r})=>e.jsx(e.Fragment,{children:r});return t.displayName=`${s}.Slottable`,t.__radixId=UKe,t}function ojt(s){return k.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===UKe}function ljt(s,t){const r={...t};for(const n in t){const a=s[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(r[n]=a):n==="style"?r[n]={...a,...i}:n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return{...s,...r}}function cjt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}function BF(s){const t=s+"CollectionProvider",[r,n]=pd(t),[a,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),l=w=>{const{scope:b,children:N}=w,S=wt.useRef(null),T=wt.useRef(new Map).current;return e.jsx(a,{scope:b,itemMap:T,collectionRef:S,children:N})};l.displayName=t;const o=s+"CollectionSlot",c=kj(o),d=wt.forwardRef((w,b)=>{const{scope:N,children:S}=w,T=i(o,N),A=Ga(b,T.collectionRef);return e.jsx(c,{ref:A,children:S})});d.displayName=o;const h=s+"CollectionItemSlot",m="data-radix-collection-item",x=kj(h),y=wt.forwardRef((w,b)=>{const{scope:N,children:S,...T}=w,A=wt.useRef(null),I=Ga(b,A),D=i(h,N);return wt.useEffect(()=>(D.itemMap.set(A,{ref:A,...T}),()=>void D.itemMap.delete(A))),e.jsx(x,{[m]:"",ref:I,children:S})});y.displayName=h;function v(w){const b=i(s+"CollectionConsumer",w);return wt.useCallback(()=>{const S=b.collectionRef.current;if(!S)return[];const T=Array.from(S.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((D,R)=>T.indexOf(D.ref.current)-T.indexOf(R.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:l,Slot:d,ItemSlot:y},v,n]}var djt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],wn=djt.reduce((s,t)=>{const r=kj(`Primitive.${t}`),n=k.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return n.displayName=`Primitive.${t}`,{...s,[t]:n}},{});function rCe(s,t){s&&Vf.flushSync(()=>s.dispatchEvent(t))}function Ed(s){const t=k.useRef(s);return k.useEffect(()=>{t.current=s}),k.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}function ujt(s,t=globalThis==null?void 0:globalThis.document){const r=Ed(s);k.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var hjt="DismissableLayer",rwe="dismissableLayer.update",mjt="dismissableLayer.pointerDownOutside",fjt="dismissableLayer.focusOutside",Q6e,VKe=k.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Hj=k.forwardRef((s,t)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=k.useContext(VKe),[h,m]=k.useState(null),x=(h==null?void 0:h.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,y]=k.useState({}),v=Ga(t,R=>m(R)),w=Array.from(d.layers),[b]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),N=w.indexOf(b),S=h?w.indexOf(h):-1,T=d.layersWithOutsidePointerEventsDisabled.size>0,A=S>=N,I=xjt(R=>{const $=R.target,F=[...d.branches].some(z=>z.contains($));!A||F||(a==null||a(R),l==null||l(R),R.defaultPrevented||o==null||o())},x),D=gjt(R=>{const $=R.target;[...d.branches].some(z=>z.contains($))||(i==null||i(R),l==null||l(R),R.defaultPrevented||o==null||o())},x);return ujt(R=>{S===d.layers.size-1&&(n==null||n(R),!R.defaultPrevented&&o&&(R.preventDefault(),o()))},x),k.useEffect(()=>{if(h)return r&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Q6e=x.body.style.pointerEvents,x.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(h)),d.layers.add(h),J6e(),()=>{r&&d.layersWithOutsidePointerEventsDisabled.size===1&&(x.body.style.pointerEvents=Q6e)}},[h,x,r,d]),k.useEffect(()=>()=>{h&&(d.layers.delete(h),d.layersWithOutsidePointerEventsDisabled.delete(h),J6e())},[h,d]),k.useEffect(()=>{const R=()=>y({});return document.addEventListener(rwe,R),()=>document.removeEventListener(rwe,R)},[]),e.jsx(wn.div,{...c,ref:v,style:{pointerEvents:T?A?"auto":"none":void 0,...s.style},onFocusCapture:Vr(s.onFocusCapture,D.onFocusCapture),onBlurCapture:Vr(s.onBlurCapture,D.onBlurCapture),onPointerDownCapture:Vr(s.onPointerDownCapture,I.onPointerDownCapture)})});Hj.displayName=hjt;var pjt="DismissableLayerBranch",HKe=k.forwardRef((s,t)=>{const r=k.useContext(VKe),n=k.useRef(null),a=Ga(t,n);return k.useEffect(()=>{const i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),e.jsx(wn.div,{...s,ref:a})});HKe.displayName=pjt;function xjt(s,t=globalThis==null?void 0:globalThis.document){const r=Ed(s),n=k.useRef(!1),a=k.useRef(()=>{});return k.useEffect(()=>{const i=o=>{if(o.target&&!n.current){let c=function(){GKe(mjt,r,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);n.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,r]),{onPointerDownCapture:()=>n.current=!0}}function gjt(s,t=globalThis==null?void 0:globalThis.document){const r=Ed(s),n=k.useRef(!1);return k.useEffect(()=>{const a=i=>{i.target&&!n.current&&GKe(fjt,r,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function J6e(){const s=new CustomEvent(rwe);document.dispatchEvent(s)}function GKe(s,t,r,{discrete:n}){const a=r.originalEvent.target,i=new CustomEvent(s,{bubbles:!1,cancelable:!0,detail:r});t&&a.addEventListener(s,t,{once:!0}),n?rCe(a,i):a.dispatchEvent(i)}var yjt=Hj,vjt=HKe,Dd=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},bjt="Portal",AI=k.forwardRef((s,t)=>{var o;const{container:r,...n}=s,[a,i]=k.useState(!1);Dd(()=>i(!0),[]);const l=r||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?tCe.createPortal(e.jsx(wn.div,{...n,ref:t}),l):null});AI.displayName=bjt;function _jt(s,t){return k.useReducer((r,n)=>t[r][n]??r,s)}var ru=s=>{const{present:t,children:r}=s,n=wjt(t),a=typeof r=="function"?r({present:n.isPresent}):k.Children.only(r),i=Ga(n.ref,jjt(a));return typeof r=="function"||n.isPresent?k.cloneElement(a,{ref:i}):null};ru.displayName="Presence";function wjt(s){const[t,r]=k.useState(),n=k.useRef(null),a=k.useRef(s),i=k.useRef("none"),l=s?"mounted":"unmounted",[o,c]=_jt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return k.useEffect(()=>{const d=E9(n.current);i.current=o==="mounted"?d:"none"},[o]),Dd(()=>{const d=n.current,h=a.current;if(h!==s){const x=i.current,y=E9(d);s?c("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(h&&x!==y?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),Dd(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,m=y=>{const w=E9(n.current).includes(y.animationName);if(y.target===t&&w&&(c("ANIMATION_END"),!a.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},x=y=>{y.target===t&&(i.current=E9(n.current))};return t.addEventListener("animationstart",x),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",x),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:k.useCallback(d=>{n.current=d?getComputedStyle(d):null,r(d)},[])}}function E9(s){return(s==null?void 0:s.animationName)||"none"}function jjt(s){var n,a;let t=(n=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?s.props.ref:s.props.ref||s.ref)}var Njt=dSe[" useInsertionEffect ".trim().toString()]||Dd;function Sh({prop:s,defaultProp:t,onChange:r=()=>{},caller:n}){const[a,i,l]=kjt({defaultProp:t,onChange:r}),o=s!==void 0,c=o?s:a;{const h=k.useRef(s!==void 0);k.useEffect(()=>{const m=h.current;m!==o&&console.warn(`${n} is changing from ${m?"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.`),h.current=o},[o,n])}const d=k.useCallback(h=>{var m;if(o){const x=Sjt(h)?h(s):h;x!==s&&((m=l.current)==null||m.call(l,x))}else i(h)},[o,s,i,l]);return[c,d]}function kjt({defaultProp:s,onChange:t}){const[r,n]=k.useState(s),a=k.useRef(r),i=k.useRef(t);return Njt(()=>{i.current=t},[t]),k.useEffect(()=>{var l;a.current!==r&&((l=i.current)==null||l.call(i,r),a.current=r)},[r,a]),[r,n,i]}function Sjt(s){return typeof s=="function"}var WKe=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"}),Cjt="VisuallyHidden",Ime=k.forwardRef((s,t)=>e.jsx(wn.span,{...s,ref:t,style:{...WKe,...s.style}}));Ime.displayName=Cjt;var Tjt=Ime,nCe="ToastProvider",[aCe,Ejt,Ajt]=BF("Toast"),[KKe,aUs]=pd("Toast",[Ajt]),[Mjt,Lme]=KKe(nCe),YKe=s=>{const{__scopeToast:t,label:r="Notification",duration:n=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=k.useState(null),[d,h]=k.useState(0),m=k.useRef(!1),x=k.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${nCe}\`. Expected non-empty \`string\`.`),e.jsx(aCe.Provider,{scope:t,children:e.jsx(Mjt,{scope:t,label:r,duration:n,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:k.useCallback(()=>h(y=>y+1),[]),onToastRemove:k.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:x,children:l})})};YKe.displayName=nCe;var ZKe="ToastViewport",Ijt=["F8"],nwe="toast.viewportPause",awe="toast.viewportResume",XKe=k.forwardRef((s,t)=>{const{__scopeToast:r,hotkey:n=Ijt,label:a="Notifications ({hotkey})",...i}=s,l=Lme(ZKe,r),o=Ejt(r),c=k.useRef(null),d=k.useRef(null),h=k.useRef(null),m=k.useRef(null),x=Ga(t,m,l.onViewportChange),y=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),v=l.toastCount>0;k.useEffect(()=>{const b=N=>{var T;n.length!==0&&n.every(A=>N[A]||N.code===A)&&((T=m.current)==null||T.focus())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[n]),k.useEffect(()=>{const b=c.current,N=m.current;if(v&&b&&N){const S=()=>{if(!l.isClosePausedRef.current){const D=new CustomEvent(nwe);N.dispatchEvent(D),l.isClosePausedRef.current=!0}},T=()=>{if(l.isClosePausedRef.current){const D=new CustomEvent(awe);N.dispatchEvent(D),l.isClosePausedRef.current=!1}},A=D=>{!b.contains(D.relatedTarget)&&T()},I=()=>{b.contains(document.activeElement)||T()};return b.addEventListener("focusin",S),b.addEventListener("focusout",A),b.addEventListener("pointermove",S),b.addEventListener("pointerleave",I),window.addEventListener("blur",S),window.addEventListener("focus",T),()=>{b.removeEventListener("focusin",S),b.removeEventListener("focusout",A),b.removeEventListener("pointermove",S),b.removeEventListener("pointerleave",I),window.removeEventListener("blur",S),window.removeEventListener("focus",T)}}},[v,l.isClosePausedRef]);const w=k.useCallback(({tabbingDirection:b})=>{const S=o().map(T=>{const A=T.ref.current,I=[A,...Hjt(A)];return b==="forwards"?I:I.reverse()});return(b==="forwards"?S.reverse():S).flat()},[o]);return k.useEffect(()=>{const b=m.current;if(b){const N=S=>{var I,D,R;const T=S.altKey||S.ctrlKey||S.metaKey;if(S.key==="Tab"&&!T){const $=document.activeElement,F=S.shiftKey;if(S.target===b&&F){(I=d.current)==null||I.focus();return}const K=w({tabbingDirection:F?"backwards":"forwards"}),X=K.findIndex(Z=>Z===$);U0e(K.slice(X+1))?S.preventDefault():F?(D=d.current)==null||D.focus():(R=h.current)==null||R.focus()}};return b.addEventListener("keydown",N),()=>b.removeEventListener("keydown",N)}},[o,w]),e.jsxs(vjt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:v?void 0:"none"},children:[v&&e.jsx(iwe,{ref:d,onFocusFromOutsideViewport:()=>{const b=w({tabbingDirection:"forwards"});U0e(b)}}),e.jsx(aCe.Slot,{scope:r,children:e.jsx(wn.ol,{tabIndex:-1,...i,ref:x})}),v&&e.jsx(iwe,{ref:h,onFocusFromOutsideViewport:()=>{const b=w({tabbingDirection:"backwards"});U0e(b)}})]})});XKe.displayName=ZKe;var QKe="ToastFocusProxy",iwe=k.forwardRef((s,t)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...a}=s,i=Lme(QKe,r);return e.jsx(Ime,{"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))&&n()}})});iwe.displayName=QKe;var zF="Toast",Ljt="toast.swipeStart",Pjt="toast.swipeMove",Djt="toast.swipeCancel",Rjt="toast.swipeEnd",JKe=k.forwardRef((s,t)=>{const{forceMount:r,open:n,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Sh({prop:n,defaultProp:a??!0,onChange:i,caller:zF});return e.jsx(ru,{present:r||o,children:e.jsx(Bjt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:Ed(s.onPause),onResume:Ed(s.onResume),onSwipeStart:Vr(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Vr(s.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:Vr(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:Vr(s.onSwipeEnd,d=>{const{x:h,y:m}=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",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),c(!1)})})})});JKe.displayName=zF;var[Ojt,Fjt]=KKe(zF,{onClose(){}}),Bjt=k.forwardRef((s,t)=>{const{__scopeToast:r,type:n="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:x,onSwipeEnd:y,...v}=s,w=Lme(zF,r),[b,N]=k.useState(null),S=Ga(t,Z=>N(Z)),T=k.useRef(null),A=k.useRef(null),I=a||w.duration,D=k.useRef(0),R=k.useRef(I),$=k.useRef(0),{onToastAdd:F,onToastRemove:z}=w,Q=Ed(()=>{var re;(b==null?void 0:b.contains(document.activeElement))&&((re=w.viewport)==null||re.focus()),l()}),K=k.useCallback(Z=>{!Z||Z===1/0||(window.clearTimeout($.current),D.current=new Date().getTime(),$.current=window.setTimeout(Q,Z))},[Q]);k.useEffect(()=>{const Z=w.viewport;if(Z){const re=()=>{K(R.current),d==null||d()},le=()=>{const oe=new Date().getTime()-D.current;R.current=R.current-oe,window.clearTimeout($.current),c==null||c()};return Z.addEventListener(nwe,le),Z.addEventListener(awe,re),()=>{Z.removeEventListener(nwe,le),Z.removeEventListener(awe,re)}}},[w.viewport,I,c,d,K]),k.useEffect(()=>{i&&!w.isClosePausedRef.current&&K(I)},[i,I,w.isClosePausedRef,K]),k.useEffect(()=>(F(),()=>z()),[F,z]);const X=k.useMemo(()=>b?iYe(b):null,[b]);return w.viewport?e.jsxs(e.Fragment,{children:[X&&e.jsx(zjt,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:X}),e.jsx(Ojt,{scope:r,onClose:Q,children:Vf.createPortal(e.jsx(aCe.ItemSlot,{scope:r,children:e.jsx(yjt,{asChild:!0,onEscapeKeyDown:Vr(o,()=>{w.isFocusedToastEscapeKeyDownRef.current||Q(),w.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(wn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":w.swipeDirection,...v,ref:S,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:Vr(s.onKeyDown,Z=>{Z.key==="Escape"&&(o==null||o(Z.nativeEvent),Z.nativeEvent.defaultPrevented||(w.isFocusedToastEscapeKeyDownRef.current=!0,Q()))}),onPointerDown:Vr(s.onPointerDown,Z=>{Z.button===0&&(T.current={x:Z.clientX,y:Z.clientY})}),onPointerMove:Vr(s.onPointerMove,Z=>{if(!T.current)return;const re=Z.clientX-T.current.x,le=Z.clientY-T.current.y,oe=!!A.current,ne=["left","right"].includes(w.swipeDirection),ie=["left","up"].includes(w.swipeDirection)?Math.min:Math.max,ye=ne?ie(0,re):0,ce=ne?0:ie(0,le),ve=Z.pointerType==="touch"?10:2,be={x:ye,y:ce},Ue={originalEvent:Z,delta:be};oe?(A.current=be,A9(Pjt,m,Ue,{discrete:!1})):eDe(be,w.swipeDirection,ve)?(A.current=be,A9(Ljt,h,Ue,{discrete:!1}),Z.target.setPointerCapture(Z.pointerId)):(Math.abs(re)>ve||Math.abs(le)>ve)&&(T.current=null)}),onPointerUp:Vr(s.onPointerUp,Z=>{const re=A.current,le=Z.target;if(le.hasPointerCapture(Z.pointerId)&&le.releasePointerCapture(Z.pointerId),A.current=null,T.current=null,re){const oe=Z.currentTarget,ne={originalEvent:Z,delta:re};eDe(re,w.swipeDirection,w.swipeThreshold)?A9(Rjt,y,ne,{discrete:!0}):A9(Djt,x,ne,{discrete:!0}),oe.addEventListener("click",ie=>ie.preventDefault(),{once:!0})}})})})}),w.viewport)})]}):null}),zjt=s=>{const{__scopeToast:t,children:r,...n}=s,a=Lme(zF,t),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return qjt(()=>l(!0)),k.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(AI,{asChild:!0,children:e.jsx(Ime,{...n,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",r]})})})},$jt="ToastTitle",eYe=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(wn.div,{...n,ref:t})});eYe.displayName=$jt;var Ujt="ToastDescription",tYe=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s;return e.jsx(wn.div,{...n,ref:t})});tYe.displayName=Ujt;var sYe="ToastAction",rYe=k.forwardRef((s,t)=>{const{altText:r,...n}=s;return r.trim()?e.jsx(aYe,{altText:r,asChild:!0,children:e.jsx(iCe,{...n,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${sYe}\`. Expected non-empty \`string\`.`),null)});rYe.displayName=sYe;var nYe="ToastClose",iCe=k.forwardRef((s,t)=>{const{__scopeToast:r,...n}=s,a=Fjt(nYe,r);return e.jsx(aYe,{asChild:!0,children:e.jsx(wn.button,{type:"button",...n,ref:t,onClick:Vr(s.onClick,a.onClose)})})});iCe.displayName=nYe;var aYe=k.forwardRef((s,t)=>{const{__scopeToast:r,altText:n,...a}=s;return e.jsx(wn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...a,ref:t})});function iYe(s){const t=[];return Array.from(s.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&t.push(n.textContent),Vjt(n)){const a=n.ariaHidden||n.hidden||n.style.display==="none",i=n.dataset.radixToastAnnounceExclude==="";if(!a)if(i){const l=n.dataset.radixToastAnnounceAlt;l&&t.push(l)}else t.push(...iYe(n))}}),t}function A9(s,t,r,{discrete:n}){const a=r.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:r});t&&a.addEventListener(s,t,{once:!0}),n?rCe(a,i):a.dispatchEvent(i)}var eDe=(s,t,r=0)=>{const n=Math.abs(s.x),a=Math.abs(s.y),i=n>a;return t==="left"||t==="right"?i&&n>r:!i&&a>r};function qjt(s=()=>{}){const t=Ed(s);Dd(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[t])}function Vjt(s){return s.nodeType===s.ELEMENT_NODE}function Hjt(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function U0e(s){const t=document.activeElement;return s.some(r=>r===t?!0:(r.focus(),document.activeElement!==t))}var Gjt=YKe,oYe=XKe,lYe=JKe,cYe=eYe,dYe=tYe,uYe=rYe,hYe=iCe;function mYe(s){var t,r,n="";if(typeof s=="string"||typeof s=="number")n+=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,sDe=Fi,r5=(s,t)=>r=>{var n;if((t==null?void 0:t.variants)==null)return sDe(s,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const h=r==null?void 0:r[d],m=i==null?void 0:i[d];if(h===null)return null;const x=tDe(h)||tDe(m);return a[d][x]}),o=r&&Object.entries(r).reduce((d,h)=>{let[m,x]=h;return x===void 0||(d[m]=x),d},{}),c=t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((d,h)=>{let{class:m,className:x,...y}=h;return Object.entries(y).every(v=>{let[w,b]=v;return Array.isArray(b)?b.includes({...i,...o}[w]):{...i,...o}[w]===b})?[...d,m,x]:d},[]);return sDe(s,l,c,r==null?void 0:r.class,r==null?void 0:r.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 Wjt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fYe=(...s)=>s.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).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 Kjt={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 pYe=k.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:l,...o},c)=>k.createElement("svg",{ref:c,...Kjt,width:t,height:t,stroke:s,strokeWidth:n?Number(r)*24/Number(t):r,className:fYe("lucide",a),...o},[...l.map(([d,h])=>k.createElement(d,h)),...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 J=(s,t)=>{const r=k.forwardRef(({className:n,...a},i)=>k.createElement(pYe,{ref:i,iconNode:t,className:fYe(`lucide-${Wjt(s)}`,n),...a}));return r.displayName=`${s}`,r};/** * @license lucide-react v0.462.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=J("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 MU=J("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 IU=J("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 LU=J("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 vh=J("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 PU=J("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 DU=J("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 MN=J("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 IN=J("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 RU=J("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 LN=J("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 OU=J("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 FU=J("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 BU=J("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 zU=J("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 $U=J("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 T4=J("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 UU=J("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 qU=J("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 VU=J("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 HU=J("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 GU=J("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 WU=J("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 KU=J("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 YU=J("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 ZU=J("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 XU=J("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 QU=J("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 E4=J("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 A4=J("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 JU=J("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 eq=J("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 tq=J("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 sq=J("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 rq=J("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 nq=J("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 aq=J("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 iq=J("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 oq=J("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 lq=J("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 cq=J("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 dq=J("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 uq=J("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 hq=J("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 mq=J("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 fq=J("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 pq=J("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 xq=J("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 gq=J("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 yq=J("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 vq=J("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 tR=J("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 bq=J("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 lA=J("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 _q=J("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 Kw=J("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 wq=J("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 jq=J("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 Nq=J("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 kq=J("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 Sq=J("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 Cq=J("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 Tq=J("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 Eq=J("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 Aq=J("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 Mq=J("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 Iq=J("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 PN=J("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 Lq=J("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 Pq=J("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 Dq=J("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 sR=J("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 Rq=J("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 Oq=J("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 Fq=J("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 DN=J("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 RN=J("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 Hu=J("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 Bq=J("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 zq=J("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 $q=J("ArrowLeftToLine",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ka=J("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 Uq=J("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 ub=J("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 qq=J("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 Ha=J("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 Vq=J("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 Hq=J("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 ON=J("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 Ad=J("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 Gq=J("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 Wq=J("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 Kq=J("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 FN=J("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 rR=J("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 Yq=J("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 Zq=J("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 BN=J("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 Id=J("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 Xq=J("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 Qq=J("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 Jq=J("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 eV=J("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 tV=J("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 sV=J("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 Yl=J("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 rV=J("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 zN=J("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 nV=J("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 aV=J("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 iV=J("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 oV=J("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 $N=J("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 lV=J("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 cV=J("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 dV=J("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 uV=J("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 hV=J("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 mV=J("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 fV=J("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 pV=J("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 xV=J("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 gV=J("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 yV=J("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 vV=J("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 bV=J("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 _V=J("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 wV=J("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 nR=J("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 jV=J("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 NV=J("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 kV=J("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 SV=J("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 CV=J("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 Xf=J("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 TV=J("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 EV=J("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 AV=J("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 MV=J("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 IV=J("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 LV=J("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 PV=J("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 DV=J("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 RV=J("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 M4=J("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 OV=J("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 Ny=J("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 FV=J("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 BV=J("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 zV=J("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 $V=J("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 UV=J("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 qV=J("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 ev=J("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 VV=J("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 aR=J("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 _m=J("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 UN=J("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 qN=J("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 HV=J("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 GV=J("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 WV=J("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 KV=J("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 YV=J("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 ZV=J("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 XV=J("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 QV=J("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 JV=J("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 eH=J("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 tH=J("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 sH=J("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 rH=J("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 nH=J("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 aH=J("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 iH=J("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 Yw=J("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 oH=J("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 lH=J("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 cH=J("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 dH=J("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 uH=J("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 hH=J("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 mH=J("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 VN=J("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 fH=J("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 pH=J("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 xH=J("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 gH=J("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 yH=J("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 vH=J("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 bH=J("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 _H=J("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 wH=J("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 jH=J("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 bh=J("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 NH=J("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 kH=J("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 SH=J("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 CH=J("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 TH=J("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 EH=J("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 AH=J("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 MH=J("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 IH=J("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 LH=J("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 iR=J("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 PH=J("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 ag=J("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 DH=J("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 RH=J("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 OH=J("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 cA=J("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 FH=J("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 BH=J("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 HN=J("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 zH=J("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 $H=J("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 UH=J("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 oR=J("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 qH=J("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 VH=J("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 HH=J("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 GH=J("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 Gu=J("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 WH=J("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 KH=J("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 YH=J("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 ZH=J("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 XH=J("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 Sa=J("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 I4=J("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 QH=J("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 JH=J("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 eG=J("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 tG=J("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 sG=J("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 _h=J("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 dA=J("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 rG=J("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 nG=J("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 aG=J("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 iG=J("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 lR=J("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 tv=J("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 oG=J("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 hd=J("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 lG=J("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 cR=J("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 cG=J("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 dG=J("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 dR=J("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 uG=J("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 rb=J("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 hG=J("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 mG=J("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 fG=J("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 pG=J("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 xG=J("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 on=J("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 gG=J("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 Qf=J("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 yG=J("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 vG=J("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 bG=J("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 _G=J("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 wG=J("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 GN=J("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 jG=J("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 NG=J("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 kG=J("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 SG=J("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 CG=J("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 TG=J("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 EG=J("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 AG=J("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 MG=J("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 IG=J("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 LG=J("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 PG=J("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 DG=J("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 WN=J("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 KN=J("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 RG=J("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 OG=J("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 FG=J("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 YN=J("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 ZN=J("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 XN=J("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 BG=J("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 QN=J("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 zG=J("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 ro=J("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 $G=J("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 JN=J("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 UG=J("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 qG=J("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 ek=J("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 tk=J("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 VG=J("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 sk=J("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 rk=J("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 nk=J("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 HG=J("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 uR=J("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 Kn=J("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 GG=J("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 WG=J("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 Wi=J("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 KG=J("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 YG=J("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 $o=J("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 va=J("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 Jf=J("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 ZG=J("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 XG=J("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 QG=J("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 JG=J("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 eW=J("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 tW=J("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 sW=J("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 qp=J("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 rW=J("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 L4=J("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 nW=J("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 aW=J("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 iW=J("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 Oi=J("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 ak=J("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 ik=J("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 ok=J("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 lk=J("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 ck=J("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 dk=J("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 uk=J("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 hk=J("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 di=J("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 In=J("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 mk=J("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 fk=J("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 pk=J("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 xk=J("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 oW=J("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 gk=J("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 lW=J("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 cW=J("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 dW=J("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 uW=J("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 hW=J("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 mW=J("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 fW=J("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 yk=J("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 G1=J("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 vk=J("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 pW=J("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 bk=J("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 _k=J("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 wk=J("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 jk=J("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 rf=J("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 Nk=J("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 kk=J("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 Sk=J("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 xW=J("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 Ck=J("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 Tk=J("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 Ek=J("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 Sc=J("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 Ld=J("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 gW=J("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 yW=J("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 vW=J("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 uA=J("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 bW=J("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 Zw=J("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 _W=J("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 wW=J("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 Ak=J("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 Mk=J("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 jW=J("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 NW=J("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 kW=J("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 SW=J("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 CW=J("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 TW=J("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 EW=J("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 AW=J("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 MW=J("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 IW=J("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 LW=J("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 PW=J("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 DW=J("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 RW=J("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 OW=J("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 FW=J("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 BW=J("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 zW=J("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 $W=J("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 fn=J("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 UW=J("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 qW=J("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 Ik=J("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 VW=J("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 HW=J("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 GW=J("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 WW=J("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 KW=J("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 YW=J("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 ZW=J("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 XW=J("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 QW=J("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 JW=J("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 eK=J("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 tK=J("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 Lk=J("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 sK=J("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 rK=J("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 nb=J("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 nK=J("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 W1=J("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 P4=J("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 aK=J("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 iK=J("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 D4=J("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 oK=J("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 hR=J("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 Pk=J("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 Dk=J("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 lK=J("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 cK=J("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 dK=J("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 hA=J("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 uK=J("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 hK=J("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 mK=J("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 fK=J("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 pK=J("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 Rk=J("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 R4=J("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 xK=J("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 gK=J("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 yK=J("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 vK=J("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 bK=J("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 _K=J("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 wK=J("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 jK=J("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 NK=J("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 Ra=J("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 kK=J("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 SK=J("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 CK=J("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 TK=J("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 EK=J("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 AK=J("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 MK=J("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 IK=J("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 LK=J("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 PK=J("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 DK=J("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 RK=J("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 Vp=J("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 OK=J("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 FK=J("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 BK=J("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 zK=J("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 Zh=J("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 $K=J("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 UK=J("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 qK=J("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 VK=J("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 HK=J("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 GK=J("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 WK=J("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 mR=J("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 KK=J("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 YK=J("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 ZK=J("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 XK=J("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 Ok=J("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 QK=J("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 JK=J("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 eY=J("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 tY=J("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 sY=J("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 rY=J("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 nY=J("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 aY=J("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 iY=J("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 oY=J("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 lY=J("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 cY=J("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 dY=J("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 uY=J("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 hY=J("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 mY=J("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 fY=J("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 pY=J("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 xY=J("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 wl=J("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 gY=J("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 yY=J("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 sv=J("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 vY=J("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 Ya=J("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 bY=J("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 _Y=J("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 wY=J("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 jY=J("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 NY=J("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 ky=J("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 kY=J("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 SY=J("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 CY=J("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 TY=J("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 EY=J("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 AY=J("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 Fk=J("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 MY=J("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 IY=J("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 LY=J("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 mA=J("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 Yx=J("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 Lp=J("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 PY=J("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 DY=J("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 RY=J("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 OY=J("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 FY=J("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 BY=J("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 zY=J("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 Qr=J("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 $Y=J("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 Xh=J("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 bn=J("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 yu=J("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 UY=J("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 qY=J("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 VY=J("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 HY=J("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 GY=J("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 WY=J("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 KY=J("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 YY=J("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 ZY=J("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 XY=J("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 Bk=J("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 QY=J("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 JY=J("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 eZ=J("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 zk=J("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 $k=J("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 Uk=J("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 qk=J("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 tZ=J("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 fR=J("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 sZ=J("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 rZ=J("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 nZ=J("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 Vk=J("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 aZ=J("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 iZ=J("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 O4=J("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 oZ=J("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 hb=J("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 lZ=J("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 cZ=J("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 dZ=J("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 uZ=J("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 hZ=J("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 mZ=J("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 fZ=J("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 pZ=J("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 xZ=J("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 gZ=J("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 yZ=J("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 Hk=J("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 Gk=J("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 vZ=J("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 bZ=J("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 _Z=J("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 wZ=J("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 jZ=J("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 NZ=J("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 kZ=J("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 mb=J("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 pR=J("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 SZ=J("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 CZ=J("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 ln=J("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 TZ=J("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 EZ=J("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 AZ=J("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 MZ=J("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 IZ=J("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 xR=J("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 LZ=J("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 PZ=J("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 DZ=J("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 RZ=J("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 OZ=J("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 fA=J("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 FZ=J("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 gh=J("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 BZ=J("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 Sy=J("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 zZ=J("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 $Z=J("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 UZ=J("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 qZ=J("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 VZ=J("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 HZ=J("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 GZ=J("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 WZ=J("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 fb=J("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 KZ=J("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 mc=J("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 YZ=J("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 ZZ=J("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 XZ=J("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 Xw=J("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 QZ=J("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 JZ=J("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 gR=J("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 eX=J("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 tX=J("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 vy=J("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 sX=J("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 rX=J("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 nX=J("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 aX=J("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 iX=J("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 oX=J("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 lX=J("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 cX=J("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 dX=J("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 Wk=J("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 uX=J("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 hX=J("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 mX=J("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 fX=J("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 pX=J("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 xX=J("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 gX=J("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 yX=J("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 vX=J("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 bX=J("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 _X=J("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 Qh=J("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 wX=J("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 Kk=J("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 jX=J("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 NX=J("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 kX=J("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 SX=J("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 CX=J("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 TX=J("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 EX=J("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 AX=J("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 MX=J("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 IX=J("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 LX=J("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 PX=J("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 DX=J("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 RX=J("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 OX=J("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 FX=J("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 BX=J("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 zX=J("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 $X=J("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 UX=J("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 qX=J("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 VX=J("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 HX=J("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 GX=J("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 WX=J("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 KX=J("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 YX=J("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 ZX=J("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 XX=J("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 F4=J("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 ii=J("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 QX=J("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 JX=J("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 Yk=J("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 eQ=J("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 tQ=J("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 sQ=J("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 rQ=J("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 nQ=J("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 aQ=J("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 iQ=J("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 oQ=J("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 lQ=J("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 cQ=J("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 dQ=J("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 uQ=J("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 hQ=J("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 mQ=J("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 fQ=J("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 pQ=J("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 xQ=J("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 fc=J("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 gQ=J("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 yQ=J("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 Md=J("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 vQ=J("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 bQ=J("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 Zk=J("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 _Q=J("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 Xk=J("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 Bx=J("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 wQ=J("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 vu=J("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 jQ=J("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 NQ=J("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 kQ=J("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 SQ=J("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 yR=J("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 CQ=J("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 TQ=J("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 fy=J("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 EQ=J("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 AQ=J("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 vR=J("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 Qw=J("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 MQ=J("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 IQ=J("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 bR=J("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 LQ=J("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 Jw=J("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 PQ=J("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 DQ=J("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 pA=J("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 xA=J("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 _R=J("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 RQ=J("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 OQ=J("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 FQ=J("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 BQ=J("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 zQ=J("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 $Q=J("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 UQ=J("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 qQ=J("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 VQ=J("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 HQ=J("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 GQ=J("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 ci=J("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 WQ=J("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 KQ=J("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 YQ=J("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 gA=J("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 ZQ=J("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 XQ=J("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 QQ=J("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 JQ=J("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 eJ=J("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 tJ=J("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 sJ=J("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 En=J("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 Qk=J("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 Jk=J("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 rJ=J("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 nJ=J("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 aJ=J("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 iJ=J("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 oJ=J("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 rv=J("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 lJ=J("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 cJ=J("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 ml=J("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 dJ=J("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 uJ=J("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 ej=J("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 eS=J("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 tS=J("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 hJ=J("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 mJ=J("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 B4=J("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 fJ=J("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 Jd=J("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 tj=J("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 pJ=J("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 xJ=J("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 gJ=J("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 yJ=J("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 nv=J("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 z4=J("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 vJ=J("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 ep=J("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 bJ=J("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 _J=J("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 wJ=J("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 jJ=J("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 NJ=J("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 kJ=J("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 SJ=J("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 CJ=J("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 TJ=J("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 EJ=J("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 AJ=J("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 MJ=J("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 IJ=J("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 sS=J("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 LJ=J("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 PJ=J("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 DJ=J("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 RJ=J("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 OJ=J("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 FJ=J("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 wR=J("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 $4=J("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 xf=J("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 BJ=J("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 zJ=J("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 $J=J("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 U4=J("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 UJ=J("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 qJ=J("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 VJ=J("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 HJ=J("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 GJ=J("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 q4=J("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 yA=J("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 WJ=J("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 KJ=J("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 sj=J("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 YJ=J("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 tl=J("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 po=J("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 Jh=J("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 ZJ=J("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 pb=J("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 XJ=J("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 QJ=J("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 jR=J("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 JJ=J("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 eee=J("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 Cy=J("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 tee=J("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 see=J("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 ree=J("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 nee=J("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 aee=J("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 iee=J("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 oee=J("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 em=J("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 es=J("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 lee=J("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 cee=J("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 dee=J("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 uee=J("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 vA=J("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 rS=J("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 hee=J("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 nS=J("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 Hc=J("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 V4=J("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 bA=J("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 mee=J("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 fee=J("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 pee=J("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 xee=J("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 gee=J("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 yee=J("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 NR=J("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 kR=J("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 vee=J("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 bee=J("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 _ee=J("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 _A=J("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=J("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 wee=J("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 jee=J("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 Nee=J("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 kee=J("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 See=J("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 Cee=J("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 Tee=J("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 Eee=J("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 Aee=J("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 Mee=J("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 Iee=J("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 Lee=J("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 Ca=J("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 Pee=J("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 H4=J("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 Dee=J("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 Ree=J("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 SR=J("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 xb=J("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 Oee=J("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 bu=J("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 Fee=J("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 Bee=J("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 G4=J("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 zee=J("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 $ee=J("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 Uee=J("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 wA=J("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 qee=J("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 Vee=J("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 Hee=J("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 CR=J("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 Gee=J("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 Wee=J("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 Kee=J("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 Jl=J("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 Yee=J("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 Zee=J("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 Xee=J("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 Qee=J("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 Jee=J("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 ete=J("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 TR=J("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 tte=J("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 V0=J("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 ER=J("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 ste=J("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 rte=J("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 nte=J("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 ate=J("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 ite=J("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 xi=J("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 ote=J("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 lte=J("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 aS=J("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 W4=J("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 cte=J("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 dte=J("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 ute=J("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 hte=J("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 mte=J("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 fte=J("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 pte=J("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 xte=J("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 av=J("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 gte=J("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 yte=J("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 vte=J("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 bte=J("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 _te=J("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 wte=J("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 AR=J("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 jte=J("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 Nte=J("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 kte=J("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 K4=J("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 Ste=J("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 rj=J("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 Cte=J("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 Tte=J("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 Ete=J("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 Ate=J("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 Mte=J("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 Ite=J("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 Lte=J("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 qc=J("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 Bu=J("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 Pte=J("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 iS=J("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 Dte=J("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 Rte=J("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 Ote=J("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 Fte=J("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 Bte=J("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 zte=J("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 $te=J("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 Ute=J("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 qte=J("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 Vte=J("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 Hte=J("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 Gte=J("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 Wte=J("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 Kte=J("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 Yte=J("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 Zte=J("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 Xte=J("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 Qte=J("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 Jte=J("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 ese=J("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 MR=J("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 tse=J("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 iv=J("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 sse=J("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 rse=J("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 nse=J("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 ase=J("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 ise=J("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 ose=J("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 lse=J("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 cse=J("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 dse=J("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 K1=J("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 use=J("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 oS=J("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 lS=J("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 hse=J("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 mse=J("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 fse=J("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 pse=J("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 xse=J("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 gse=J("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 yse=J("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 vse=J("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 bse=J("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 _se=J("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 wse=J("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 jse=J("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 Il=J("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 Nse=J("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 kse=J("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 cS=J("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 Sse=J("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=J("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 Cse=J("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 dS=J("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 Tse=J("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 Ese=J("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 uS=J("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 hS=J("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 mS=J("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 fS=J("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 Ase=J("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 pS=J("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 Mse=J("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 Ise=J("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 Lse=J("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 xS=J("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 Pse=J("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 Dse=J("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 Rse=J("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 Ose=J("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 Y1=J("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 nj=J("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 Fse=J("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 Bse=J("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 eu=J("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 tm=J("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 zse=J("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 $se=J("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 D0=J("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 Use=J("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 aj=J("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 R0=J("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 qse=J("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 Vse=J("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 Hse=J("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 Ea=J("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 Gse=J("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 Y4=J("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 Wse=J("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 Kse=J("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 Yse=J("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 Zse=J("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 Xse=J("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 Qse=J("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 Jse=J("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 ere=J("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 Cn=J("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 tre=J("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 sre=J("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 rre=J("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 nre=J("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 are=J("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 ire=J("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 ore=J("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 lre=J("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 cre=J("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 dre=J("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 ure=J("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 IR=J("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 ij=J("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 hre=J("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 mre=J("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 fre=J("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 pre=J("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 LR=J("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 Uo=J("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 xre=J("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 gS=J("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 Z4=J("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 $s=J("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 gre=J("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 yre=J("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 vre=J("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 bre=J("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 _re=J("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 wre=J("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 jre=J("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 Nre=J("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 kre=J("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 PR=J("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 Ty=J("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 Sre=J("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 DR=J("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 Cre=J("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 Tre=J("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 Ere=J("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 Are=J("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 ov=J("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 X4=J("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 Mre=J("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 jA=J("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 Ire=J("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 Lre=J("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 Pre=J("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 Dre=J("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 gb=J("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 Rre=J("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 Ore=J("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 Fre=J("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 Bre=J("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 zre=J("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 $re=J("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 Ure=J("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 qre=J("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 Vre=J("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 Hre=J("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 Gre=J("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 Wre=J("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 Kre=J("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 Yre=J("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 yS=J("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 Zre=J("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 Xre=J("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 Qre=J("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 Jre=J("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 ene=J("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 oj=J("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 tne=J("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 NA=J("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 sne=J("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 Mi=J("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 rne=J("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 nne=J("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 ane=J("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 ine=J("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 one=J("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 RR=J("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 lne=J("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 cne=J("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 dne=J("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 OR=J("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 une=J("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 hne=J("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 lv=J("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 mne=J("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 fne=J("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 vS=J("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 pne=J("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 cv=J("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 xne=J("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 Q4=J("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 gne=J("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 yne=J("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 vne=J("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 bS=J("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 _S=J("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 bne=J("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 _ne=J("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 J4=J("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 wne=J("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 jne=J("Sailboat",[["path",{d:"M22 18H2a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4Z",key:"1404fh"}],["path",{d:"M21 14 10 2 3 14h18Z",key:"1nzg7v"}],["path",{d:"M10 2v16",key:"1labyt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nne=J("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 kne=J("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 Sne=J("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 Cne=J("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 Tne=J("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 Ene=J("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 Bl=J("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 wS=J("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 FR=J("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 Ane=J("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 Mne=J("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 Ine=J("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 Lne=J("ScanFace",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 9h.01",key:"x1ddxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pne=J("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 Dne=J("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 Rne=J("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 One=J("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 Fne=J("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 Bne=J("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 zne=J("ScissorsLineDashed",[["path",{d:"M5.42 9.42 8 12",key:"12pkuq"}],["circle",{cx:"4",cy:"8",r:"2",key:"107mxr"}],["path",{d:"m14 6-8.58 8.58",key:"gvzu5l"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"M10.8 14.8 14 18",key:"ax7m9r"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ne=J("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 Une=J("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 qne=J("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 Vne=J("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 Hne=J("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 Gne=J("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 Wne=J("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 Kne=J("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 BR=J("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 yn=J("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 Yne=J("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 jS=J("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 Zne=J("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 en=J("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 Xne=J("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 Qne=J("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 Jne=J("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 eae=J("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 tae=J("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 sae=J("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 zR=J("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 oo=J("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 rae=J("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 Ec=J("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 $R=J("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 nae=J("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 aae=J("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 UR=J("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 iae=J("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 Ey=J("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 oae=J("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 lae=J("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 cae=J("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 e3=J("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 dae=J("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 uae=J("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 NS=J("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 Wu=J("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 hae=J("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 mae=J("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 fae=J("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 dv=J("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 pae=J("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 Hf=J("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 xae=J("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 gae=J("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 yae=J("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 vae=J("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 t3=J("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 bae=J("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 _ae=J("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 wae=J("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 jae=J("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 Nae=J("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 kae=J("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 Sae=J("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 Cae=J("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 Tae=J("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 Eae=J("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 Aae=J("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 Mae=J("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 Iae=J("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 Lae=J("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 Pae=J("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 Dae=J("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 s3=J("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 kS=J("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 Rae=J("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 Oae=J("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 ig=J("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 Fae=J("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 Bae=J("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 zae=J("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 H0=J("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 $ae=J("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 Uae=J("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 qae=J("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 Vae=J("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 Hae=J("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 jr=J("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 Gae=J("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 Wae=J("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 Kae=J("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 Yae=J("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 Zae=J("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 Xae=J("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 Qae=J("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 r3=J("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 SS=J("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 CS=J("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 TS=J("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 ES=J("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 AS=J("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 MS=J("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 IS=J("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 LS=J("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 PS=J("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 DS=J("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 RS=J("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 OS=J("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 FS=J("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 BS=J("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 zS=J("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 j0=J("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 Z1=J("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 $S=J("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 US=J("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 qS=J("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 VS=J("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 HS=J("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 GS=J("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 Jae=J("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 eie=J("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 WS=J("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 KS=J("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 YS=J("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 ZS=J("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 XS=J("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 QS=J("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 JS=J("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 eC=J("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 tC=J("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 sC=J("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 rC=J("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 nC=J("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 aC=J("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 iC=J("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 oC=J("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 sd=J("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 lC=J("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 cC=J("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 dC=J("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 uC=J("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 hC=J("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 mC=J("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 tie=J("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 fC=J("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 pC=J("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 xC=J("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 gC=J("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 yC=J("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 sie=J("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 rie=J("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 vC=J("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 bC=J("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 _C=J("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 wC=J("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 og=J("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 nie=J("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 aie=J("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 iie=J("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 oie=J("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 lie=J("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 Xn=J("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 cie=J("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 die=J("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 uie=J("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 hie=J("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 mie=J("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 fie=J("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 pie=J("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 xie=J("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 qR=J("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 gie=J("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 yie=J("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 vie=J("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 bie=J("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 _ie=J("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=J("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 wie=J("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 jie=J("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 Nie=J("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 kie=J("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 Sie=J("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 Cie=J("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 Tie=J("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 Eie=J("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 Aie=J("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 kA=J("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 Mie=J("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 Iie=J("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 Lie=J("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 Pie=J("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 Die=J("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 Rie=J("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 SA=J("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 Oie=J("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 Fie=J("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 Bie=J("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 wh=J("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 zie=J("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 $ie=J("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 Uie=J("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 qie=J("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 Vie=J("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 Hie=J("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 Gie=J("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 Pd=J("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 Wie=J("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 Kie=J("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 Yie=J("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 Zie=J("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 jC=J("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 Xie=J("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 Qie=J("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 Jie=J("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 eoe=J("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 toe=J("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 soe=J("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 NC=J("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 roe=J("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 noe=J("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 aoe=J("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 ioe=J("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 ooe=J("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 VR=J("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 jh=J("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 loe=J("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 coe=J("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 doe=J("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 uoe=J("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 hoe=J("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 moe=J("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 HR=J("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 foe=J("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 poe=J("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 xoe=J("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 goe=J("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 yoe=J("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 voe=J("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 boe=J("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 _oe=J("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 woe=J("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 joe=J("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 Noe=J("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 koe=J("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 Soe=J("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 Coe=J("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 Toe=J("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 Eoe=J("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 Aoe=J("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 Moe=J("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 Ioe=J("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 kC=J("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 yr=J("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 Loe=J("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 Poe=J("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 SC=J("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 lj=J("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 Doe=J("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 Roe=J("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=J("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 Ooe=J("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 bo=J("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 id=J("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 Foe=J("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 Boe=J("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 Gi=J("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 GR=J("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 zoe=J("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 $oe=J("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 CC=J("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 Uoe=J("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 qoe=J("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 Voe=J("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 Hoe=J("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 Goe=J("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 Woe=J("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 Koe=J("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 CA=J("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 Yoe=J("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 Zoe=J("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 cj=J("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 Xoe=J("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 Qoe=J("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 Joe=J("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 TC=J("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 ele=J("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 n3=J("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 tle=J("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 da=J("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 sle=J("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 uv=J("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 WR=J("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 KR=J("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 rle=J("UserPen",[["path",{d:"M11.5 15H7a4 4 0 0 0-4 4v2",key:"15lzij"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sl=J("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 EC=J("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 AC=J("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 MC=J("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 nle=J("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 IC=J("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 ale=J("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 LC=J("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 PC=J("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 ile=J("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 ole=J("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 Di=J("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 DC=J("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 pr=J("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 RC=J("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 OC=J("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 lle=J("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 TA=J("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 cle=J("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 dle=J("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 ule=J("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 hle=J("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 mle=J("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 fle=J("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 Jr=J("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 ple=J("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 xle=J("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 gle=J("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 yle=J("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 vle=J("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 YR=J("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 ble=J("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 ZR=J("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 _le=J("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 wle=J("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 jle=J("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 FC=J("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 XR=J("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 Nle=J("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 Zx=J("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 kle=J("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 Sle=J("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 Cle=J("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 Tle=J("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 Ele=J("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 Ale=J("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 Mle=J("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 Ile=J("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 Lle=J("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 Ple=J("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 Dle=J("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 Rle=J("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 Ole=J("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 Fle=J("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 Ble=J("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 zle=J("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 $le=J("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 Ule=J("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 qle=J("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 Vle=J("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 Hle=J("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 Gle=J("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 QR=J("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 Wle=J("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 Kle=J("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 Ay=J("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 vr=J("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 Yle=J("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 Zle=J("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 Ku=J("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 dj=J("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 EA=J("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 Yjt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:AU,AArrowUp:MU,ALargeSmall:IU,Accessibility:LU,Activity:vh,AirVent:PU,Airplay:DU,AlarmClock:OU,AlarmClockCheck:MN,AlarmClockMinus:IN,AlarmClockOff:RU,AlarmClockPlus:LN,AlarmSmoke:FU,Album:BU,AlignCenter:T4,AlignCenterHorizontal:zU,AlignCenterVertical:$U,AlignEndHorizontal:UU,AlignEndVertical:qU,AlignHorizontalDistributeCenter:VU,AlignHorizontalDistributeEnd:HU,AlignHorizontalDistributeStart:GU,AlignHorizontalJustifyCenter:WU,AlignHorizontalJustifyEnd:KU,AlignHorizontalJustifyStart:YU,AlignHorizontalSpaceAround:ZU,AlignHorizontalSpaceBetween:XU,AlignJustify:QU,AlignLeft:E4,AlignRight:A4,AlignStartHorizontal:JU,AlignStartVertical:eq,AlignVerticalDistributeCenter:tq,AlignVerticalDistributeEnd:sq,AlignVerticalDistributeStart:rq,AlignVerticalJustifyCenter:nq,AlignVerticalJustifyEnd:aq,AlignVerticalJustifyStart:iq,AlignVerticalSpaceAround:oq,AlignVerticalSpaceBetween:lq,Ambulance:cq,Ampersand:dq,Ampersands:uq,Amphora:hq,Anchor:mq,Angry:fq,Annoyed:pq,Antenna:xq,Anvil:gq,Aperture:yq,AppWindow:tR,AppWindowMac:vq,Apple:bq,Archive:Kw,ArchiveRestore:lA,ArchiveX:_q,Armchair:wq,ArrowBigDown:Nq,ArrowBigDownDash:jq,ArrowBigLeft:Sq,ArrowBigLeftDash:kq,ArrowBigRight:Tq,ArrowBigRightDash:Cq,ArrowBigUp:Aq,ArrowBigUpDash:Eq,ArrowDown:Hu,ArrowDown01:Mq,ArrowDown10:Iq,ArrowDownAZ:PN,ArrowDownFromLine:Lq,ArrowDownLeft:Pq,ArrowDownNarrowWide:Dq,ArrowDownRight:sR,ArrowDownToDot:Rq,ArrowDownToLine:Oq,ArrowDownUp:Fq,ArrowDownWideNarrow:DN,ArrowDownZA:RN,ArrowLeft:ka,ArrowLeftFromLine:Bq,ArrowLeftRight:zq,ArrowLeftToLine:$q,ArrowRight:Ha,ArrowRightFromLine:Uq,ArrowRightLeft:ub,ArrowRightToLine:qq,ArrowUp:Id,ArrowUp01:Vq,ArrowUp10:Hq,ArrowUpAZ:ON,ArrowUpDown:Ad,ArrowUpFromDot:Gq,ArrowUpFromLine:Wq,ArrowUpLeft:Kq,ArrowUpNarrowWide:FN,ArrowUpRight:rR,ArrowUpToLine:Yq,ArrowUpWideNarrow:Zq,ArrowUpZA:BN,ArrowsUpFromLine:Xq,Asterisk:Qq,AtSign:Jq,Atom:eV,AudioLines:tV,AudioWaveform:sV,Award:Yl,Axe:rV,Axis3d:zN,Baby:nV,Backpack:aV,Badge:_V,BadgeAlert:iV,BadgeCent:oV,BadgeCheck:$N,BadgeDollarSign:lV,BadgeEuro:cV,BadgeHelp:dV,BadgeIndianRupee:uV,BadgeInfo:hV,BadgeJapaneseYen:mV,BadgeMinus:fV,BadgePercent:pV,BadgePlus:xV,BadgePoundSterling:gV,BadgeRussianRuble:yV,BadgeSwissFranc:vV,BadgeX:bV,BaggageClaim:wV,Ban:nR,Banana:jV,Bandage:NV,Banknote:kV,Barcode:SV,Baseline:CV,Bath:Xf,Battery:LV,BatteryCharging:TV,BatteryFull:EV,BatteryLow:AV,BatteryMedium:MV,BatteryWarning:IV,Beaker:PV,Bean:RV,BeanOff:DV,Bed:Ny,BedDouble:M4,BedSingle:OV,Beef:FV,Beer:zV,BeerOff:BV,Bell:_m,BellDot:$V,BellElectric:UV,BellMinus:qV,BellOff:ev,BellPlus:VV,BellRing:aR,BetweenHorizontalEnd:UN,BetweenHorizontalStart:qN,BetweenVerticalEnd:HV,BetweenVerticalStart:GV,BicepsFlexed:WV,Bike:KV,Binary:YV,Binoculars:ZV,Biohazard:XV,Bird:QV,Bitcoin:JV,Blend:eH,Blinds:tH,Blocks:sH,Bluetooth:iH,BluetoothConnected:rH,BluetoothOff:nH,BluetoothSearching:aH,Bold:Yw,Bolt:oH,Bomb:lH,Bone:cH,Book:MH,BookA:dH,BookAudio:uH,BookCheck:hH,BookCopy:mH,BookDashed:VN,BookDown:fH,BookHeadphones:pH,BookHeart:xH,BookImage:gH,BookKey:yH,BookLock:vH,BookMarked:bH,BookMinus:_H,BookOpen:bh,BookOpenCheck:wH,BookOpenText:jH,BookPlus:NH,BookText:kH,BookType:SH,BookUp:TH,BookUp2:CH,BookUser:EH,BookX:AH,Bookmark:ag,BookmarkCheck:IH,BookmarkMinus:LH,BookmarkPlus:iR,BookmarkX:PH,BoomBox:DH,Bot:cA,BotMessageSquare:RH,BotOff:OH,Box:FH,Boxes:BH,Braces:HN,Brackets:zH,Brain:oR,BrainCircuit:$H,BrainCog:UH,BrickWall:qH,Briefcase:Gu,BriefcaseBusiness:VH,BriefcaseConveyorBelt:HH,BriefcaseMedical:GH,BringToFront:WH,Brush:KH,Bug:XH,BugOff:YH,BugPlay:ZH,Building:I4,Building2:Sa,Bus:JH,BusFront:QH,Cable:tG,CableCar:eG,Cake:_h,CakeSlice:sG,Calculator:dA,Calendar:on,Calendar1:rG,CalendarArrowDown:nG,CalendarArrowUp:aG,CalendarCheck:lR,CalendarCheck2:iG,CalendarClock:tv,CalendarCog:oG,CalendarDays:hd,CalendarFold:lG,CalendarHeart:cR,CalendarMinus:dG,CalendarMinus2:cG,CalendarOff:dR,CalendarPlus:rb,CalendarPlus2:uG,CalendarRange:hG,CalendarSearch:mG,CalendarSync:fG,CalendarX:xG,CalendarX2:pG,Camera:Qf,CameraOff:gG,Candy:bG,CandyCane:yG,CandyOff:vG,Cannabis:_G,Captions:GN,CaptionsOff:wG,Car:kG,CarFront:jG,CarTaxiFront:NG,Caravan:SG,Carrot:CG,CaseLower:TG,CaseSensitive:EG,CaseUpper:AG,CassetteTape:MG,Cast:IG,Castle:LG,Cat:PG,Cctv:DG,ChartArea:WN,ChartBar:YN,ChartBarBig:KN,ChartBarDecreasing:RG,ChartBarIncreasing:OG,ChartBarStacked:FG,ChartCandlestick:ZN,ChartColumn:ro,ChartColumnBig:XN,ChartColumnDecreasing:BG,ChartColumnIncreasing:QN,ChartColumnStacked:zG,ChartGantt:$G,ChartLine:JN,ChartNetwork:UG,ChartNoAxesColumn:tk,ChartNoAxesColumnDecreasing:qG,ChartNoAxesColumnIncreasing:ek,ChartNoAxesCombined:VG,ChartNoAxesGantt:sk,ChartPie:rk,ChartScatter:nk,ChartSpline:HG,Check:Kn,CheckCheck:uR,ChefHat:GG,Cherry:WG,ChevronDown:Wi,ChevronFirst:KG,ChevronLast:YG,ChevronLeft:$o,ChevronRight:va,ChevronUp:Jf,ChevronsDown:XG,ChevronsDownUp:ZG,ChevronsLeft:eW,ChevronsLeftRight:JG,ChevronsLeftRightEllipsis:QG,ChevronsRight:sW,ChevronsRightLeft:tW,ChevronsUp:rW,ChevronsUpDown:qp,Chrome:L4,Church:nW,Cigarette:iW,CigaretteOff:aW,Circle:Ld,CircleAlert:Oi,CircleArrowDown:ak,CircleArrowLeft:ik,CircleArrowOutDownLeft:ok,CircleArrowOutDownRight:lk,CircleArrowOutUpLeft:ck,CircleArrowOutUpRight:dk,CircleArrowRight:uk,CircleArrowUp:hk,CircleCheck:In,CircleCheckBig:di,CircleChevronDown:mk,CircleChevronLeft:fk,CircleChevronRight:pk,CircleChevronUp:xk,CircleDashed:oW,CircleDivide:gk,CircleDollarSign:lW,CircleDot:dW,CircleDotDashed:cW,CircleEllipsis:uW,CircleEqual:hW,CircleFadingArrowUp:mW,CircleFadingPlus:fW,CircleGauge:yk,CircleHelp:G1,CircleMinus:vk,CircleOff:pW,CircleParking:_k,CircleParkingOff:bk,CirclePause:wk,CirclePercent:jk,CirclePlay:rf,CirclePlus:Nk,CirclePower:kk,CircleSlash:xW,CircleSlash2:Sk,CircleStop:Ck,CircleUser:Ek,CircleUserRound:Tk,CircleX:Sc,CircuitBoard:gW,Citrus:yW,Clapperboard:vW,Clipboard:SW,ClipboardCheck:uA,ClipboardCopy:bW,ClipboardList:Zw,ClipboardMinus:_W,ClipboardPaste:wW,ClipboardPen:Mk,ClipboardPenLine:Ak,ClipboardPlus:jW,ClipboardType:NW,ClipboardX:kW,Clock:fn,Clock1:CW,Clock10:TW,Clock11:EW,Clock12:AW,Clock2:MW,Clock3:IW,Clock4:LW,Clock5:PW,Clock6:DW,Clock7:RW,Clock8:OW,Clock9:FW,ClockAlert:BW,ClockArrowDown:zW,ClockArrowUp:$W,Cloud:sK,CloudAlert:UW,CloudCog:qW,CloudDownload:Ik,CloudDrizzle:VW,CloudFog:HW,CloudHail:GW,CloudLightning:WW,CloudMoon:YW,CloudMoonRain:KW,CloudOff:ZW,CloudRain:QW,CloudRainWind:XW,CloudSnow:JW,CloudSun:tK,CloudSunRain:eK,CloudUpload:Lk,Cloudy:rK,Clover:nb,Club:nK,Code:P4,CodeXml:W1,Codepen:aK,Codesandbox:iK,Coffee:D4,Cog:oK,Coins:hR,Columns2:Pk,Columns3:Dk,Columns4:lK,Combine:cK,Command:dK,Compass:hA,Component:uK,Computer:hK,ConciergeBell:mK,Cone:fK,Construction:pK,Contact:R4,ContactRound:Rk,Container:xK,Contrast:gK,Cookie:yK,CookingPot:vK,Copy:Ra,CopyCheck:bK,CopyMinus:_K,CopyPlus:wK,CopySlash:jK,CopyX:NK,Copyleft:kK,Copyright:SK,CornerDownLeft:CK,CornerDownRight:TK,CornerLeftDown:EK,CornerLeftUp:AK,CornerRightDown:MK,CornerRightUp:IK,CornerUpLeft:LK,CornerUpRight:PK,Cpu:DK,CreativeCommons:RK,CreditCard:Vp,Croissant:OK,Crop:FK,Cross:BK,Crosshair:zK,Crown:Zh,Cuboid:$K,CupSoda:UK,Currency:qK,Cylinder:VK,Dam:HK,Database:mR,DatabaseBackup:GK,DatabaseZap:WK,Delete:KK,Dessert:YK,Diameter:ZK,Diamond:JK,DiamondMinus:XK,DiamondPercent:Ok,DiamondPlus:QK,Dice1:eY,Dice2:tY,Dice3:sY,Dice4:rY,Dice5:nY,Dice6:aY,Dices:iY,Diff:oY,Disc:uY,Disc2:lY,Disc3:cY,DiscAlbum:dY,Divide:hY,Dna:fY,DnaOff:mY,Dock:pY,Dog:xY,DollarSign:wl,Donut:gY,DoorClosed:yY,DoorOpen:sv,Dot:vY,Download:Ya,DraftingCompass:bY,Drama:_Y,Dribbble:wY,Drill:jY,Droplet:NY,Droplets:ky,Drum:kY,Drumstick:SY,Dumbbell:CY,Ear:EY,EarOff:TY,Earth:Fk,EarthLock:AY,Eclipse:MY,Egg:mA,EggFried:IY,EggOff:LY,Ellipsis:Lp,EllipsisVertical:Yx,Equal:RY,EqualApproximately:PY,EqualNot:DY,Eraser:OY,EthernetPort:FY,Euro:BY,Expand:zY,ExternalLink:Qr,Eye:bn,EyeClosed:$Y,EyeOff:Xh,Facebook:yu,Factory:UY,Fan:qY,FastForward:VY,Feather:HY,Fence:GY,FerrisWheel:WY,Figma:KY,File:fA,FileArchive:YY,FileAudio:XY,FileAudio2:ZY,FileAxis3d:Bk,FileBadge:JY,FileBadge2:QY,FileBox:eZ,FileChartColumn:$k,FileChartColumnIncreasing:zk,FileChartLine:Uk,FileChartPie:qk,FileCheck:fR,FileCheck2:tZ,FileClock:sZ,FileCode:nZ,FileCode2:rZ,FileCog:Vk,FileDiff:aZ,FileDigit:iZ,FileDown:O4,FileHeart:oZ,FileImage:hb,FileInput:lZ,FileJson:dZ,FileJson2:cZ,FileKey:hZ,FileKey2:uZ,FileLock:fZ,FileLock2:mZ,FileMinus:xZ,FileMinus2:pZ,FileMusic:gZ,FileOutput:yZ,FilePen:Gk,FilePenLine:Hk,FilePlus:bZ,FilePlus2:vZ,FileQuestion:_Z,FileScan:wZ,FileSearch:NZ,FileSearch2:jZ,FileSliders:kZ,FileSpreadsheet:mb,FileStack:pR,FileSymlink:SZ,FileTerminal:CZ,FileText:ln,FileType:EZ,FileType2:TZ,FileUp:AZ,FileUser:MZ,FileVideo:xR,FileVideo2:IZ,FileVolume:PZ,FileVolume2:LZ,FileWarning:DZ,FileX:OZ,FileX2:RZ,Files:FZ,Film:gh,Filter:Sy,FilterX:BZ,Fingerprint:zZ,FireExtinguisher:$Z,Fish:VZ,FishOff:UZ,FishSymbol:qZ,Flag:fb,FlagOff:HZ,FlagTriangleLeft:GZ,FlagTriangleRight:WZ,Flame:mc,FlameKindling:KZ,Flashlight:ZZ,FlashlightOff:YZ,FlaskConical:Xw,FlaskConicalOff:XZ,FlaskRound:QZ,FlipHorizontal:gR,FlipHorizontal2:JZ,FlipVertical:tX,FlipVertical2:eX,Flower:sX,Flower2:vy,Focus:rX,FoldHorizontal:nX,FoldVertical:aX,Folder:IX,FolderArchive:iX,FolderCheck:oX,FolderClock:lX,FolderClosed:cX,FolderCode:dX,FolderCog:Wk,FolderDot:uX,FolderDown:hX,FolderGit:fX,FolderGit2:mX,FolderHeart:pX,FolderInput:xX,FolderKanban:gX,FolderKey:yX,FolderLock:vX,FolderMinus:bX,FolderOpen:Qh,FolderOpenDot:_X,FolderOutput:wX,FolderPen:Kk,FolderPlus:jX,FolderRoot:NX,FolderSearch:SX,FolderSearch2:kX,FolderSymlink:CX,FolderSync:TX,FolderTree:EX,FolderUp:AX,FolderX:MX,Folders:LX,Footprints:PX,Forklift:DX,Forward:RX,Frame:OX,Framer:FX,Frown:BX,Fuel:zX,Fullscreen:$X,GalleryHorizontal:qX,GalleryHorizontalEnd:UX,GalleryThumbnails:VX,GalleryVertical:GX,GalleryVerticalEnd:HX,Gamepad:KX,Gamepad2:WX,Gauge:YX,Gavel:ZX,Gem:XX,Ghost:F4,Gift:ii,GitBranch:JX,GitBranchPlus:QX,GitCommitHorizontal:Yk,GitCommitVertical:eQ,GitCompare:sQ,GitCompareArrows:tQ,GitFork:rQ,GitGraph:nQ,GitMerge:aQ,GitPullRequest:uQ,GitPullRequestArrow:iQ,GitPullRequestClosed:oQ,GitPullRequestCreate:cQ,GitPullRequestCreateArrow:lQ,GitPullRequestDraft:dQ,Github:hQ,Gitlab:mQ,GlassWater:fQ,Glasses:pQ,Globe:fc,GlobeLock:xQ,Goal:gQ,Grab:yQ,GraduationCap:Md,Grape:vQ,Grid2x2:Xk,Grid2x2Check:bQ,Grid2x2Plus:Zk,Grid2x2X:_Q,Grid3x3:Bx,Grip:jQ,GripHorizontal:wQ,GripVertical:vu,Group:NQ,Guitar:kQ,Ham:SQ,Hammer:yR,Hand:vR,HandCoins:CQ,HandHeart:TQ,HandHelping:fy,HandMetal:EQ,HandPlatter:AQ,Handshake:Qw,HardDrive:bR,HardDriveDownload:MQ,HardDriveUpload:IQ,HardHat:LQ,Hash:Jw,Haze:PQ,HdmiPort:DQ,Heading:BQ,Heading1:pA,Heading2:xA,Heading3:_R,Heading4:RQ,Heading5:OQ,Heading6:FQ,HeadphoneOff:zQ,Headphones:$Q,Headset:UQ,Heart:ci,HeartCrack:qQ,HeartHandshake:VQ,HeartOff:HQ,HeartPulse:GQ,Heater:WQ,Hexagon:KQ,Highlighter:YQ,History:gA,Hop:XQ,HopOff:ZQ,Hospital:QQ,Hotel:JQ,Hourglass:eJ,House:En,HousePlug:tJ,HousePlus:sJ,IceCreamBowl:Qk,IceCreamCone:Jk,IdCard:rJ,Image:ml,ImageDown:nJ,ImageMinus:aJ,ImageOff:iJ,ImagePlay:oJ,ImagePlus:rv,ImageUp:lJ,ImageUpscale:cJ,Images:dJ,Import:uJ,Inbox:ej,IndentDecrease:eS,IndentIncrease:tS,IndianRupee:hJ,Infinity:mJ,Info:B4,InspectionPanel:fJ,Instagram:Jd,Italic:tj,IterationCcw:pJ,IterationCw:xJ,JapaneseYen:gJ,Joystick:yJ,Kanban:nv,Key:ep,KeyRound:z4,KeySquare:vJ,Keyboard:wJ,KeyboardMusic:bJ,KeyboardOff:_J,Lamp:TJ,LampCeiling:jJ,LampDesk:NJ,LampFloor:kJ,LampWallDown:SJ,LampWallUp:CJ,LandPlot:EJ,Landmark:AJ,Languages:MJ,Laptop:LJ,LaptopMinimal:sS,LaptopMinimalCheck:IJ,Lasso:DJ,LassoSelect:PJ,Laugh:RJ,Layers:wR,Layers2:OJ,Layers3:FJ,LayoutDashboard:$4,LayoutGrid:xf,LayoutList:BJ,LayoutPanelLeft:zJ,LayoutPanelTop:$J,LayoutTemplate:U4,Leaf:UJ,LeafyGreen:qJ,Lectern:VJ,LetterText:HJ,Library:q4,LibraryBig:GJ,LifeBuoy:yA,Ligature:WJ,Lightbulb:sj,LightbulbOff:KJ,Link:po,Link2:tl,Link2Off:YJ,Linkedin:Jh,List:em,ListCheck:ZJ,ListChecks:pb,ListCollapse:XJ,ListEnd:QJ,ListFilter:jR,ListMinus:JJ,ListMusic:eee,ListOrdered:Cy,ListPlus:tee,ListRestart:see,ListStart:ree,ListTodo:nee,ListTree:aee,ListVideo:iee,ListX:oee,Loader:cee,LoaderCircle:es,LoaderPinwheel:lee,Locate:vA,LocateFixed:dee,LocateOff:uee,Lock:Hc,LockKeyhole:hee,LockKeyholeOpen:rS,LockOpen:nS,LogIn:V4,LogOut:bA,Logs:mee,Lollipop:fee,Luggage:pee,Magnet:xee,Mail:Vs,MailCheck:gee,MailMinus:yee,MailOpen:NR,MailPlus:kR,MailQuestion:vee,MailSearch:bee,MailWarning:_ee,MailX:_A,Mailbox:wee,Mails:jee,Map:H4,MapPin:Ca,MapPinCheck:kee,MapPinCheckInside:Nee,MapPinHouse:See,MapPinMinus:Tee,MapPinMinusInside:Cee,MapPinOff:Eee,MapPinPlus:Mee,MapPinPlusInside:Aee,MapPinX:Lee,MapPinXInside:Iee,MapPinned:Pee,Martini:Dee,Maximize:SR,Maximize2:Ree,Medal:xb,Megaphone:bu,MegaphoneOff:Oee,Meh:Fee,MemoryStick:Bee,Menu:G4,Merge:zee,MessageCircle:Jl,MessageCircleCode:$ee,MessageCircleDashed:Uee,MessageCircleHeart:wA,MessageCircleMore:qee,MessageCircleOff:Vee,MessageCirclePlus:Hee,MessageCircleQuestion:CR,MessageCircleReply:Gee,MessageCircleWarning:Wee,MessageCircleX:Kee,MessageSquare:xi,MessageSquareCode:Yee,MessageSquareDashed:Zee,MessageSquareDiff:Xee,MessageSquareDot:Qee,MessageSquareHeart:Jee,MessageSquareLock:ete,MessageSquareMore:TR,MessageSquareOff:tte,MessageSquarePlus:V0,MessageSquareQuote:ER,MessageSquareReply:ste,MessageSquareShare:rte,MessageSquareText:nte,MessageSquareWarning:ate,MessageSquareX:ite,MessagesSquare:ote,Mic:W4,MicOff:lte,MicVocal:aS,Microchip:cte,Microscope:dte,Microwave:ute,Milestone:hte,Milk:fte,MilkOff:mte,Minimize:xte,Minimize2:pte,Minus:av,Monitor:rj,MonitorCheck:gte,MonitorCog:yte,MonitorDot:vte,MonitorDown:bte,MonitorOff:_te,MonitorPause:wte,MonitorPlay:AR,MonitorSmartphone:jte,MonitorSpeaker:Nte,MonitorStop:kte,MonitorUp:K4,MonitorX:Ste,Moon:Tte,MoonStar:Cte,Mountain:Ate,MountainSnow:Ete,Mouse:Pte,MouseOff:Mte,MousePointer:Bu,MousePointer2:Ite,MousePointerBan:Lte,MousePointerClick:qc,Move:Wte,Move3d:iS,MoveDiagonal:Rte,MoveDiagonal2:Dte,MoveDown:Bte,MoveDownLeft:Ote,MoveDownRight:Fte,MoveHorizontal:zte,MoveLeft:$te,MoveRight:Ute,MoveUp:Hte,MoveUpLeft:qte,MoveUpRight:Vte,MoveVertical:Gte,Music:Xte,Music2:Kte,Music3:Yte,Music4:Zte,Navigation:MR,Navigation2:Jte,Navigation2Off:Qte,NavigationOff:ese,Network:tse,Newspaper:iv,Nfc:sse,Notebook:ise,NotebookPen:rse,NotebookTabs:nse,NotebookText:ase,NotepadText:lse,NotepadTextDashed:ose,Nut:dse,NutOff:cse,Octagon:hse,OctagonAlert:K1,OctagonMinus:use,OctagonPause:oS,OctagonX:lS,Omega:mse,Option:fse,Orbit:pse,Origami:xse,Package:Il,Package2:gse,PackageCheck:yse,PackageMinus:vse,PackageOpen:bse,PackagePlus:_se,PackageSearch:wse,PackageX:jse,PaintBucket:Nse,PaintRoller:kse,Paintbrush:Sse,PaintbrushVertical:cS,Palette:fl,PanelBottom:Ese,PanelBottomClose:Cse,PanelBottomDashed:dS,PanelBottomOpen:Tse,PanelLeft:fS,PanelLeftClose:uS,PanelLeftDashed:hS,PanelLeftOpen:mS,PanelRight:Ise,PanelRightClose:Ase,PanelRightDashed:pS,PanelRightOpen:Mse,PanelTop:Dse,PanelTopClose:Lse,PanelTopDashed:xS,PanelTopOpen:Pse,PanelsLeftBottom:Rse,PanelsRightBottom:Ose,PanelsTopLeft:Y1,Paperclip:nj,Parentheses:Fse,ParkingMeter:Bse,PartyPopper:eu,Pause:tm,PawPrint:zse,PcCase:$se,Pen:R0,PenLine:D0,PenOff:Use,PenTool:aj,Pencil:Ea,PencilLine:qse,PencilOff:Vse,PencilRuler:Hse,Pentagon:Gse,Percent:Y4,PersonStanding:Wse,PhilippinePeso:Kse,Phone:Cn,PhoneCall:Yse,PhoneForwarded:Zse,PhoneIncoming:Xse,PhoneMissed:Qse,PhoneOff:Jse,PhoneOutgoing:ere,Pi:tre,Piano:sre,Pickaxe:rre,PictureInPicture:are,PictureInPicture2:nre,PiggyBank:ire,Pilcrow:cre,PilcrowLeft:ore,PilcrowRight:lre,Pill:ure,PillBottle:dre,Pin:ij,PinOff:IR,Pipette:hre,Pizza:mre,Plane:LR,PlaneLanding:fre,PlaneTakeoff:pre,Play:Uo,Plug:Z4,Plug2:xre,PlugZap:gS,Plus:$s,Pocket:yre,PocketKnife:gre,Podcast:vre,Pointer:_re,PointerOff:bre,Popcorn:wre,Popsicle:jre,PoundSterling:Nre,Power:PR,PowerOff:kre,Presentation:Ty,Printer:DR,PrinterCheck:Sre,Projector:Cre,Proportions:Tre,Puzzle:Ere,Pyramid:Are,QrCode:ov,Quote:X4,Rabbit:Mre,Radar:jA,Radiation:Ire,Radical:Lre,Radio:gb,RadioReceiver:Pre,RadioTower:Dre,Radius:Rre,RailSymbol:Ore,Rainbow:Fre,Rat:Bre,Ratio:zre,Receipt:Yre,ReceiptCent:$re,ReceiptEuro:Ure,ReceiptIndianRupee:qre,ReceiptJapaneseYen:Vre,ReceiptPoundSterling:Hre,ReceiptRussianRuble:Gre,ReceiptSwissFranc:Wre,ReceiptText:Kre,RectangleEllipsis:yS,RectangleHorizontal:Zre,RectangleVertical:Xre,Recycle:Qre,Redo:oj,Redo2:Jre,RedoDot:ene,RefreshCcw:NA,RefreshCcwDot:tne,RefreshCw:Mi,RefreshCwOff:sne,Refrigerator:rne,Regex:nne,RemoveFormatting:ane,Repeat:RR,Repeat1:ine,Repeat2:one,Replace:cne,ReplaceAll:lne,Reply:OR,ReplyAll:dne,Rewind:une,Ribbon:hne,Rocket:lv,RockingChair:mne,RollerCoaster:fne,Rotate3d:vS,RotateCcw:cv,RotateCcwSquare:pne,RotateCw:Q4,RotateCwSquare:xne,Route:yne,RouteOff:gne,Router:vne,Rows2:bS,Rows3:_S,Rows4:bne,Rss:_ne,Ruler:J4,RussianRuble:wne,Sailboat:jne,Salad:Nne,Sandwich:kne,Satellite:Cne,SatelliteDish:Sne,Save:Bl,SaveAll:Tne,SaveOff:Ene,Scale:FR,Scale3d:wS,Scaling:Ane,Scan:Fne,ScanBarcode:Mne,ScanEye:Ine,ScanFace:Lne,ScanLine:Pne,ScanQrCode:Dne,ScanSearch:Rne,ScanText:One,School:Bne,Scissors:$ne,ScissorsLineDashed:zne,ScreenShare:qne,ScreenShareOff:Une,Scroll:Hne,ScrollText:Vne,Search:yn,SearchCheck:Gne,SearchCode:Wne,SearchSlash:Kne,SearchX:BR,Section:Yne,Send:en,SendHorizontal:jS,SendToBack:Zne,SeparatorHorizontal:Xne,SeparatorVertical:Qne,Server:sae,ServerCog:Jne,ServerCrash:eae,ServerOff:tae,Settings:oo,Settings2:zR,Shapes:rae,Share:$R,Share2:Ec,Sheet:nae,Shell:aae,Shield:Wu,ShieldAlert:UR,ShieldBan:iae,ShieldCheck:Ey,ShieldEllipsis:oae,ShieldHalf:lae,ShieldMinus:cae,ShieldOff:e3,ShieldPlus:dae,ShieldQuestion:uae,ShieldX:NS,Ship:mae,ShipWheel:hae,Shirt:fae,ShoppingBag:dv,ShoppingBasket:pae,ShoppingCart:Hf,Shovel:xae,ShowerHead:gae,Shrink:yae,Shrub:vae,Shuffle:t3,Sigma:bae,Signal:kae,SignalHigh:_ae,SignalLow:wae,SignalMedium:jae,SignalZero:Nae,Signature:Sae,Signpost:Tae,SignpostBig:Cae,Siren:Eae,SkipBack:Aae,SkipForward:Mae,Skull:Iae,Slack:Lae,Slash:Pae,Slice:Dae,SlidersHorizontal:s3,SlidersVertical:kS,Smartphone:ig,SmartphoneCharging:Rae,SmartphoneNfc:Oae,Smile:Bae,SmilePlus:Fae,Snail:zae,Snowflake:H0,Sofa:$ae,Soup:Uae,Space:qae,Spade:Vae,Sparkle:Hae,Sparkles:jr,Speaker:Gae,Speech:Wae,SpellCheck:Yae,SpellCheck2:Kae,Spline:Zae,Split:Xae,SprayCan:Qae,Sprout:r3,Square:og,SquareActivity:SS,SquareArrowDown:ES,SquareArrowDownLeft:CS,SquareArrowDownRight:TS,SquareArrowLeft:AS,SquareArrowOutDownLeft:MS,SquareArrowOutDownRight:IS,SquareArrowOutUpLeft:LS,SquareArrowOutUpRight:PS,SquareArrowRight:DS,SquareArrowUp:FS,SquareArrowUpLeft:RS,SquareArrowUpRight:OS,SquareAsterisk:BS,SquareBottomDashedScissors:zS,SquareChartGantt:j0,SquareCheck:$S,SquareCheckBig:Z1,SquareChevronDown:US,SquareChevronLeft:qS,SquareChevronRight:VS,SquareChevronUp:HS,SquareCode:GS,SquareDashed:YS,SquareDashedBottom:eie,SquareDashedBottomCode:Jae,SquareDashedKanban:WS,SquareDashedMousePointer:KS,SquareDivide:ZS,SquareDot:XS,SquareEqual:QS,SquareFunction:JS,SquareKanban:eC,SquareLibrary:tC,SquareM:sC,SquareMenu:rC,SquareMinus:nC,SquareMousePointer:aC,SquareParking:oC,SquareParkingOff:iC,SquarePen:sd,SquarePercent:lC,SquarePi:cC,SquarePilcrow:dC,SquarePlay:uC,SquarePlus:hC,SquarePower:mC,SquareRadical:tie,SquareScissors:fC,SquareSigma:pC,SquareSlash:xC,SquareSplitHorizontal:gC,SquareSplitVertical:yC,SquareSquare:sie,SquareStack:rie,SquareTerminal:vC,SquareUser:_C,SquareUserRound:bC,SquareX:wC,Squircle:nie,Squirrel:aie,Stamp:iie,Star:Xn,StarHalf:oie,StarOff:lie,StepBack:cie,StepForward:die,Stethoscope:uie,Sticker:hie,StickyNote:mie,Store:fie,StretchHorizontal:pie,StretchVertical:xie,Strikethrough:qR,Subscript:gie,Sun:yb,SunDim:yie,SunMedium:vie,SunMoon:bie,SunSnow:_ie,Sunrise:wie,Sunset:jie,Superscript:Nie,SwatchBook:kie,SwissFranc:Sie,SwitchCamera:Cie,Sword:Tie,Swords:Eie,Syringe:Aie,Table:SA,Table2:kA,TableCellsMerge:Mie,TableCellsSplit:Iie,TableColumnsSplit:Lie,TableOfContents:Pie,TableProperties:Die,TableRowsSplit:Rie,Tablet:Fie,TabletSmartphone:Oie,Tablets:Bie,Tag:wh,Tags:zie,Tally1:$ie,Tally2:Uie,Tally3:qie,Tally4:Vie,Tally5:Hie,Tangent:Gie,Target:Pd,Telescope:Wie,Tent:Yie,TentTree:Kie,Terminal:Zie,TestTube:Xie,TestTubeDiagonal:jC,TestTubes:Qie,Text:roe,TextCursor:eoe,TextCursorInput:Jie,TextQuote:toe,TextSearch:soe,TextSelect:NC,Theater:noe,Thermometer:ooe,ThermometerSnowflake:aoe,ThermometerSun:ioe,ThumbsDown:VR,ThumbsUp:jh,Ticket:HR,TicketCheck:loe,TicketMinus:coe,TicketPercent:doe,TicketPlus:uoe,TicketSlash:hoe,TicketX:moe,Tickets:poe,TicketsPlane:foe,Timer:yoe,TimerOff:xoe,TimerReset:goe,ToggleLeft:voe,ToggleRight:boe,Toilet:_oe,Tornado:woe,Torus:joe,Touchpad:koe,TouchpadOff:Noe,TowerControl:Soe,ToyBrick:Coe,Tractor:Toe,TrafficCone:Eoe,TrainFront:Moe,TrainFrontTunnel:Aoe,TrainTrack:Ioe,TramFront:kC,Trash:Loe,Trash2:yr,TreeDeciduous:Poe,TreePalm:SC,TreePine:lj,Trees:Doe,Trello:Roe,TrendingDown:vb,TrendingUp:bo,TrendingUpDown:Ooe,Triangle:Boe,TriangleAlert:id,TriangleRight:Foe,Trophy:Gi,Truck:GR,Turtle:zoe,Tv:Uoe,TvMinimal:CC,TvMinimalPlay:$oe,Twitch:qoe,Twitter:Voe,Type:Goe,TypeOutline:Hoe,Umbrella:Koe,UmbrellaOff:Woe,Underline:CA,Undo:cj,Undo2:Yoe,UndoDot:Zoe,UnfoldHorizontal:Xoe,UnfoldVertical:Qoe,Ungroup:Joe,University:TC,Unlink:n3,Unlink2:ele,Unplug:tle,Upload:da,Usb:sle,User:Di,UserCheck:uv,UserCog:WR,UserMinus:KR,UserPen:rle,UserPlus:sl,UserRound:PC,UserRoundCheck:EC,UserRoundCog:AC,UserRoundMinus:MC,UserRoundPen:nle,UserRoundPlus:IC,UserRoundSearch:ale,UserRoundX:LC,UserSearch:ile,UserX:ole,Users:pr,UsersRound:DC,Utensils:OC,UtensilsCrossed:RC,UtilityPole:lle,Variable:TA,Vault:cle,Vegan:dle,VenetianMask:ule,Vibrate:mle,VibrateOff:hle,Video:Jr,VideoOff:fle,Videotape:ple,View:xle,Voicemail:gle,Volleyball:yle,Volume:_le,Volume1:vle,Volume2:YR,VolumeOff:ble,VolumeX:ZR,Vote:wle,Wallet:XR,WalletCards:jle,WalletMinimal:FC,Wallpaper:Nle,Wand:kle,WandSparkles:Zx,Warehouse:Sle,WashingMachine:Cle,Watch:Tle,Waves:Ele,Waypoints:Ale,Webcam:Mle,Webhook:Lle,WebhookOff:Ile,Weight:Ple,Wheat:Rle,WheatOff:Dle,WholeWord:Ole,Wifi:Ule,WifiHigh:Fle,WifiLow:Ble,WifiOff:zle,WifiZero:$le,Wind:Vle,WindArrowDown:qle,Wine:Gle,WineOff:Hle,Workflow:QR,Worm:Wle,WrapText:Kle,Wrench:Ay,X:vr,Youtube:Yle,Zap:Ku,ZapOff:Zle,ZoomIn:dj,ZoomOut:EA},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 Pme=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:AU,AArrowDownIcon:AU,AArrowUp:MU,AArrowUpIcon:MU,ALargeSmall:IU,ALargeSmallIcon:IU,Accessibility:LU,AccessibilityIcon:LU,Activity:vh,ActivityIcon:vh,ActivitySquare:SS,ActivitySquareIcon:SS,AirVent:PU,AirVentIcon:PU,Airplay:DU,AirplayIcon:DU,AlarmCheck:MN,AlarmCheckIcon:MN,AlarmClock:OU,AlarmClockCheck:MN,AlarmClockCheckIcon:MN,AlarmClockIcon:OU,AlarmClockMinus:IN,AlarmClockMinusIcon:IN,AlarmClockOff:RU,AlarmClockOffIcon:RU,AlarmClockPlus:LN,AlarmClockPlusIcon:LN,AlarmMinus:IN,AlarmMinusIcon:IN,AlarmPlus:LN,AlarmPlusIcon:LN,AlarmSmoke:FU,AlarmSmokeIcon:FU,Album:BU,AlbumIcon:BU,AlertCircle:Oi,AlertCircleIcon:Oi,AlertOctagon:K1,AlertOctagonIcon:K1,AlertTriangle:id,AlertTriangleIcon:id,AlignCenter:T4,AlignCenterHorizontal:zU,AlignCenterHorizontalIcon:zU,AlignCenterIcon:T4,AlignCenterVertical:$U,AlignCenterVerticalIcon:$U,AlignEndHorizontal:UU,AlignEndHorizontalIcon:UU,AlignEndVertical:qU,AlignEndVerticalIcon:qU,AlignHorizontalDistributeCenter:VU,AlignHorizontalDistributeCenterIcon:VU,AlignHorizontalDistributeEnd:HU,AlignHorizontalDistributeEndIcon:HU,AlignHorizontalDistributeStart:GU,AlignHorizontalDistributeStartIcon:GU,AlignHorizontalJustifyCenter:WU,AlignHorizontalJustifyCenterIcon:WU,AlignHorizontalJustifyEnd:KU,AlignHorizontalJustifyEndIcon:KU,AlignHorizontalJustifyStart:YU,AlignHorizontalJustifyStartIcon:YU,AlignHorizontalSpaceAround:ZU,AlignHorizontalSpaceAroundIcon:ZU,AlignHorizontalSpaceBetween:XU,AlignHorizontalSpaceBetweenIcon:XU,AlignJustify:QU,AlignJustifyIcon:QU,AlignLeft:E4,AlignLeftIcon:E4,AlignRight:A4,AlignRightIcon:A4,AlignStartHorizontal:JU,AlignStartHorizontalIcon:JU,AlignStartVertical:eq,AlignStartVerticalIcon:eq,AlignVerticalDistributeCenter:tq,AlignVerticalDistributeCenterIcon:tq,AlignVerticalDistributeEnd:sq,AlignVerticalDistributeEndIcon:sq,AlignVerticalDistributeStart:rq,AlignVerticalDistributeStartIcon:rq,AlignVerticalJustifyCenter:nq,AlignVerticalJustifyCenterIcon:nq,AlignVerticalJustifyEnd:aq,AlignVerticalJustifyEndIcon:aq,AlignVerticalJustifyStart:iq,AlignVerticalJustifyStartIcon:iq,AlignVerticalSpaceAround:oq,AlignVerticalSpaceAroundIcon:oq,AlignVerticalSpaceBetween:lq,AlignVerticalSpaceBetweenIcon:lq,Ambulance:cq,AmbulanceIcon:cq,Ampersand:dq,AmpersandIcon:dq,Ampersands:uq,AmpersandsIcon:uq,Amphora:hq,AmphoraIcon:hq,Anchor:mq,AnchorIcon:mq,Angry:fq,AngryIcon:fq,Annoyed:pq,AnnoyedIcon:pq,Antenna:xq,AntennaIcon:xq,Anvil:gq,AnvilIcon:gq,Aperture:yq,ApertureIcon:yq,AppWindow:tR,AppWindowIcon:tR,AppWindowMac:vq,AppWindowMacIcon:vq,Apple:bq,AppleIcon:bq,Archive:Kw,ArchiveIcon:Kw,ArchiveRestore:lA,ArchiveRestoreIcon:lA,ArchiveX:_q,ArchiveXIcon:_q,AreaChart:WN,AreaChartIcon:WN,Armchair:wq,ArmchairIcon:wq,ArrowBigDown:Nq,ArrowBigDownDash:jq,ArrowBigDownDashIcon:jq,ArrowBigDownIcon:Nq,ArrowBigLeft:Sq,ArrowBigLeftDash:kq,ArrowBigLeftDashIcon:kq,ArrowBigLeftIcon:Sq,ArrowBigRight:Tq,ArrowBigRightDash:Cq,ArrowBigRightDashIcon:Cq,ArrowBigRightIcon:Tq,ArrowBigUp:Aq,ArrowBigUpDash:Eq,ArrowBigUpDashIcon:Eq,ArrowBigUpIcon:Aq,ArrowDown:Hu,ArrowDown01:Mq,ArrowDown01Icon:Mq,ArrowDown10:Iq,ArrowDown10Icon:Iq,ArrowDownAZ:PN,ArrowDownAZIcon:PN,ArrowDownAz:PN,ArrowDownAzIcon:PN,ArrowDownCircle:ak,ArrowDownCircleIcon:ak,ArrowDownFromLine:Lq,ArrowDownFromLineIcon:Lq,ArrowDownIcon:Hu,ArrowDownLeft:Pq,ArrowDownLeftFromCircle:ok,ArrowDownLeftFromCircleIcon:ok,ArrowDownLeftFromSquare:MS,ArrowDownLeftFromSquareIcon:MS,ArrowDownLeftIcon:Pq,ArrowDownLeftSquare:CS,ArrowDownLeftSquareIcon:CS,ArrowDownNarrowWide:Dq,ArrowDownNarrowWideIcon:Dq,ArrowDownRight:sR,ArrowDownRightFromCircle:lk,ArrowDownRightFromCircleIcon:lk,ArrowDownRightFromSquare:IS,ArrowDownRightFromSquareIcon:IS,ArrowDownRightIcon:sR,ArrowDownRightSquare:TS,ArrowDownRightSquareIcon:TS,ArrowDownSquare:ES,ArrowDownSquareIcon:ES,ArrowDownToDot:Rq,ArrowDownToDotIcon:Rq,ArrowDownToLine:Oq,ArrowDownToLineIcon:Oq,ArrowDownUp:Fq,ArrowDownUpIcon:Fq,ArrowDownWideNarrow:DN,ArrowDownWideNarrowIcon:DN,ArrowDownZA:RN,ArrowDownZAIcon:RN,ArrowDownZa:RN,ArrowDownZaIcon:RN,ArrowLeft:ka,ArrowLeftCircle:ik,ArrowLeftCircleIcon:ik,ArrowLeftFromLine:Bq,ArrowLeftFromLineIcon:Bq,ArrowLeftIcon:ka,ArrowLeftRight:zq,ArrowLeftRightIcon:zq,ArrowLeftSquare:AS,ArrowLeftSquareIcon:AS,ArrowLeftToLine:$q,ArrowLeftToLineIcon:$q,ArrowRight:Ha,ArrowRightCircle:uk,ArrowRightCircleIcon:uk,ArrowRightFromLine:Uq,ArrowRightFromLineIcon:Uq,ArrowRightIcon:Ha,ArrowRightLeft:ub,ArrowRightLeftIcon:ub,ArrowRightSquare:DS,ArrowRightSquareIcon:DS,ArrowRightToLine:qq,ArrowRightToLineIcon:qq,ArrowUp:Id,ArrowUp01:Vq,ArrowUp01Icon:Vq,ArrowUp10:Hq,ArrowUp10Icon:Hq,ArrowUpAZ:ON,ArrowUpAZIcon:ON,ArrowUpAz:ON,ArrowUpAzIcon:ON,ArrowUpCircle:hk,ArrowUpCircleIcon:hk,ArrowUpDown:Ad,ArrowUpDownIcon:Ad,ArrowUpFromDot:Gq,ArrowUpFromDotIcon:Gq,ArrowUpFromLine:Wq,ArrowUpFromLineIcon:Wq,ArrowUpIcon:Id,ArrowUpLeft:Kq,ArrowUpLeftFromCircle:ck,ArrowUpLeftFromCircleIcon:ck,ArrowUpLeftFromSquare:LS,ArrowUpLeftFromSquareIcon:LS,ArrowUpLeftIcon:Kq,ArrowUpLeftSquare:RS,ArrowUpLeftSquareIcon:RS,ArrowUpNarrowWide:FN,ArrowUpNarrowWideIcon:FN,ArrowUpRight:rR,ArrowUpRightFromCircle:dk,ArrowUpRightFromCircleIcon:dk,ArrowUpRightFromSquare:PS,ArrowUpRightFromSquareIcon:PS,ArrowUpRightIcon:rR,ArrowUpRightSquare:OS,ArrowUpRightSquareIcon:OS,ArrowUpSquare:FS,ArrowUpSquareIcon:FS,ArrowUpToLine:Yq,ArrowUpToLineIcon:Yq,ArrowUpWideNarrow:Zq,ArrowUpWideNarrowIcon:Zq,ArrowUpZA:BN,ArrowUpZAIcon:BN,ArrowUpZa:BN,ArrowUpZaIcon:BN,ArrowsUpFromLine:Xq,ArrowsUpFromLineIcon:Xq,Asterisk:Qq,AsteriskIcon:Qq,AsteriskSquare:BS,AsteriskSquareIcon:BS,AtSign:Jq,AtSignIcon:Jq,Atom:eV,AtomIcon:eV,AudioLines:tV,AudioLinesIcon:tV,AudioWaveform:sV,AudioWaveformIcon:sV,Award:Yl,AwardIcon:Yl,Axe:rV,AxeIcon:rV,Axis3D:zN,Axis3DIcon:zN,Axis3d:zN,Axis3dIcon:zN,Baby:nV,BabyIcon:nV,Backpack:aV,BackpackIcon:aV,Badge:_V,BadgeAlert:iV,BadgeAlertIcon:iV,BadgeCent:oV,BadgeCentIcon:oV,BadgeCheck:$N,BadgeCheckIcon:$N,BadgeDollarSign:lV,BadgeDollarSignIcon:lV,BadgeEuro:cV,BadgeEuroIcon:cV,BadgeHelp:dV,BadgeHelpIcon:dV,BadgeIcon:_V,BadgeIndianRupee:uV,BadgeIndianRupeeIcon:uV,BadgeInfo:hV,BadgeInfoIcon:hV,BadgeJapaneseYen:mV,BadgeJapaneseYenIcon:mV,BadgeMinus:fV,BadgeMinusIcon:fV,BadgePercent:pV,BadgePercentIcon:pV,BadgePlus:xV,BadgePlusIcon:xV,BadgePoundSterling:gV,BadgePoundSterlingIcon:gV,BadgeRussianRuble:yV,BadgeRussianRubleIcon:yV,BadgeSwissFranc:vV,BadgeSwissFrancIcon:vV,BadgeX:bV,BadgeXIcon:bV,BaggageClaim:wV,BaggageClaimIcon:wV,Ban:nR,BanIcon:nR,Banana:jV,BananaIcon:jV,Bandage:NV,BandageIcon:NV,Banknote:kV,BanknoteIcon:kV,BarChart:ek,BarChart2:tk,BarChart2Icon:tk,BarChart3:ro,BarChart3Icon:ro,BarChart4:QN,BarChart4Icon:QN,BarChartBig:XN,BarChartBigIcon:XN,BarChartHorizontal:YN,BarChartHorizontalBig:KN,BarChartHorizontalBigIcon:KN,BarChartHorizontalIcon:YN,BarChartIcon:ek,Barcode:SV,BarcodeIcon:SV,Baseline:CV,BaselineIcon:CV,Bath:Xf,BathIcon:Xf,Battery:LV,BatteryCharging:TV,BatteryChargingIcon:TV,BatteryFull:EV,BatteryFullIcon:EV,BatteryIcon:LV,BatteryLow:AV,BatteryLowIcon:AV,BatteryMedium:MV,BatteryMediumIcon:MV,BatteryWarning:IV,BatteryWarningIcon:IV,Beaker:PV,BeakerIcon:PV,Bean:RV,BeanIcon:RV,BeanOff:DV,BeanOffIcon:DV,Bed:Ny,BedDouble:M4,BedDoubleIcon:M4,BedIcon:Ny,BedSingle:OV,BedSingleIcon:OV,Beef:FV,BeefIcon:FV,Beer:zV,BeerIcon:zV,BeerOff:BV,BeerOffIcon:BV,Bell:_m,BellDot:$V,BellDotIcon:$V,BellElectric:UV,BellElectricIcon:UV,BellIcon:_m,BellMinus:qV,BellMinusIcon:qV,BellOff:ev,BellOffIcon:ev,BellPlus:VV,BellPlusIcon:VV,BellRing:aR,BellRingIcon:aR,BetweenHorizonalEnd:UN,BetweenHorizonalEndIcon:UN,BetweenHorizonalStart:qN,BetweenHorizonalStartIcon:qN,BetweenHorizontalEnd:UN,BetweenHorizontalEndIcon:UN,BetweenHorizontalStart:qN,BetweenHorizontalStartIcon:qN,BetweenVerticalEnd:HV,BetweenVerticalEndIcon:HV,BetweenVerticalStart:GV,BetweenVerticalStartIcon:GV,BicepsFlexed:WV,BicepsFlexedIcon:WV,Bike:KV,BikeIcon:KV,Binary:YV,BinaryIcon:YV,Binoculars:ZV,BinocularsIcon:ZV,Biohazard:XV,BiohazardIcon:XV,Bird:QV,BirdIcon:QV,Bitcoin:JV,BitcoinIcon:JV,Blend:eH,BlendIcon:eH,Blinds:tH,BlindsIcon:tH,Blocks:sH,BlocksIcon:sH,Bluetooth:iH,BluetoothConnected:rH,BluetoothConnectedIcon:rH,BluetoothIcon:iH,BluetoothOff:nH,BluetoothOffIcon:nH,BluetoothSearching:aH,BluetoothSearchingIcon:aH,Bold:Yw,BoldIcon:Yw,Bolt:oH,BoltIcon:oH,Bomb:lH,BombIcon:lH,Bone:cH,BoneIcon:cH,Book:MH,BookA:dH,BookAIcon:dH,BookAudio:uH,BookAudioIcon:uH,BookCheck:hH,BookCheckIcon:hH,BookCopy:mH,BookCopyIcon:mH,BookDashed:VN,BookDashedIcon:VN,BookDown:fH,BookDownIcon:fH,BookHeadphones:pH,BookHeadphonesIcon:pH,BookHeart:xH,BookHeartIcon:xH,BookIcon:MH,BookImage:gH,BookImageIcon:gH,BookKey:yH,BookKeyIcon:yH,BookLock:vH,BookLockIcon:vH,BookMarked:bH,BookMarkedIcon:bH,BookMinus:_H,BookMinusIcon:_H,BookOpen:bh,BookOpenCheck:wH,BookOpenCheckIcon:wH,BookOpenIcon:bh,BookOpenText:jH,BookOpenTextIcon:jH,BookPlus:NH,BookPlusIcon:NH,BookTemplate:VN,BookTemplateIcon:VN,BookText:kH,BookTextIcon:kH,BookType:SH,BookTypeIcon:SH,BookUp:TH,BookUp2:CH,BookUp2Icon:CH,BookUpIcon:TH,BookUser:EH,BookUserIcon:EH,BookX:AH,BookXIcon:AH,Bookmark:ag,BookmarkCheck:IH,BookmarkCheckIcon:IH,BookmarkIcon:ag,BookmarkMinus:LH,BookmarkMinusIcon:LH,BookmarkPlus:iR,BookmarkPlusIcon:iR,BookmarkX:PH,BookmarkXIcon:PH,BoomBox:DH,BoomBoxIcon:DH,Bot:cA,BotIcon:cA,BotMessageSquare:RH,BotMessageSquareIcon:RH,BotOff:OH,BotOffIcon:OH,Box:FH,BoxIcon:FH,BoxSelect:YS,BoxSelectIcon:YS,Boxes:BH,BoxesIcon:BH,Braces:HN,BracesIcon:HN,Brackets:zH,BracketsIcon:zH,Brain:oR,BrainCircuit:$H,BrainCircuitIcon:$H,BrainCog:UH,BrainCogIcon:UH,BrainIcon:oR,BrickWall:qH,BrickWallIcon:qH,Briefcase:Gu,BriefcaseBusiness:VH,BriefcaseBusinessIcon:VH,BriefcaseConveyorBelt:HH,BriefcaseConveyorBeltIcon:HH,BriefcaseIcon:Gu,BriefcaseMedical:GH,BriefcaseMedicalIcon:GH,BringToFront:WH,BringToFrontIcon:WH,Brush:KH,BrushIcon:KH,Bug:XH,BugIcon:XH,BugOff:YH,BugOffIcon:YH,BugPlay:ZH,BugPlayIcon:ZH,Building:I4,Building2:Sa,Building2Icon:Sa,BuildingIcon:I4,Bus:JH,BusFront:QH,BusFrontIcon:QH,BusIcon:JH,Cable:tG,CableCar:eG,CableCarIcon:eG,CableIcon:tG,Cake:_h,CakeIcon:_h,CakeSlice:sG,CakeSliceIcon:sG,Calculator:dA,CalculatorIcon:dA,Calendar:on,Calendar1:rG,Calendar1Icon:rG,CalendarArrowDown:nG,CalendarArrowDownIcon:nG,CalendarArrowUp:aG,CalendarArrowUpIcon:aG,CalendarCheck:lR,CalendarCheck2:iG,CalendarCheck2Icon:iG,CalendarCheckIcon:lR,CalendarClock:tv,CalendarClockIcon:tv,CalendarCog:oG,CalendarCogIcon:oG,CalendarDays:hd,CalendarDaysIcon:hd,CalendarFold:lG,CalendarFoldIcon:lG,CalendarHeart:cR,CalendarHeartIcon:cR,CalendarIcon:on,CalendarMinus:dG,CalendarMinus2:cG,CalendarMinus2Icon:cG,CalendarMinusIcon:dG,CalendarOff:dR,CalendarOffIcon:dR,CalendarPlus:rb,CalendarPlus2:uG,CalendarPlus2Icon:uG,CalendarPlusIcon:rb,CalendarRange:hG,CalendarRangeIcon:hG,CalendarSearch:mG,CalendarSearchIcon:mG,CalendarSync:fG,CalendarSyncIcon:fG,CalendarX:xG,CalendarX2:pG,CalendarX2Icon:pG,CalendarXIcon:xG,Camera:Qf,CameraIcon:Qf,CameraOff:gG,CameraOffIcon:gG,CandlestickChart:ZN,CandlestickChartIcon:ZN,Candy:bG,CandyCane:yG,CandyCaneIcon:yG,CandyIcon:bG,CandyOff:vG,CandyOffIcon:vG,Cannabis:_G,CannabisIcon:_G,Captions:GN,CaptionsIcon:GN,CaptionsOff:wG,CaptionsOffIcon:wG,Car:kG,CarFront:jG,CarFrontIcon:jG,CarIcon:kG,CarTaxiFront:NG,CarTaxiFrontIcon:NG,Caravan:SG,CaravanIcon:SG,Carrot:CG,CarrotIcon:CG,CaseLower:TG,CaseLowerIcon:TG,CaseSensitive:EG,CaseSensitiveIcon:EG,CaseUpper:AG,CaseUpperIcon:AG,CassetteTape:MG,CassetteTapeIcon:MG,Cast:IG,CastIcon:IG,Castle:LG,CastleIcon:LG,Cat:PG,CatIcon:PG,Cctv:DG,CctvIcon:DG,ChartArea:WN,ChartAreaIcon:WN,ChartBar:YN,ChartBarBig:KN,ChartBarBigIcon:KN,ChartBarDecreasing:RG,ChartBarDecreasingIcon:RG,ChartBarIcon:YN,ChartBarIncreasing:OG,ChartBarIncreasingIcon:OG,ChartBarStacked:FG,ChartBarStackedIcon:FG,ChartCandlestick:ZN,ChartCandlestickIcon:ZN,ChartColumn:ro,ChartColumnBig:XN,ChartColumnBigIcon:XN,ChartColumnDecreasing:BG,ChartColumnDecreasingIcon:BG,ChartColumnIcon:ro,ChartColumnIncreasing:QN,ChartColumnIncreasingIcon:QN,ChartColumnStacked:zG,ChartColumnStackedIcon:zG,ChartGantt:$G,ChartGanttIcon:$G,ChartLine:JN,ChartLineIcon:JN,ChartNetwork:UG,ChartNetworkIcon:UG,ChartNoAxesColumn:tk,ChartNoAxesColumnDecreasing:qG,ChartNoAxesColumnDecreasingIcon:qG,ChartNoAxesColumnIcon:tk,ChartNoAxesColumnIncreasing:ek,ChartNoAxesColumnIncreasingIcon:ek,ChartNoAxesCombined:VG,ChartNoAxesCombinedIcon:VG,ChartNoAxesGantt:sk,ChartNoAxesGanttIcon:sk,ChartPie:rk,ChartPieIcon:rk,ChartScatter:nk,ChartScatterIcon:nk,ChartSpline:HG,ChartSplineIcon:HG,Check:Kn,CheckCheck:uR,CheckCheckIcon:uR,CheckCircle:di,CheckCircle2:In,CheckCircle2Icon:In,CheckCircleIcon:di,CheckIcon:Kn,CheckSquare:Z1,CheckSquare2:$S,CheckSquare2Icon:$S,CheckSquareIcon:Z1,ChefHat:GG,ChefHatIcon:GG,Cherry:WG,CherryIcon:WG,ChevronDown:Wi,ChevronDownCircle:mk,ChevronDownCircleIcon:mk,ChevronDownIcon:Wi,ChevronDownSquare:US,ChevronDownSquareIcon:US,ChevronFirst:KG,ChevronFirstIcon:KG,ChevronLast:YG,ChevronLastIcon:YG,ChevronLeft:$o,ChevronLeftCircle:fk,ChevronLeftCircleIcon:fk,ChevronLeftIcon:$o,ChevronLeftSquare:qS,ChevronLeftSquareIcon:qS,ChevronRight:va,ChevronRightCircle:pk,ChevronRightCircleIcon:pk,ChevronRightIcon:va,ChevronRightSquare:VS,ChevronRightSquareIcon:VS,ChevronUp:Jf,ChevronUpCircle:xk,ChevronUpCircleIcon:xk,ChevronUpIcon:Jf,ChevronUpSquare:HS,ChevronUpSquareIcon:HS,ChevronsDown:XG,ChevronsDownIcon:XG,ChevronsDownUp:ZG,ChevronsDownUpIcon:ZG,ChevronsLeft:eW,ChevronsLeftIcon:eW,ChevronsLeftRight:JG,ChevronsLeftRightEllipsis:QG,ChevronsLeftRightEllipsisIcon:QG,ChevronsLeftRightIcon:JG,ChevronsRight:sW,ChevronsRightIcon:sW,ChevronsRightLeft:tW,ChevronsRightLeftIcon:tW,ChevronsUp:rW,ChevronsUpDown:qp,ChevronsUpDownIcon:qp,ChevronsUpIcon:rW,Chrome:L4,ChromeIcon:L4,Church:nW,ChurchIcon:nW,Cigarette:iW,CigaretteIcon:iW,CigaretteOff:aW,CigaretteOffIcon:aW,Circle:Ld,CircleAlert:Oi,CircleAlertIcon:Oi,CircleArrowDown:ak,CircleArrowDownIcon:ak,CircleArrowLeft:ik,CircleArrowLeftIcon:ik,CircleArrowOutDownLeft:ok,CircleArrowOutDownLeftIcon:ok,CircleArrowOutDownRight:lk,CircleArrowOutDownRightIcon:lk,CircleArrowOutUpLeft:ck,CircleArrowOutUpLeftIcon:ck,CircleArrowOutUpRight:dk,CircleArrowOutUpRightIcon:dk,CircleArrowRight:uk,CircleArrowRightIcon:uk,CircleArrowUp:hk,CircleArrowUpIcon:hk,CircleCheck:In,CircleCheckBig:di,CircleCheckBigIcon:di,CircleCheckIcon:In,CircleChevronDown:mk,CircleChevronDownIcon:mk,CircleChevronLeft:fk,CircleChevronLeftIcon:fk,CircleChevronRight:pk,CircleChevronRightIcon:pk,CircleChevronUp:xk,CircleChevronUpIcon:xk,CircleDashed:oW,CircleDashedIcon:oW,CircleDivide:gk,CircleDivideIcon:gk,CircleDollarSign:lW,CircleDollarSignIcon:lW,CircleDot:dW,CircleDotDashed:cW,CircleDotDashedIcon:cW,CircleDotIcon:dW,CircleEllipsis:uW,CircleEllipsisIcon:uW,CircleEqual:hW,CircleEqualIcon:hW,CircleFadingArrowUp:mW,CircleFadingArrowUpIcon:mW,CircleFadingPlus:fW,CircleFadingPlusIcon:fW,CircleGauge:yk,CircleGaugeIcon:yk,CircleHelp:G1,CircleHelpIcon:G1,CircleIcon:Ld,CircleMinus:vk,CircleMinusIcon:vk,CircleOff:pW,CircleOffIcon:pW,CircleParking:_k,CircleParkingIcon:_k,CircleParkingOff:bk,CircleParkingOffIcon:bk,CirclePause:wk,CirclePauseIcon:wk,CirclePercent:jk,CirclePercentIcon:jk,CirclePlay:rf,CirclePlayIcon:rf,CirclePlus:Nk,CirclePlusIcon:Nk,CirclePower:kk,CirclePowerIcon:kk,CircleSlash:xW,CircleSlash2:Sk,CircleSlash2Icon:Sk,CircleSlashIcon:xW,CircleSlashed:Sk,CircleSlashedIcon:Sk,CircleStop:Ck,CircleStopIcon:Ck,CircleUser:Ek,CircleUserIcon:Ek,CircleUserRound:Tk,CircleUserRoundIcon:Tk,CircleX:Sc,CircleXIcon:Sc,CircuitBoard:gW,CircuitBoardIcon:gW,Citrus:yW,CitrusIcon:yW,Clapperboard:vW,ClapperboardIcon:vW,Clipboard:SW,ClipboardCheck:uA,ClipboardCheckIcon:uA,ClipboardCopy:bW,ClipboardCopyIcon:bW,ClipboardEdit:Mk,ClipboardEditIcon:Mk,ClipboardIcon:SW,ClipboardList:Zw,ClipboardListIcon:Zw,ClipboardMinus:_W,ClipboardMinusIcon:_W,ClipboardPaste:wW,ClipboardPasteIcon:wW,ClipboardPen:Mk,ClipboardPenIcon:Mk,ClipboardPenLine:Ak,ClipboardPenLineIcon:Ak,ClipboardPlus:jW,ClipboardPlusIcon:jW,ClipboardSignature:Ak,ClipboardSignatureIcon:Ak,ClipboardType:NW,ClipboardTypeIcon:NW,ClipboardX:kW,ClipboardXIcon:kW,Clock:fn,Clock1:CW,Clock10:TW,Clock10Icon:TW,Clock11:EW,Clock11Icon:EW,Clock12:AW,Clock12Icon:AW,Clock1Icon:CW,Clock2:MW,Clock2Icon:MW,Clock3:IW,Clock3Icon:IW,Clock4:LW,Clock4Icon:LW,Clock5:PW,Clock5Icon:PW,Clock6:DW,Clock6Icon:DW,Clock7:RW,Clock7Icon:RW,Clock8:OW,Clock8Icon:OW,Clock9:FW,Clock9Icon:FW,ClockAlert:BW,ClockAlertIcon:BW,ClockArrowDown:zW,ClockArrowDownIcon:zW,ClockArrowUp:$W,ClockArrowUpIcon:$W,ClockIcon:fn,Cloud:sK,CloudAlert:UW,CloudAlertIcon:UW,CloudCog:qW,CloudCogIcon:qW,CloudDownload:Ik,CloudDownloadIcon:Ik,CloudDrizzle:VW,CloudDrizzleIcon:VW,CloudFog:HW,CloudFogIcon:HW,CloudHail:GW,CloudHailIcon:GW,CloudIcon:sK,CloudLightning:WW,CloudLightningIcon:WW,CloudMoon:YW,CloudMoonIcon:YW,CloudMoonRain:KW,CloudMoonRainIcon:KW,CloudOff:ZW,CloudOffIcon:ZW,CloudRain:QW,CloudRainIcon:QW,CloudRainWind:XW,CloudRainWindIcon:XW,CloudSnow:JW,CloudSnowIcon:JW,CloudSun:tK,CloudSunIcon:tK,CloudSunRain:eK,CloudSunRainIcon:eK,CloudUpload:Lk,CloudUploadIcon:Lk,Cloudy:rK,CloudyIcon:rK,Clover:nb,CloverIcon:nb,Club:nK,ClubIcon:nK,Code:P4,Code2:W1,Code2Icon:W1,CodeIcon:P4,CodeSquare:GS,CodeSquareIcon:GS,CodeXml:W1,CodeXmlIcon:W1,Codepen:aK,CodepenIcon:aK,Codesandbox:iK,CodesandboxIcon:iK,Coffee:D4,CoffeeIcon:D4,Cog:oK,CogIcon:oK,Coins:hR,CoinsIcon:hR,Columns:Pk,Columns2:Pk,Columns2Icon:Pk,Columns3:Dk,Columns3Icon:Dk,Columns4:lK,Columns4Icon:lK,ColumnsIcon:Pk,Combine:cK,CombineIcon:cK,Command:dK,CommandIcon:dK,Compass:hA,CompassIcon:hA,Component:uK,ComponentIcon:uK,Computer:hK,ComputerIcon:hK,ConciergeBell:mK,ConciergeBellIcon:mK,Cone:fK,ConeIcon:fK,Construction:pK,ConstructionIcon:pK,Contact:R4,Contact2:Rk,Contact2Icon:Rk,ContactIcon:R4,ContactRound:Rk,ContactRoundIcon:Rk,Container:xK,ContainerIcon:xK,Contrast:gK,ContrastIcon:gK,Cookie:yK,CookieIcon:yK,CookingPot:vK,CookingPotIcon:vK,Copy:Ra,CopyCheck:bK,CopyCheckIcon:bK,CopyIcon:Ra,CopyMinus:_K,CopyMinusIcon:_K,CopyPlus:wK,CopyPlusIcon:wK,CopySlash:jK,CopySlashIcon:jK,CopyX:NK,CopyXIcon:NK,Copyleft:kK,CopyleftIcon:kK,Copyright:SK,CopyrightIcon:SK,CornerDownLeft:CK,CornerDownLeftIcon:CK,CornerDownRight:TK,CornerDownRightIcon:TK,CornerLeftDown:EK,CornerLeftDownIcon:EK,CornerLeftUp:AK,CornerLeftUpIcon:AK,CornerRightDown:MK,CornerRightDownIcon:MK,CornerRightUp:IK,CornerRightUpIcon:IK,CornerUpLeft:LK,CornerUpLeftIcon:LK,CornerUpRight:PK,CornerUpRightIcon:PK,Cpu:DK,CpuIcon:DK,CreativeCommons:RK,CreativeCommonsIcon:RK,CreditCard:Vp,CreditCardIcon:Vp,Croissant:OK,CroissantIcon:OK,Crop:FK,CropIcon:FK,Cross:BK,CrossIcon:BK,Crosshair:zK,CrosshairIcon:zK,Crown:Zh,CrownIcon:Zh,Cuboid:$K,CuboidIcon:$K,CupSoda:UK,CupSodaIcon:UK,CurlyBraces:HN,CurlyBracesIcon:HN,Currency:qK,CurrencyIcon:qK,Cylinder:VK,CylinderIcon:VK,Dam:HK,DamIcon:HK,Database:mR,DatabaseBackup:GK,DatabaseBackupIcon:GK,DatabaseIcon:mR,DatabaseZap:WK,DatabaseZapIcon:WK,Delete:KK,DeleteIcon:KK,Dessert:YK,DessertIcon:YK,Diameter:ZK,DiameterIcon:ZK,Diamond:JK,DiamondIcon:JK,DiamondMinus:XK,DiamondMinusIcon:XK,DiamondPercent:Ok,DiamondPercentIcon:Ok,DiamondPlus:QK,DiamondPlusIcon:QK,Dice1:eY,Dice1Icon:eY,Dice2:tY,Dice2Icon:tY,Dice3:sY,Dice3Icon:sY,Dice4:rY,Dice4Icon:rY,Dice5:nY,Dice5Icon:nY,Dice6:aY,Dice6Icon:aY,Dices:iY,DicesIcon:iY,Diff:oY,DiffIcon:oY,Disc:uY,Disc2:lY,Disc2Icon:lY,Disc3:cY,Disc3Icon:cY,DiscAlbum:dY,DiscAlbumIcon:dY,DiscIcon:uY,Divide:hY,DivideCircle:gk,DivideCircleIcon:gk,DivideIcon:hY,DivideSquare:ZS,DivideSquareIcon:ZS,Dna:fY,DnaIcon:fY,DnaOff:mY,DnaOffIcon:mY,Dock:pY,DockIcon:pY,Dog:xY,DogIcon:xY,DollarSign:wl,DollarSignIcon:wl,Donut:gY,DonutIcon:gY,DoorClosed:yY,DoorClosedIcon:yY,DoorOpen:sv,DoorOpenIcon:sv,Dot:vY,DotIcon:vY,DotSquare:XS,DotSquareIcon:XS,Download:Ya,DownloadCloud:Ik,DownloadCloudIcon:Ik,DownloadIcon:Ya,DraftingCompass:bY,DraftingCompassIcon:bY,Drama:_Y,DramaIcon:_Y,Dribbble:wY,DribbbleIcon:wY,Drill:jY,DrillIcon:jY,Droplet:NY,DropletIcon:NY,Droplets:ky,DropletsIcon:ky,Drum:kY,DrumIcon:kY,Drumstick:SY,DrumstickIcon:SY,Dumbbell:CY,DumbbellIcon:CY,Ear:EY,EarIcon:EY,EarOff:TY,EarOffIcon:TY,Earth:Fk,EarthIcon:Fk,EarthLock:AY,EarthLockIcon:AY,Eclipse:MY,EclipseIcon:MY,Edit:sd,Edit2:R0,Edit2Icon:R0,Edit3:D0,Edit3Icon:D0,EditIcon:sd,Egg:mA,EggFried:IY,EggFriedIcon:IY,EggIcon:mA,EggOff:LY,EggOffIcon:LY,Ellipsis:Lp,EllipsisIcon:Lp,EllipsisVertical:Yx,EllipsisVerticalIcon:Yx,Equal:RY,EqualApproximately:PY,EqualApproximatelyIcon:PY,EqualIcon:RY,EqualNot:DY,EqualNotIcon:DY,EqualSquare:QS,EqualSquareIcon:QS,Eraser:OY,EraserIcon:OY,EthernetPort:FY,EthernetPortIcon:FY,Euro:BY,EuroIcon:BY,Expand:zY,ExpandIcon:zY,ExternalLink:Qr,ExternalLinkIcon:Qr,Eye:bn,EyeClosed:$Y,EyeClosedIcon:$Y,EyeIcon:bn,EyeOff:Xh,EyeOffIcon:Xh,Facebook:yu,FacebookIcon:yu,Factory:UY,FactoryIcon:UY,Fan:qY,FanIcon:qY,FastForward:VY,FastForwardIcon:VY,Feather:HY,FeatherIcon:HY,Fence:GY,FenceIcon:GY,FerrisWheel:WY,FerrisWheelIcon:WY,Figma:KY,FigmaIcon:KY,File:fA,FileArchive:YY,FileArchiveIcon:YY,FileAudio:XY,FileAudio2:ZY,FileAudio2Icon:ZY,FileAudioIcon:XY,FileAxis3D:Bk,FileAxis3DIcon:Bk,FileAxis3d:Bk,FileAxis3dIcon:Bk,FileBadge:JY,FileBadge2:QY,FileBadge2Icon:QY,FileBadgeIcon:JY,FileBarChart:zk,FileBarChart2:$k,FileBarChart2Icon:$k,FileBarChartIcon:zk,FileBox:eZ,FileBoxIcon:eZ,FileChartColumn:$k,FileChartColumnIcon:$k,FileChartColumnIncreasing:zk,FileChartColumnIncreasingIcon:zk,FileChartLine:Uk,FileChartLineIcon:Uk,FileChartPie:qk,FileChartPieIcon:qk,FileCheck:fR,FileCheck2:tZ,FileCheck2Icon:tZ,FileCheckIcon:fR,FileClock:sZ,FileClockIcon:sZ,FileCode:nZ,FileCode2:rZ,FileCode2Icon:rZ,FileCodeIcon:nZ,FileCog:Vk,FileCog2:Vk,FileCog2Icon:Vk,FileCogIcon:Vk,FileDiff:aZ,FileDiffIcon:aZ,FileDigit:iZ,FileDigitIcon:iZ,FileDown:O4,FileDownIcon:O4,FileEdit:Gk,FileEditIcon:Gk,FileHeart:oZ,FileHeartIcon:oZ,FileIcon:fA,FileImage:hb,FileImageIcon:hb,FileInput:lZ,FileInputIcon:lZ,FileJson:dZ,FileJson2:cZ,FileJson2Icon:cZ,FileJsonIcon:dZ,FileKey:hZ,FileKey2:uZ,FileKey2Icon:uZ,FileKeyIcon:hZ,FileLineChart:Uk,FileLineChartIcon:Uk,FileLock:fZ,FileLock2:mZ,FileLock2Icon:mZ,FileLockIcon:fZ,FileMinus:xZ,FileMinus2:pZ,FileMinus2Icon:pZ,FileMinusIcon:xZ,FileMusic:gZ,FileMusicIcon:gZ,FileOutput:yZ,FileOutputIcon:yZ,FilePen:Gk,FilePenIcon:Gk,FilePenLine:Hk,FilePenLineIcon:Hk,FilePieChart:qk,FilePieChartIcon:qk,FilePlus:bZ,FilePlus2:vZ,FilePlus2Icon:vZ,FilePlusIcon:bZ,FileQuestion:_Z,FileQuestionIcon:_Z,FileScan:wZ,FileScanIcon:wZ,FileSearch:NZ,FileSearch2:jZ,FileSearch2Icon:jZ,FileSearchIcon:NZ,FileSignature:Hk,FileSignatureIcon:Hk,FileSliders:kZ,FileSlidersIcon:kZ,FileSpreadsheet:mb,FileSpreadsheetIcon:mb,FileStack:pR,FileStackIcon:pR,FileSymlink:SZ,FileSymlinkIcon:SZ,FileTerminal:CZ,FileTerminalIcon:CZ,FileText:ln,FileTextIcon:ln,FileType:EZ,FileType2:TZ,FileType2Icon:TZ,FileTypeIcon:EZ,FileUp:AZ,FileUpIcon:AZ,FileUser:MZ,FileUserIcon:MZ,FileVideo:xR,FileVideo2:IZ,FileVideo2Icon:IZ,FileVideoIcon:xR,FileVolume:PZ,FileVolume2:LZ,FileVolume2Icon:LZ,FileVolumeIcon:PZ,FileWarning:DZ,FileWarningIcon:DZ,FileX:OZ,FileX2:RZ,FileX2Icon:RZ,FileXIcon:OZ,Files:FZ,FilesIcon:FZ,Film:gh,FilmIcon:gh,Filter:Sy,FilterIcon:Sy,FilterX:BZ,FilterXIcon:BZ,Fingerprint:zZ,FingerprintIcon:zZ,FireExtinguisher:$Z,FireExtinguisherIcon:$Z,Fish:VZ,FishIcon:VZ,FishOff:UZ,FishOffIcon:UZ,FishSymbol:qZ,FishSymbolIcon:qZ,Flag:fb,FlagIcon:fb,FlagOff:HZ,FlagOffIcon:HZ,FlagTriangleLeft:GZ,FlagTriangleLeftIcon:GZ,FlagTriangleRight:WZ,FlagTriangleRightIcon:WZ,Flame:mc,FlameIcon:mc,FlameKindling:KZ,FlameKindlingIcon:KZ,Flashlight:ZZ,FlashlightIcon:ZZ,FlashlightOff:YZ,FlashlightOffIcon:YZ,FlaskConical:Xw,FlaskConicalIcon:Xw,FlaskConicalOff:XZ,FlaskConicalOffIcon:XZ,FlaskRound:QZ,FlaskRoundIcon:QZ,FlipHorizontal:gR,FlipHorizontal2:JZ,FlipHorizontal2Icon:JZ,FlipHorizontalIcon:gR,FlipVertical:tX,FlipVertical2:eX,FlipVertical2Icon:eX,FlipVerticalIcon:tX,Flower:sX,Flower2:vy,Flower2Icon:vy,FlowerIcon:sX,Focus:rX,FocusIcon:rX,FoldHorizontal:nX,FoldHorizontalIcon:nX,FoldVertical:aX,FoldVerticalIcon:aX,Folder:IX,FolderArchive:iX,FolderArchiveIcon:iX,FolderCheck:oX,FolderCheckIcon:oX,FolderClock:lX,FolderClockIcon:lX,FolderClosed:cX,FolderClosedIcon:cX,FolderCode:dX,FolderCodeIcon:dX,FolderCog:Wk,FolderCog2:Wk,FolderCog2Icon:Wk,FolderCogIcon:Wk,FolderDot:uX,FolderDotIcon:uX,FolderDown:hX,FolderDownIcon:hX,FolderEdit:Kk,FolderEditIcon:Kk,FolderGit:fX,FolderGit2:mX,FolderGit2Icon:mX,FolderGitIcon:fX,FolderHeart:pX,FolderHeartIcon:pX,FolderIcon:IX,FolderInput:xX,FolderInputIcon:xX,FolderKanban:gX,FolderKanbanIcon:gX,FolderKey:yX,FolderKeyIcon:yX,FolderLock:vX,FolderLockIcon:vX,FolderMinus:bX,FolderMinusIcon:bX,FolderOpen:Qh,FolderOpenDot:_X,FolderOpenDotIcon:_X,FolderOpenIcon:Qh,FolderOutput:wX,FolderOutputIcon:wX,FolderPen:Kk,FolderPenIcon:Kk,FolderPlus:jX,FolderPlusIcon:jX,FolderRoot:NX,FolderRootIcon:NX,FolderSearch:SX,FolderSearch2:kX,FolderSearch2Icon:kX,FolderSearchIcon:SX,FolderSymlink:CX,FolderSymlinkIcon:CX,FolderSync:TX,FolderSyncIcon:TX,FolderTree:EX,FolderTreeIcon:EX,FolderUp:AX,FolderUpIcon:AX,FolderX:MX,FolderXIcon:MX,Folders:LX,FoldersIcon:LX,Footprints:PX,FootprintsIcon:PX,ForkKnife:OC,ForkKnifeCrossed:RC,ForkKnifeCrossedIcon:RC,ForkKnifeIcon:OC,Forklift:DX,ForkliftIcon:DX,FormInput:yS,FormInputIcon:yS,Forward:RX,ForwardIcon:RX,Frame:OX,FrameIcon:OX,Framer:FX,FramerIcon:FX,Frown:BX,FrownIcon:BX,Fuel:zX,FuelIcon:zX,Fullscreen:$X,FullscreenIcon:$X,FunctionSquare:JS,FunctionSquareIcon:JS,GalleryHorizontal:qX,GalleryHorizontalEnd:UX,GalleryHorizontalEndIcon:UX,GalleryHorizontalIcon:qX,GalleryThumbnails:VX,GalleryThumbnailsIcon:VX,GalleryVertical:GX,GalleryVerticalEnd:HX,GalleryVerticalEndIcon:HX,GalleryVerticalIcon:GX,Gamepad:KX,Gamepad2:WX,Gamepad2Icon:WX,GamepadIcon:KX,GanttChart:sk,GanttChartIcon:sk,GanttChartSquare:j0,GanttChartSquareIcon:j0,Gauge:YX,GaugeCircle:yk,GaugeCircleIcon:yk,GaugeIcon:YX,Gavel:ZX,GavelIcon:ZX,Gem:XX,GemIcon:XX,Ghost:F4,GhostIcon:F4,Gift:ii,GiftIcon:ii,GitBranch:JX,GitBranchIcon:JX,GitBranchPlus:QX,GitBranchPlusIcon:QX,GitCommit:Yk,GitCommitHorizontal:Yk,GitCommitHorizontalIcon:Yk,GitCommitIcon:Yk,GitCommitVertical:eQ,GitCommitVerticalIcon:eQ,GitCompare:sQ,GitCompareArrows:tQ,GitCompareArrowsIcon:tQ,GitCompareIcon:sQ,GitFork:rQ,GitForkIcon:rQ,GitGraph:nQ,GitGraphIcon:nQ,GitMerge:aQ,GitMergeIcon:aQ,GitPullRequest:uQ,GitPullRequestArrow:iQ,GitPullRequestArrowIcon:iQ,GitPullRequestClosed:oQ,GitPullRequestClosedIcon:oQ,GitPullRequestCreate:cQ,GitPullRequestCreateArrow:lQ,GitPullRequestCreateArrowIcon:lQ,GitPullRequestCreateIcon:cQ,GitPullRequestDraft:dQ,GitPullRequestDraftIcon:dQ,GitPullRequestIcon:uQ,Github:hQ,GithubIcon:hQ,Gitlab:mQ,GitlabIcon:mQ,GlassWater:fQ,GlassWaterIcon:fQ,Glasses:pQ,GlassesIcon:pQ,Globe:fc,Globe2:Fk,Globe2Icon:Fk,GlobeIcon:fc,GlobeLock:xQ,GlobeLockIcon:xQ,Goal:gQ,GoalIcon:gQ,Grab:yQ,GrabIcon:yQ,GraduationCap:Md,GraduationCapIcon:Md,Grape:vQ,GrapeIcon:vQ,Grid:Bx,Grid2X2:Xk,Grid2X2Icon:Xk,Grid2X2Plus:Zk,Grid2X2PlusIcon:Zk,Grid2x2:Xk,Grid2x2Check:bQ,Grid2x2CheckIcon:bQ,Grid2x2Icon:Xk,Grid2x2Plus:Zk,Grid2x2PlusIcon:Zk,Grid2x2X:_Q,Grid2x2XIcon:_Q,Grid3X3:Bx,Grid3X3Icon:Bx,Grid3x3:Bx,Grid3x3Icon:Bx,GridIcon:Bx,Grip:jQ,GripHorizontal:wQ,GripHorizontalIcon:wQ,GripIcon:jQ,GripVertical:vu,GripVerticalIcon:vu,Group:NQ,GroupIcon:NQ,Guitar:kQ,GuitarIcon:kQ,Ham:SQ,HamIcon:SQ,Hammer:yR,HammerIcon:yR,Hand:vR,HandCoins:CQ,HandCoinsIcon:CQ,HandHeart:TQ,HandHeartIcon:TQ,HandHelping:fy,HandHelpingIcon:fy,HandIcon:vR,HandMetal:EQ,HandMetalIcon:EQ,HandPlatter:AQ,HandPlatterIcon:AQ,Handshake:Qw,HandshakeIcon:Qw,HardDrive:bR,HardDriveDownload:MQ,HardDriveDownloadIcon:MQ,HardDriveIcon:bR,HardDriveUpload:IQ,HardDriveUploadIcon:IQ,HardHat:LQ,HardHatIcon:LQ,Hash:Jw,HashIcon:Jw,Haze:PQ,HazeIcon:PQ,HdmiPort:DQ,HdmiPortIcon:DQ,Heading:BQ,Heading1:pA,Heading1Icon:pA,Heading2:xA,Heading2Icon:xA,Heading3:_R,Heading3Icon:_R,Heading4:RQ,Heading4Icon:RQ,Heading5:OQ,Heading5Icon:OQ,Heading6:FQ,Heading6Icon:FQ,HeadingIcon:BQ,HeadphoneOff:zQ,HeadphoneOffIcon:zQ,Headphones:$Q,HeadphonesIcon:$Q,Headset:UQ,HeadsetIcon:UQ,Heart:ci,HeartCrack:qQ,HeartCrackIcon:qQ,HeartHandshake:VQ,HeartHandshakeIcon:VQ,HeartIcon:ci,HeartOff:HQ,HeartOffIcon:HQ,HeartPulse:GQ,HeartPulseIcon:GQ,Heater:WQ,HeaterIcon:WQ,HelpCircle:G1,HelpCircleIcon:G1,HelpingHand:fy,HelpingHandIcon:fy,Hexagon:KQ,HexagonIcon:KQ,Highlighter:YQ,HighlighterIcon:YQ,History:gA,HistoryIcon:gA,Home:En,HomeIcon:En,Hop:XQ,HopIcon:XQ,HopOff:ZQ,HopOffIcon:ZQ,Hospital:QQ,HospitalIcon:QQ,Hotel:JQ,HotelIcon:JQ,Hourglass:eJ,HourglassIcon:eJ,House:En,HouseIcon:En,HousePlug:tJ,HousePlugIcon:tJ,HousePlus:sJ,HousePlusIcon:sJ,IceCream:Jk,IceCream2:Qk,IceCream2Icon:Qk,IceCreamBowl:Qk,IceCreamBowlIcon:Qk,IceCreamCone:Jk,IceCreamConeIcon:Jk,IceCreamIcon:Jk,Icon:pYe,IdCard:rJ,IdCardIcon:rJ,Image:ml,ImageDown:nJ,ImageDownIcon:nJ,ImageIcon:ml,ImageMinus:aJ,ImageMinusIcon:aJ,ImageOff:iJ,ImageOffIcon:iJ,ImagePlay:oJ,ImagePlayIcon:oJ,ImagePlus:rv,ImagePlusIcon:rv,ImageUp:lJ,ImageUpIcon:lJ,ImageUpscale:cJ,ImageUpscaleIcon:cJ,Images:dJ,ImagesIcon:dJ,Import:uJ,ImportIcon:uJ,Inbox:ej,InboxIcon:ej,Indent:tS,IndentDecrease:eS,IndentDecreaseIcon:eS,IndentIcon:tS,IndentIncrease:tS,IndentIncreaseIcon:tS,IndianRupee:hJ,IndianRupeeIcon:hJ,Infinity:mJ,InfinityIcon:mJ,Info:B4,InfoIcon:B4,Inspect:aC,InspectIcon:aC,InspectionPanel:fJ,InspectionPanelIcon:fJ,Instagram:Jd,InstagramIcon:Jd,Italic:tj,ItalicIcon:tj,IterationCcw:pJ,IterationCcwIcon:pJ,IterationCw:xJ,IterationCwIcon:xJ,JapaneseYen:gJ,JapaneseYenIcon:gJ,Joystick:yJ,JoystickIcon:yJ,Kanban:nv,KanbanIcon:nv,KanbanSquare:eC,KanbanSquareDashed:WS,KanbanSquareDashedIcon:WS,KanbanSquareIcon:eC,Key:ep,KeyIcon:ep,KeyRound:z4,KeyRoundIcon:z4,KeySquare:vJ,KeySquareIcon:vJ,Keyboard:wJ,KeyboardIcon:wJ,KeyboardMusic:bJ,KeyboardMusicIcon:bJ,KeyboardOff:_J,KeyboardOffIcon:_J,Lamp:TJ,LampCeiling:jJ,LampCeilingIcon:jJ,LampDesk:NJ,LampDeskIcon:NJ,LampFloor:kJ,LampFloorIcon:kJ,LampIcon:TJ,LampWallDown:SJ,LampWallDownIcon:SJ,LampWallUp:CJ,LampWallUpIcon:CJ,LandPlot:EJ,LandPlotIcon:EJ,Landmark:AJ,LandmarkIcon:AJ,Languages:MJ,LanguagesIcon:MJ,Laptop:LJ,Laptop2:sS,Laptop2Icon:sS,LaptopIcon:LJ,LaptopMinimal:sS,LaptopMinimalCheck:IJ,LaptopMinimalCheckIcon:IJ,LaptopMinimalIcon:sS,Lasso:DJ,LassoIcon:DJ,LassoSelect:PJ,LassoSelectIcon:PJ,Laugh:RJ,LaughIcon:RJ,Layers:wR,Layers2:OJ,Layers2Icon:OJ,Layers3:FJ,Layers3Icon:FJ,LayersIcon:wR,Layout:Y1,LayoutDashboard:$4,LayoutDashboardIcon:$4,LayoutGrid:xf,LayoutGridIcon:xf,LayoutIcon:Y1,LayoutList:BJ,LayoutListIcon:BJ,LayoutPanelLeft:zJ,LayoutPanelLeftIcon:zJ,LayoutPanelTop:$J,LayoutPanelTopIcon:$J,LayoutTemplate:U4,LayoutTemplateIcon:U4,Leaf:UJ,LeafIcon:UJ,LeafyGreen:qJ,LeafyGreenIcon:qJ,Lectern:VJ,LecternIcon:VJ,LetterText:HJ,LetterTextIcon:HJ,Library:q4,LibraryBig:GJ,LibraryBigIcon:GJ,LibraryIcon:q4,LibrarySquare:tC,LibrarySquareIcon:tC,LifeBuoy:yA,LifeBuoyIcon:yA,Ligature:WJ,LigatureIcon:WJ,Lightbulb:sj,LightbulbIcon:sj,LightbulbOff:KJ,LightbulbOffIcon:KJ,LineChart:JN,LineChartIcon:JN,Link:po,Link2:tl,Link2Icon:tl,Link2Off:YJ,Link2OffIcon:YJ,LinkIcon:po,Linkedin:Jh,LinkedinIcon:Jh,List:em,ListCheck:ZJ,ListCheckIcon:ZJ,ListChecks:pb,ListChecksIcon:pb,ListCollapse:XJ,ListCollapseIcon:XJ,ListEnd:QJ,ListEndIcon:QJ,ListFilter:jR,ListFilterIcon:jR,ListIcon:em,ListMinus:JJ,ListMinusIcon:JJ,ListMusic:eee,ListMusicIcon:eee,ListOrdered:Cy,ListOrderedIcon:Cy,ListPlus:tee,ListPlusIcon:tee,ListRestart:see,ListRestartIcon:see,ListStart:ree,ListStartIcon:ree,ListTodo:nee,ListTodoIcon:nee,ListTree:aee,ListTreeIcon:aee,ListVideo:iee,ListVideoIcon:iee,ListX:oee,ListXIcon:oee,Loader:cee,Loader2:es,Loader2Icon:es,LoaderCircle:es,LoaderCircleIcon:es,LoaderIcon:cee,LoaderPinwheel:lee,LoaderPinwheelIcon:lee,Locate:vA,LocateFixed:dee,LocateFixedIcon:dee,LocateIcon:vA,LocateOff:uee,LocateOffIcon:uee,Lock:Hc,LockIcon:Hc,LockKeyhole:hee,LockKeyholeIcon:hee,LockKeyholeOpen:rS,LockKeyholeOpenIcon:rS,LockOpen:nS,LockOpenIcon:nS,LogIn:V4,LogInIcon:V4,LogOut:bA,LogOutIcon:bA,Logs:mee,LogsIcon:mee,Lollipop:fee,LollipopIcon:fee,LucideAArrowDown:AU,LucideAArrowUp:MU,LucideALargeSmall:IU,LucideAccessibility:LU,LucideActivity:vh,LucideActivitySquare:SS,LucideAirVent:PU,LucideAirplay:DU,LucideAlarmCheck:MN,LucideAlarmClock:OU,LucideAlarmClockCheck:MN,LucideAlarmClockMinus:IN,LucideAlarmClockOff:RU,LucideAlarmClockPlus:LN,LucideAlarmMinus:IN,LucideAlarmPlus:LN,LucideAlarmSmoke:FU,LucideAlbum:BU,LucideAlertCircle:Oi,LucideAlertOctagon:K1,LucideAlertTriangle:id,LucideAlignCenter:T4,LucideAlignCenterHorizontal:zU,LucideAlignCenterVertical:$U,LucideAlignEndHorizontal:UU,LucideAlignEndVertical:qU,LucideAlignHorizontalDistributeCenter:VU,LucideAlignHorizontalDistributeEnd:HU,LucideAlignHorizontalDistributeStart:GU,LucideAlignHorizontalJustifyCenter:WU,LucideAlignHorizontalJustifyEnd:KU,LucideAlignHorizontalJustifyStart:YU,LucideAlignHorizontalSpaceAround:ZU,LucideAlignHorizontalSpaceBetween:XU,LucideAlignJustify:QU,LucideAlignLeft:E4,LucideAlignRight:A4,LucideAlignStartHorizontal:JU,LucideAlignStartVertical:eq,LucideAlignVerticalDistributeCenter:tq,LucideAlignVerticalDistributeEnd:sq,LucideAlignVerticalDistributeStart:rq,LucideAlignVerticalJustifyCenter:nq,LucideAlignVerticalJustifyEnd:aq,LucideAlignVerticalJustifyStart:iq,LucideAlignVerticalSpaceAround:oq,LucideAlignVerticalSpaceBetween:lq,LucideAmbulance:cq,LucideAmpersand:dq,LucideAmpersands:uq,LucideAmphora:hq,LucideAnchor:mq,LucideAngry:fq,LucideAnnoyed:pq,LucideAntenna:xq,LucideAnvil:gq,LucideAperture:yq,LucideAppWindow:tR,LucideAppWindowMac:vq,LucideApple:bq,LucideArchive:Kw,LucideArchiveRestore:lA,LucideArchiveX:_q,LucideAreaChart:WN,LucideArmchair:wq,LucideArrowBigDown:Nq,LucideArrowBigDownDash:jq,LucideArrowBigLeft:Sq,LucideArrowBigLeftDash:kq,LucideArrowBigRight:Tq,LucideArrowBigRightDash:Cq,LucideArrowBigUp:Aq,LucideArrowBigUpDash:Eq,LucideArrowDown:Hu,LucideArrowDown01:Mq,LucideArrowDown10:Iq,LucideArrowDownAZ:PN,LucideArrowDownAz:PN,LucideArrowDownCircle:ak,LucideArrowDownFromLine:Lq,LucideArrowDownLeft:Pq,LucideArrowDownLeftFromCircle:ok,LucideArrowDownLeftFromSquare:MS,LucideArrowDownLeftSquare:CS,LucideArrowDownNarrowWide:Dq,LucideArrowDownRight:sR,LucideArrowDownRightFromCircle:lk,LucideArrowDownRightFromSquare:IS,LucideArrowDownRightSquare:TS,LucideArrowDownSquare:ES,LucideArrowDownToDot:Rq,LucideArrowDownToLine:Oq,LucideArrowDownUp:Fq,LucideArrowDownWideNarrow:DN,LucideArrowDownZA:RN,LucideArrowDownZa:RN,LucideArrowLeft:ka,LucideArrowLeftCircle:ik,LucideArrowLeftFromLine:Bq,LucideArrowLeftRight:zq,LucideArrowLeftSquare:AS,LucideArrowLeftToLine:$q,LucideArrowRight:Ha,LucideArrowRightCircle:uk,LucideArrowRightFromLine:Uq,LucideArrowRightLeft:ub,LucideArrowRightSquare:DS,LucideArrowRightToLine:qq,LucideArrowUp:Id,LucideArrowUp01:Vq,LucideArrowUp10:Hq,LucideArrowUpAZ:ON,LucideArrowUpAz:ON,LucideArrowUpCircle:hk,LucideArrowUpDown:Ad,LucideArrowUpFromDot:Gq,LucideArrowUpFromLine:Wq,LucideArrowUpLeft:Kq,LucideArrowUpLeftFromCircle:ck,LucideArrowUpLeftFromSquare:LS,LucideArrowUpLeftSquare:RS,LucideArrowUpNarrowWide:FN,LucideArrowUpRight:rR,LucideArrowUpRightFromCircle:dk,LucideArrowUpRightFromSquare:PS,LucideArrowUpRightSquare:OS,LucideArrowUpSquare:FS,LucideArrowUpToLine:Yq,LucideArrowUpWideNarrow:Zq,LucideArrowUpZA:BN,LucideArrowUpZa:BN,LucideArrowsUpFromLine:Xq,LucideAsterisk:Qq,LucideAsteriskSquare:BS,LucideAtSign:Jq,LucideAtom:eV,LucideAudioLines:tV,LucideAudioWaveform:sV,LucideAward:Yl,LucideAxe:rV,LucideAxis3D:zN,LucideAxis3d:zN,LucideBaby:nV,LucideBackpack:aV,LucideBadge:_V,LucideBadgeAlert:iV,LucideBadgeCent:oV,LucideBadgeCheck:$N,LucideBadgeDollarSign:lV,LucideBadgeEuro:cV,LucideBadgeHelp:dV,LucideBadgeIndianRupee:uV,LucideBadgeInfo:hV,LucideBadgeJapaneseYen:mV,LucideBadgeMinus:fV,LucideBadgePercent:pV,LucideBadgePlus:xV,LucideBadgePoundSterling:gV,LucideBadgeRussianRuble:yV,LucideBadgeSwissFranc:vV,LucideBadgeX:bV,LucideBaggageClaim:wV,LucideBan:nR,LucideBanana:jV,LucideBandage:NV,LucideBanknote:kV,LucideBarChart:ek,LucideBarChart2:tk,LucideBarChart3:ro,LucideBarChart4:QN,LucideBarChartBig:XN,LucideBarChartHorizontal:YN,LucideBarChartHorizontalBig:KN,LucideBarcode:SV,LucideBaseline:CV,LucideBath:Xf,LucideBattery:LV,LucideBatteryCharging:TV,LucideBatteryFull:EV,LucideBatteryLow:AV,LucideBatteryMedium:MV,LucideBatteryWarning:IV,LucideBeaker:PV,LucideBean:RV,LucideBeanOff:DV,LucideBed:Ny,LucideBedDouble:M4,LucideBedSingle:OV,LucideBeef:FV,LucideBeer:zV,LucideBeerOff:BV,LucideBell:_m,LucideBellDot:$V,LucideBellElectric:UV,LucideBellMinus:qV,LucideBellOff:ev,LucideBellPlus:VV,LucideBellRing:aR,LucideBetweenHorizonalEnd:UN,LucideBetweenHorizonalStart:qN,LucideBetweenHorizontalEnd:UN,LucideBetweenHorizontalStart:qN,LucideBetweenVerticalEnd:HV,LucideBetweenVerticalStart:GV,LucideBicepsFlexed:WV,LucideBike:KV,LucideBinary:YV,LucideBinoculars:ZV,LucideBiohazard:XV,LucideBird:QV,LucideBitcoin:JV,LucideBlend:eH,LucideBlinds:tH,LucideBlocks:sH,LucideBluetooth:iH,LucideBluetoothConnected:rH,LucideBluetoothOff:nH,LucideBluetoothSearching:aH,LucideBold:Yw,LucideBolt:oH,LucideBomb:lH,LucideBone:cH,LucideBook:MH,LucideBookA:dH,LucideBookAudio:uH,LucideBookCheck:hH,LucideBookCopy:mH,LucideBookDashed:VN,LucideBookDown:fH,LucideBookHeadphones:pH,LucideBookHeart:xH,LucideBookImage:gH,LucideBookKey:yH,LucideBookLock:vH,LucideBookMarked:bH,LucideBookMinus:_H,LucideBookOpen:bh,LucideBookOpenCheck:wH,LucideBookOpenText:jH,LucideBookPlus:NH,LucideBookTemplate:VN,LucideBookText:kH,LucideBookType:SH,LucideBookUp:TH,LucideBookUp2:CH,LucideBookUser:EH,LucideBookX:AH,LucideBookmark:ag,LucideBookmarkCheck:IH,LucideBookmarkMinus:LH,LucideBookmarkPlus:iR,LucideBookmarkX:PH,LucideBoomBox:DH,LucideBot:cA,LucideBotMessageSquare:RH,LucideBotOff:OH,LucideBox:FH,LucideBoxSelect:YS,LucideBoxes:BH,LucideBraces:HN,LucideBrackets:zH,LucideBrain:oR,LucideBrainCircuit:$H,LucideBrainCog:UH,LucideBrickWall:qH,LucideBriefcase:Gu,LucideBriefcaseBusiness:VH,LucideBriefcaseConveyorBelt:HH,LucideBriefcaseMedical:GH,LucideBringToFront:WH,LucideBrush:KH,LucideBug:XH,LucideBugOff:YH,LucideBugPlay:ZH,LucideBuilding:I4,LucideBuilding2:Sa,LucideBus:JH,LucideBusFront:QH,LucideCable:tG,LucideCableCar:eG,LucideCake:_h,LucideCakeSlice:sG,LucideCalculator:dA,LucideCalendar:on,LucideCalendar1:rG,LucideCalendarArrowDown:nG,LucideCalendarArrowUp:aG,LucideCalendarCheck:lR,LucideCalendarCheck2:iG,LucideCalendarClock:tv,LucideCalendarCog:oG,LucideCalendarDays:hd,LucideCalendarFold:lG,LucideCalendarHeart:cR,LucideCalendarMinus:dG,LucideCalendarMinus2:cG,LucideCalendarOff:dR,LucideCalendarPlus:rb,LucideCalendarPlus2:uG,LucideCalendarRange:hG,LucideCalendarSearch:mG,LucideCalendarSync:fG,LucideCalendarX:xG,LucideCalendarX2:pG,LucideCamera:Qf,LucideCameraOff:gG,LucideCandlestickChart:ZN,LucideCandy:bG,LucideCandyCane:yG,LucideCandyOff:vG,LucideCannabis:_G,LucideCaptions:GN,LucideCaptionsOff:wG,LucideCar:kG,LucideCarFront:jG,LucideCarTaxiFront:NG,LucideCaravan:SG,LucideCarrot:CG,LucideCaseLower:TG,LucideCaseSensitive:EG,LucideCaseUpper:AG,LucideCassetteTape:MG,LucideCast:IG,LucideCastle:LG,LucideCat:PG,LucideCctv:DG,LucideChartArea:WN,LucideChartBar:YN,LucideChartBarBig:KN,LucideChartBarDecreasing:RG,LucideChartBarIncreasing:OG,LucideChartBarStacked:FG,LucideChartCandlestick:ZN,LucideChartColumn:ro,LucideChartColumnBig:XN,LucideChartColumnDecreasing:BG,LucideChartColumnIncreasing:QN,LucideChartColumnStacked:zG,LucideChartGantt:$G,LucideChartLine:JN,LucideChartNetwork:UG,LucideChartNoAxesColumn:tk,LucideChartNoAxesColumnDecreasing:qG,LucideChartNoAxesColumnIncreasing:ek,LucideChartNoAxesCombined:VG,LucideChartNoAxesGantt:sk,LucideChartPie:rk,LucideChartScatter:nk,LucideChartSpline:HG,LucideCheck:Kn,LucideCheckCheck:uR,LucideCheckCircle:di,LucideCheckCircle2:In,LucideCheckSquare:Z1,LucideCheckSquare2:$S,LucideChefHat:GG,LucideCherry:WG,LucideChevronDown:Wi,LucideChevronDownCircle:mk,LucideChevronDownSquare:US,LucideChevronFirst:KG,LucideChevronLast:YG,LucideChevronLeft:$o,LucideChevronLeftCircle:fk,LucideChevronLeftSquare:qS,LucideChevronRight:va,LucideChevronRightCircle:pk,LucideChevronRightSquare:VS,LucideChevronUp:Jf,LucideChevronUpCircle:xk,LucideChevronUpSquare:HS,LucideChevronsDown:XG,LucideChevronsDownUp:ZG,LucideChevronsLeft:eW,LucideChevronsLeftRight:JG,LucideChevronsLeftRightEllipsis:QG,LucideChevronsRight:sW,LucideChevronsRightLeft:tW,LucideChevronsUp:rW,LucideChevronsUpDown:qp,LucideChrome:L4,LucideChurch:nW,LucideCigarette:iW,LucideCigaretteOff:aW,LucideCircle:Ld,LucideCircleAlert:Oi,LucideCircleArrowDown:ak,LucideCircleArrowLeft:ik,LucideCircleArrowOutDownLeft:ok,LucideCircleArrowOutDownRight:lk,LucideCircleArrowOutUpLeft:ck,LucideCircleArrowOutUpRight:dk,LucideCircleArrowRight:uk,LucideCircleArrowUp:hk,LucideCircleCheck:In,LucideCircleCheckBig:di,LucideCircleChevronDown:mk,LucideCircleChevronLeft:fk,LucideCircleChevronRight:pk,LucideCircleChevronUp:xk,LucideCircleDashed:oW,LucideCircleDivide:gk,LucideCircleDollarSign:lW,LucideCircleDot:dW,LucideCircleDotDashed:cW,LucideCircleEllipsis:uW,LucideCircleEqual:hW,LucideCircleFadingArrowUp:mW,LucideCircleFadingPlus:fW,LucideCircleGauge:yk,LucideCircleHelp:G1,LucideCircleMinus:vk,LucideCircleOff:pW,LucideCircleParking:_k,LucideCircleParkingOff:bk,LucideCirclePause:wk,LucideCirclePercent:jk,LucideCirclePlay:rf,LucideCirclePlus:Nk,LucideCirclePower:kk,LucideCircleSlash:xW,LucideCircleSlash2:Sk,LucideCircleSlashed:Sk,LucideCircleStop:Ck,LucideCircleUser:Ek,LucideCircleUserRound:Tk,LucideCircleX:Sc,LucideCircuitBoard:gW,LucideCitrus:yW,LucideClapperboard:vW,LucideClipboard:SW,LucideClipboardCheck:uA,LucideClipboardCopy:bW,LucideClipboardEdit:Mk,LucideClipboardList:Zw,LucideClipboardMinus:_W,LucideClipboardPaste:wW,LucideClipboardPen:Mk,LucideClipboardPenLine:Ak,LucideClipboardPlus:jW,LucideClipboardSignature:Ak,LucideClipboardType:NW,LucideClipboardX:kW,LucideClock:fn,LucideClock1:CW,LucideClock10:TW,LucideClock11:EW,LucideClock12:AW,LucideClock2:MW,LucideClock3:IW,LucideClock4:LW,LucideClock5:PW,LucideClock6:DW,LucideClock7:RW,LucideClock8:OW,LucideClock9:FW,LucideClockAlert:BW,LucideClockArrowDown:zW,LucideClockArrowUp:$W,LucideCloud:sK,LucideCloudAlert:UW,LucideCloudCog:qW,LucideCloudDownload:Ik,LucideCloudDrizzle:VW,LucideCloudFog:HW,LucideCloudHail:GW,LucideCloudLightning:WW,LucideCloudMoon:YW,LucideCloudMoonRain:KW,LucideCloudOff:ZW,LucideCloudRain:QW,LucideCloudRainWind:XW,LucideCloudSnow:JW,LucideCloudSun:tK,LucideCloudSunRain:eK,LucideCloudUpload:Lk,LucideCloudy:rK,LucideClover:nb,LucideClub:nK,LucideCode:P4,LucideCode2:W1,LucideCodeSquare:GS,LucideCodeXml:W1,LucideCodepen:aK,LucideCodesandbox:iK,LucideCoffee:D4,LucideCog:oK,LucideCoins:hR,LucideColumns:Pk,LucideColumns2:Pk,LucideColumns3:Dk,LucideColumns4:lK,LucideCombine:cK,LucideCommand:dK,LucideCompass:hA,LucideComponent:uK,LucideComputer:hK,LucideConciergeBell:mK,LucideCone:fK,LucideConstruction:pK,LucideContact:R4,LucideContact2:Rk,LucideContactRound:Rk,LucideContainer:xK,LucideContrast:gK,LucideCookie:yK,LucideCookingPot:vK,LucideCopy:Ra,LucideCopyCheck:bK,LucideCopyMinus:_K,LucideCopyPlus:wK,LucideCopySlash:jK,LucideCopyX:NK,LucideCopyleft:kK,LucideCopyright:SK,LucideCornerDownLeft:CK,LucideCornerDownRight:TK,LucideCornerLeftDown:EK,LucideCornerLeftUp:AK,LucideCornerRightDown:MK,LucideCornerRightUp:IK,LucideCornerUpLeft:LK,LucideCornerUpRight:PK,LucideCpu:DK,LucideCreativeCommons:RK,LucideCreditCard:Vp,LucideCroissant:OK,LucideCrop:FK,LucideCross:BK,LucideCrosshair:zK,LucideCrown:Zh,LucideCuboid:$K,LucideCupSoda:UK,LucideCurlyBraces:HN,LucideCurrency:qK,LucideCylinder:VK,LucideDam:HK,LucideDatabase:mR,LucideDatabaseBackup:GK,LucideDatabaseZap:WK,LucideDelete:KK,LucideDessert:YK,LucideDiameter:ZK,LucideDiamond:JK,LucideDiamondMinus:XK,LucideDiamondPercent:Ok,LucideDiamondPlus:QK,LucideDice1:eY,LucideDice2:tY,LucideDice3:sY,LucideDice4:rY,LucideDice5:nY,LucideDice6:aY,LucideDices:iY,LucideDiff:oY,LucideDisc:uY,LucideDisc2:lY,LucideDisc3:cY,LucideDiscAlbum:dY,LucideDivide:hY,LucideDivideCircle:gk,LucideDivideSquare:ZS,LucideDna:fY,LucideDnaOff:mY,LucideDock:pY,LucideDog:xY,LucideDollarSign:wl,LucideDonut:gY,LucideDoorClosed:yY,LucideDoorOpen:sv,LucideDot:vY,LucideDotSquare:XS,LucideDownload:Ya,LucideDownloadCloud:Ik,LucideDraftingCompass:bY,LucideDrama:_Y,LucideDribbble:wY,LucideDrill:jY,LucideDroplet:NY,LucideDroplets:ky,LucideDrum:kY,LucideDrumstick:SY,LucideDumbbell:CY,LucideEar:EY,LucideEarOff:TY,LucideEarth:Fk,LucideEarthLock:AY,LucideEclipse:MY,LucideEdit:sd,LucideEdit2:R0,LucideEdit3:D0,LucideEgg:mA,LucideEggFried:IY,LucideEggOff:LY,LucideEllipsis:Lp,LucideEllipsisVertical:Yx,LucideEqual:RY,LucideEqualApproximately:PY,LucideEqualNot:DY,LucideEqualSquare:QS,LucideEraser:OY,LucideEthernetPort:FY,LucideEuro:BY,LucideExpand:zY,LucideExternalLink:Qr,LucideEye:bn,LucideEyeClosed:$Y,LucideEyeOff:Xh,LucideFacebook:yu,LucideFactory:UY,LucideFan:qY,LucideFastForward:VY,LucideFeather:HY,LucideFence:GY,LucideFerrisWheel:WY,LucideFigma:KY,LucideFile:fA,LucideFileArchive:YY,LucideFileAudio:XY,LucideFileAudio2:ZY,LucideFileAxis3D:Bk,LucideFileAxis3d:Bk,LucideFileBadge:JY,LucideFileBadge2:QY,LucideFileBarChart:zk,LucideFileBarChart2:$k,LucideFileBox:eZ,LucideFileChartColumn:$k,LucideFileChartColumnIncreasing:zk,LucideFileChartLine:Uk,LucideFileChartPie:qk,LucideFileCheck:fR,LucideFileCheck2:tZ,LucideFileClock:sZ,LucideFileCode:nZ,LucideFileCode2:rZ,LucideFileCog:Vk,LucideFileCog2:Vk,LucideFileDiff:aZ,LucideFileDigit:iZ,LucideFileDown:O4,LucideFileEdit:Gk,LucideFileHeart:oZ,LucideFileImage:hb,LucideFileInput:lZ,LucideFileJson:dZ,LucideFileJson2:cZ,LucideFileKey:hZ,LucideFileKey2:uZ,LucideFileLineChart:Uk,LucideFileLock:fZ,LucideFileLock2:mZ,LucideFileMinus:xZ,LucideFileMinus2:pZ,LucideFileMusic:gZ,LucideFileOutput:yZ,LucideFilePen:Gk,LucideFilePenLine:Hk,LucideFilePieChart:qk,LucideFilePlus:bZ,LucideFilePlus2:vZ,LucideFileQuestion:_Z,LucideFileScan:wZ,LucideFileSearch:NZ,LucideFileSearch2:jZ,LucideFileSignature:Hk,LucideFileSliders:kZ,LucideFileSpreadsheet:mb,LucideFileStack:pR,LucideFileSymlink:SZ,LucideFileTerminal:CZ,LucideFileText:ln,LucideFileType:EZ,LucideFileType2:TZ,LucideFileUp:AZ,LucideFileUser:MZ,LucideFileVideo:xR,LucideFileVideo2:IZ,LucideFileVolume:PZ,LucideFileVolume2:LZ,LucideFileWarning:DZ,LucideFileX:OZ,LucideFileX2:RZ,LucideFiles:FZ,LucideFilm:gh,LucideFilter:Sy,LucideFilterX:BZ,LucideFingerprint:zZ,LucideFireExtinguisher:$Z,LucideFish:VZ,LucideFishOff:UZ,LucideFishSymbol:qZ,LucideFlag:fb,LucideFlagOff:HZ,LucideFlagTriangleLeft:GZ,LucideFlagTriangleRight:WZ,LucideFlame:mc,LucideFlameKindling:KZ,LucideFlashlight:ZZ,LucideFlashlightOff:YZ,LucideFlaskConical:Xw,LucideFlaskConicalOff:XZ,LucideFlaskRound:QZ,LucideFlipHorizontal:gR,LucideFlipHorizontal2:JZ,LucideFlipVertical:tX,LucideFlipVertical2:eX,LucideFlower:sX,LucideFlower2:vy,LucideFocus:rX,LucideFoldHorizontal:nX,LucideFoldVertical:aX,LucideFolder:IX,LucideFolderArchive:iX,LucideFolderCheck:oX,LucideFolderClock:lX,LucideFolderClosed:cX,LucideFolderCode:dX,LucideFolderCog:Wk,LucideFolderCog2:Wk,LucideFolderDot:uX,LucideFolderDown:hX,LucideFolderEdit:Kk,LucideFolderGit:fX,LucideFolderGit2:mX,LucideFolderHeart:pX,LucideFolderInput:xX,LucideFolderKanban:gX,LucideFolderKey:yX,LucideFolderLock:vX,LucideFolderMinus:bX,LucideFolderOpen:Qh,LucideFolderOpenDot:_X,LucideFolderOutput:wX,LucideFolderPen:Kk,LucideFolderPlus:jX,LucideFolderRoot:NX,LucideFolderSearch:SX,LucideFolderSearch2:kX,LucideFolderSymlink:CX,LucideFolderSync:TX,LucideFolderTree:EX,LucideFolderUp:AX,LucideFolderX:MX,LucideFolders:LX,LucideFootprints:PX,LucideForkKnife:OC,LucideForkKnifeCrossed:RC,LucideForklift:DX,LucideFormInput:yS,LucideForward:RX,LucideFrame:OX,LucideFramer:FX,LucideFrown:BX,LucideFuel:zX,LucideFullscreen:$X,LucideFunctionSquare:JS,LucideGalleryHorizontal:qX,LucideGalleryHorizontalEnd:UX,LucideGalleryThumbnails:VX,LucideGalleryVertical:GX,LucideGalleryVerticalEnd:HX,LucideGamepad:KX,LucideGamepad2:WX,LucideGanttChart:sk,LucideGanttChartSquare:j0,LucideGauge:YX,LucideGaugeCircle:yk,LucideGavel:ZX,LucideGem:XX,LucideGhost:F4,LucideGift:ii,LucideGitBranch:JX,LucideGitBranchPlus:QX,LucideGitCommit:Yk,LucideGitCommitHorizontal:Yk,LucideGitCommitVertical:eQ,LucideGitCompare:sQ,LucideGitCompareArrows:tQ,LucideGitFork:rQ,LucideGitGraph:nQ,LucideGitMerge:aQ,LucideGitPullRequest:uQ,LucideGitPullRequestArrow:iQ,LucideGitPullRequestClosed:oQ,LucideGitPullRequestCreate:cQ,LucideGitPullRequestCreateArrow:lQ,LucideGitPullRequestDraft:dQ,LucideGithub:hQ,LucideGitlab:mQ,LucideGlassWater:fQ,LucideGlasses:pQ,LucideGlobe:fc,LucideGlobe2:Fk,LucideGlobeLock:xQ,LucideGoal:gQ,LucideGrab:yQ,LucideGraduationCap:Md,LucideGrape:vQ,LucideGrid:Bx,LucideGrid2X2:Xk,LucideGrid2X2Plus:Zk,LucideGrid2x2:Xk,LucideGrid2x2Check:bQ,LucideGrid2x2Plus:Zk,LucideGrid2x2X:_Q,LucideGrid3X3:Bx,LucideGrid3x3:Bx,LucideGrip:jQ,LucideGripHorizontal:wQ,LucideGripVertical:vu,LucideGroup:NQ,LucideGuitar:kQ,LucideHam:SQ,LucideHammer:yR,LucideHand:vR,LucideHandCoins:CQ,LucideHandHeart:TQ,LucideHandHelping:fy,LucideHandMetal:EQ,LucideHandPlatter:AQ,LucideHandshake:Qw,LucideHardDrive:bR,LucideHardDriveDownload:MQ,LucideHardDriveUpload:IQ,LucideHardHat:LQ,LucideHash:Jw,LucideHaze:PQ,LucideHdmiPort:DQ,LucideHeading:BQ,LucideHeading1:pA,LucideHeading2:xA,LucideHeading3:_R,LucideHeading4:RQ,LucideHeading5:OQ,LucideHeading6:FQ,LucideHeadphoneOff:zQ,LucideHeadphones:$Q,LucideHeadset:UQ,LucideHeart:ci,LucideHeartCrack:qQ,LucideHeartHandshake:VQ,LucideHeartOff:HQ,LucideHeartPulse:GQ,LucideHeater:WQ,LucideHelpCircle:G1,LucideHelpingHand:fy,LucideHexagon:KQ,LucideHighlighter:YQ,LucideHistory:gA,LucideHome:En,LucideHop:XQ,LucideHopOff:ZQ,LucideHospital:QQ,LucideHotel:JQ,LucideHourglass:eJ,LucideHouse:En,LucideHousePlug:tJ,LucideHousePlus:sJ,LucideIceCream:Jk,LucideIceCream2:Qk,LucideIceCreamBowl:Qk,LucideIceCreamCone:Jk,LucideIdCard:rJ,LucideImage:ml,LucideImageDown:nJ,LucideImageMinus:aJ,LucideImageOff:iJ,LucideImagePlay:oJ,LucideImagePlus:rv,LucideImageUp:lJ,LucideImageUpscale:cJ,LucideImages:dJ,LucideImport:uJ,LucideInbox:ej,LucideIndent:tS,LucideIndentDecrease:eS,LucideIndentIncrease:tS,LucideIndianRupee:hJ,LucideInfinity:mJ,LucideInfo:B4,LucideInspect:aC,LucideInspectionPanel:fJ,LucideInstagram:Jd,LucideItalic:tj,LucideIterationCcw:pJ,LucideIterationCw:xJ,LucideJapaneseYen:gJ,LucideJoystick:yJ,LucideKanban:nv,LucideKanbanSquare:eC,LucideKanbanSquareDashed:WS,LucideKey:ep,LucideKeyRound:z4,LucideKeySquare:vJ,LucideKeyboard:wJ,LucideKeyboardMusic:bJ,LucideKeyboardOff:_J,LucideLamp:TJ,LucideLampCeiling:jJ,LucideLampDesk:NJ,LucideLampFloor:kJ,LucideLampWallDown:SJ,LucideLampWallUp:CJ,LucideLandPlot:EJ,LucideLandmark:AJ,LucideLanguages:MJ,LucideLaptop:LJ,LucideLaptop2:sS,LucideLaptopMinimal:sS,LucideLaptopMinimalCheck:IJ,LucideLasso:DJ,LucideLassoSelect:PJ,LucideLaugh:RJ,LucideLayers:wR,LucideLayers2:OJ,LucideLayers3:FJ,LucideLayout:Y1,LucideLayoutDashboard:$4,LucideLayoutGrid:xf,LucideLayoutList:BJ,LucideLayoutPanelLeft:zJ,LucideLayoutPanelTop:$J,LucideLayoutTemplate:U4,LucideLeaf:UJ,LucideLeafyGreen:qJ,LucideLectern:VJ,LucideLetterText:HJ,LucideLibrary:q4,LucideLibraryBig:GJ,LucideLibrarySquare:tC,LucideLifeBuoy:yA,LucideLigature:WJ,LucideLightbulb:sj,LucideLightbulbOff:KJ,LucideLineChart:JN,LucideLink:po,LucideLink2:tl,LucideLink2Off:YJ,LucideLinkedin:Jh,LucideList:em,LucideListCheck:ZJ,LucideListChecks:pb,LucideListCollapse:XJ,LucideListEnd:QJ,LucideListFilter:jR,LucideListMinus:JJ,LucideListMusic:eee,LucideListOrdered:Cy,LucideListPlus:tee,LucideListRestart:see,LucideListStart:ree,LucideListTodo:nee,LucideListTree:aee,LucideListVideo:iee,LucideListX:oee,LucideLoader:cee,LucideLoader2:es,LucideLoaderCircle:es,LucideLoaderPinwheel:lee,LucideLocate:vA,LucideLocateFixed:dee,LucideLocateOff:uee,LucideLock:Hc,LucideLockKeyhole:hee,LucideLockKeyholeOpen:rS,LucideLockOpen:nS,LucideLogIn:V4,LucideLogOut:bA,LucideLogs:mee,LucideLollipop:fee,LucideLuggage:pee,LucideMSquare:sC,LucideMagnet:xee,LucideMail:Vs,LucideMailCheck:gee,LucideMailMinus:yee,LucideMailOpen:NR,LucideMailPlus:kR,LucideMailQuestion:vee,LucideMailSearch:bee,LucideMailWarning:_ee,LucideMailX:_A,LucideMailbox:wee,LucideMails:jee,LucideMap:H4,LucideMapPin:Ca,LucideMapPinCheck:kee,LucideMapPinCheckInside:Nee,LucideMapPinHouse:See,LucideMapPinMinus:Tee,LucideMapPinMinusInside:Cee,LucideMapPinOff:Eee,LucideMapPinPlus:Mee,LucideMapPinPlusInside:Aee,LucideMapPinX:Lee,LucideMapPinXInside:Iee,LucideMapPinned:Pee,LucideMartini:Dee,LucideMaximize:SR,LucideMaximize2:Ree,LucideMedal:xb,LucideMegaphone:bu,LucideMegaphoneOff:Oee,LucideMeh:Fee,LucideMemoryStick:Bee,LucideMenu:G4,LucideMenuSquare:rC,LucideMerge:zee,LucideMessageCircle:Jl,LucideMessageCircleCode:$ee,LucideMessageCircleDashed:Uee,LucideMessageCircleHeart:wA,LucideMessageCircleMore:qee,LucideMessageCircleOff:Vee,LucideMessageCirclePlus:Hee,LucideMessageCircleQuestion:CR,LucideMessageCircleReply:Gee,LucideMessageCircleWarning:Wee,LucideMessageCircleX:Kee,LucideMessageSquare:xi,LucideMessageSquareCode:Yee,LucideMessageSquareDashed:Zee,LucideMessageSquareDiff:Xee,LucideMessageSquareDot:Qee,LucideMessageSquareHeart:Jee,LucideMessageSquareLock:ete,LucideMessageSquareMore:TR,LucideMessageSquareOff:tte,LucideMessageSquarePlus:V0,LucideMessageSquareQuote:ER,LucideMessageSquareReply:ste,LucideMessageSquareShare:rte,LucideMessageSquareText:nte,LucideMessageSquareWarning:ate,LucideMessageSquareX:ite,LucideMessagesSquare:ote,LucideMic:W4,LucideMic2:aS,LucideMicOff:lte,LucideMicVocal:aS,LucideMicrochip:cte,LucideMicroscope:dte,LucideMicrowave:ute,LucideMilestone:hte,LucideMilk:fte,LucideMilkOff:mte,LucideMinimize:xte,LucideMinimize2:pte,LucideMinus:av,LucideMinusCircle:vk,LucideMinusSquare:nC,LucideMonitor:rj,LucideMonitorCheck:gte,LucideMonitorCog:yte,LucideMonitorDot:vte,LucideMonitorDown:bte,LucideMonitorOff:_te,LucideMonitorPause:wte,LucideMonitorPlay:AR,LucideMonitorSmartphone:jte,LucideMonitorSpeaker:Nte,LucideMonitorStop:kte,LucideMonitorUp:K4,LucideMonitorX:Ste,LucideMoon:Tte,LucideMoonStar:Cte,LucideMoreHorizontal:Lp,LucideMoreVertical:Yx,LucideMountain:Ate,LucideMountainSnow:Ete,LucideMouse:Pte,LucideMouseOff:Mte,LucideMousePointer:Bu,LucideMousePointer2:Ite,LucideMousePointerBan:Lte,LucideMousePointerClick:qc,LucideMousePointerSquareDashed:KS,LucideMove:Wte,LucideMove3D:iS,LucideMove3d:iS,LucideMoveDiagonal:Rte,LucideMoveDiagonal2:Dte,LucideMoveDown:Bte,LucideMoveDownLeft:Ote,LucideMoveDownRight:Fte,LucideMoveHorizontal:zte,LucideMoveLeft:$te,LucideMoveRight:Ute,LucideMoveUp:Hte,LucideMoveUpLeft:qte,LucideMoveUpRight:Vte,LucideMoveVertical:Gte,LucideMusic:Xte,LucideMusic2:Kte,LucideMusic3:Yte,LucideMusic4:Zte,LucideNavigation:MR,LucideNavigation2:Jte,LucideNavigation2Off:Qte,LucideNavigationOff:ese,LucideNetwork:tse,LucideNewspaper:iv,LucideNfc:sse,LucideNotebook:ise,LucideNotebookPen:rse,LucideNotebookTabs:nse,LucideNotebookText:ase,LucideNotepadText:lse,LucideNotepadTextDashed:ose,LucideNut:dse,LucideNutOff:cse,LucideOctagon:hse,LucideOctagonAlert:K1,LucideOctagonMinus:use,LucideOctagonPause:oS,LucideOctagonX:lS,LucideOmega:mse,LucideOption:fse,LucideOrbit:pse,LucideOrigami:xse,LucideOutdent:eS,LucidePackage:Il,LucidePackage2:gse,LucidePackageCheck:yse,LucidePackageMinus:vse,LucidePackageOpen:bse,LucidePackagePlus:_se,LucidePackageSearch:wse,LucidePackageX:jse,LucidePaintBucket:Nse,LucidePaintRoller:kse,LucidePaintbrush:Sse,LucidePaintbrush2:cS,LucidePaintbrushVertical:cS,LucidePalette:fl,LucidePalmtree:SC,LucidePanelBottom:Ese,LucidePanelBottomClose:Cse,LucidePanelBottomDashed:dS,LucidePanelBottomInactive:dS,LucidePanelBottomOpen:Tse,LucidePanelLeft:fS,LucidePanelLeftClose:uS,LucidePanelLeftDashed:hS,LucidePanelLeftInactive:hS,LucidePanelLeftOpen:mS,LucidePanelRight:Ise,LucidePanelRightClose:Ase,LucidePanelRightDashed:pS,LucidePanelRightInactive:pS,LucidePanelRightOpen:Mse,LucidePanelTop:Dse,LucidePanelTopClose:Lse,LucidePanelTopDashed:xS,LucidePanelTopInactive:xS,LucidePanelTopOpen:Pse,LucidePanelsLeftBottom:Rse,LucidePanelsLeftRight:Dk,LucidePanelsRightBottom:Ose,LucidePanelsTopBottom:_S,LucidePanelsTopLeft:Y1,LucidePaperclip:nj,LucideParentheses:Fse,LucideParkingCircle:_k,LucideParkingCircleOff:bk,LucideParkingMeter:Bse,LucideParkingSquare:oC,LucideParkingSquareOff:iC,LucidePartyPopper:eu,LucidePause:tm,LucidePauseCircle:wk,LucidePauseOctagon:oS,LucidePawPrint:zse,LucidePcCase:$se,LucidePen:R0,LucidePenBox:sd,LucidePenLine:D0,LucidePenOff:Use,LucidePenSquare:sd,LucidePenTool:aj,LucidePencil:Ea,LucidePencilLine:qse,LucidePencilOff:Vse,LucidePencilRuler:Hse,LucidePentagon:Gse,LucidePercent:Y4,LucidePercentCircle:jk,LucidePercentDiamond:Ok,LucidePercentSquare:lC,LucidePersonStanding:Wse,LucidePhilippinePeso:Kse,LucidePhone:Cn,LucidePhoneCall:Yse,LucidePhoneForwarded:Zse,LucidePhoneIncoming:Xse,LucidePhoneMissed:Qse,LucidePhoneOff:Jse,LucidePhoneOutgoing:ere,LucidePi:tre,LucidePiSquare:cC,LucidePiano:sre,LucidePickaxe:rre,LucidePictureInPicture:are,LucidePictureInPicture2:nre,LucidePieChart:rk,LucidePiggyBank:ire,LucidePilcrow:cre,LucidePilcrowLeft:ore,LucidePilcrowRight:lre,LucidePilcrowSquare:dC,LucidePill:ure,LucidePillBottle:dre,LucidePin:ij,LucidePinOff:IR,LucidePipette:hre,LucidePizza:mre,LucidePlane:LR,LucidePlaneLanding:fre,LucidePlaneTakeoff:pre,LucidePlay:Uo,LucidePlayCircle:rf,LucidePlaySquare:uC,LucidePlug:Z4,LucidePlug2:xre,LucidePlugZap:gS,LucidePlugZap2:gS,LucidePlus:$s,LucidePlusCircle:Nk,LucidePlusSquare:hC,LucidePocket:yre,LucidePocketKnife:gre,LucidePodcast:vre,LucidePointer:_re,LucidePointerOff:bre,LucidePopcorn:wre,LucidePopsicle:jre,LucidePoundSterling:Nre,LucidePower:PR,LucidePowerCircle:kk,LucidePowerOff:kre,LucidePowerSquare:mC,LucidePresentation:Ty,LucidePrinter:DR,LucidePrinterCheck:Sre,LucideProjector:Cre,LucideProportions:Tre,LucidePuzzle:Ere,LucidePyramid:Are,LucideQrCode:ov,LucideQuote:X4,LucideRabbit:Mre,LucideRadar:jA,LucideRadiation:Ire,LucideRadical:Lre,LucideRadio:gb,LucideRadioReceiver:Pre,LucideRadioTower:Dre,LucideRadius:Rre,LucideRailSymbol:Ore,LucideRainbow:Fre,LucideRat:Bre,LucideRatio:zre,LucideReceipt:Yre,LucideReceiptCent:$re,LucideReceiptEuro:Ure,LucideReceiptIndianRupee:qre,LucideReceiptJapaneseYen:Vre,LucideReceiptPoundSterling:Hre,LucideReceiptRussianRuble:Gre,LucideReceiptSwissFranc:Wre,LucideReceiptText:Kre,LucideRectangleEllipsis:yS,LucideRectangleHorizontal:Zre,LucideRectangleVertical:Xre,LucideRecycle:Qre,LucideRedo:oj,LucideRedo2:Jre,LucideRedoDot:ene,LucideRefreshCcw:NA,LucideRefreshCcwDot:tne,LucideRefreshCw:Mi,LucideRefreshCwOff:sne,LucideRefrigerator:rne,LucideRegex:nne,LucideRemoveFormatting:ane,LucideRepeat:RR,LucideRepeat1:ine,LucideRepeat2:one,LucideReplace:cne,LucideReplaceAll:lne,LucideReply:OR,LucideReplyAll:dne,LucideRewind:une,LucideRibbon:hne,LucideRocket:lv,LucideRockingChair:mne,LucideRollerCoaster:fne,LucideRotate3D:vS,LucideRotate3d:vS,LucideRotateCcw:cv,LucideRotateCcwSquare:pne,LucideRotateCw:Q4,LucideRotateCwSquare:xne,LucideRoute:yne,LucideRouteOff:gne,LucideRouter:vne,LucideRows:bS,LucideRows2:bS,LucideRows3:_S,LucideRows4:bne,LucideRss:_ne,LucideRuler:J4,LucideRussianRuble:wne,LucideSailboat:jne,LucideSalad:Nne,LucideSandwich:kne,LucideSatellite:Cne,LucideSatelliteDish:Sne,LucideSave:Bl,LucideSaveAll:Tne,LucideSaveOff:Ene,LucideScale:FR,LucideScale3D:wS,LucideScale3d:wS,LucideScaling:Ane,LucideScan:Fne,LucideScanBarcode:Mne,LucideScanEye:Ine,LucideScanFace:Lne,LucideScanLine:Pne,LucideScanQrCode:Dne,LucideScanSearch:Rne,LucideScanText:One,LucideScatterChart:nk,LucideSchool:Bne,LucideSchool2:TC,LucideScissors:$ne,LucideScissorsLineDashed:zne,LucideScissorsSquare:fC,LucideScissorsSquareDashedBottom:zS,LucideScreenShare:qne,LucideScreenShareOff:Une,LucideScroll:Hne,LucideScrollText:Vne,LucideSearch:yn,LucideSearchCheck:Gne,LucideSearchCode:Wne,LucideSearchSlash:Kne,LucideSearchX:BR,LucideSection:Yne,LucideSend:en,LucideSendHorizonal:jS,LucideSendHorizontal:jS,LucideSendToBack:Zne,LucideSeparatorHorizontal:Xne,LucideSeparatorVertical:Qne,LucideServer:sae,LucideServerCog:Jne,LucideServerCrash:eae,LucideServerOff:tae,LucideSettings:oo,LucideSettings2:zR,LucideShapes:rae,LucideShare:$R,LucideShare2:Ec,LucideSheet:nae,LucideShell:aae,LucideShield:Wu,LucideShieldAlert:UR,LucideShieldBan:iae,LucideShieldCheck:Ey,LucideShieldClose:NS,LucideShieldEllipsis:oae,LucideShieldHalf:lae,LucideShieldMinus:cae,LucideShieldOff:e3,LucideShieldPlus:dae,LucideShieldQuestion:uae,LucideShieldX:NS,LucideShip:mae,LucideShipWheel:hae,LucideShirt:fae,LucideShoppingBag:dv,LucideShoppingBasket:pae,LucideShoppingCart:Hf,LucideShovel:xae,LucideShowerHead:gae,LucideShrink:yae,LucideShrub:vae,LucideShuffle:t3,LucideSidebar:fS,LucideSidebarClose:uS,LucideSidebarOpen:mS,LucideSigma:bae,LucideSigmaSquare:pC,LucideSignal:kae,LucideSignalHigh:_ae,LucideSignalLow:wae,LucideSignalMedium:jae,LucideSignalZero:Nae,LucideSignature:Sae,LucideSignpost:Tae,LucideSignpostBig:Cae,LucideSiren:Eae,LucideSkipBack:Aae,LucideSkipForward:Mae,LucideSkull:Iae,LucideSlack:Lae,LucideSlash:Pae,LucideSlashSquare:xC,LucideSlice:Dae,LucideSliders:kS,LucideSlidersHorizontal:s3,LucideSlidersVertical:kS,LucideSmartphone:ig,LucideSmartphoneCharging:Rae,LucideSmartphoneNfc:Oae,LucideSmile:Bae,LucideSmilePlus:Fae,LucideSnail:zae,LucideSnowflake:H0,LucideSofa:$ae,LucideSortAsc:FN,LucideSortDesc:DN,LucideSoup:Uae,LucideSpace:qae,LucideSpade:Vae,LucideSparkle:Hae,LucideSparkles:jr,LucideSpeaker:Gae,LucideSpeech:Wae,LucideSpellCheck:Yae,LucideSpellCheck2:Kae,LucideSpline:Zae,LucideSplit:Xae,LucideSplitSquareHorizontal:gC,LucideSplitSquareVertical:yC,LucideSprayCan:Qae,LucideSprout:r3,LucideSquare:og,LucideSquareActivity:SS,LucideSquareArrowDown:ES,LucideSquareArrowDownLeft:CS,LucideSquareArrowDownRight:TS,LucideSquareArrowLeft:AS,LucideSquareArrowOutDownLeft:MS,LucideSquareArrowOutDownRight:IS,LucideSquareArrowOutUpLeft:LS,LucideSquareArrowOutUpRight:PS,LucideSquareArrowRight:DS,LucideSquareArrowUp:FS,LucideSquareArrowUpLeft:RS,LucideSquareArrowUpRight:OS,LucideSquareAsterisk:BS,LucideSquareBottomDashedScissors:zS,LucideSquareChartGantt:j0,LucideSquareCheck:$S,LucideSquareCheckBig:Z1,LucideSquareChevronDown:US,LucideSquareChevronLeft:qS,LucideSquareChevronRight:VS,LucideSquareChevronUp:HS,LucideSquareCode:GS,LucideSquareDashed:YS,LucideSquareDashedBottom:eie,LucideSquareDashedBottomCode:Jae,LucideSquareDashedKanban:WS,LucideSquareDashedMousePointer:KS,LucideSquareDivide:ZS,LucideSquareDot:XS,LucideSquareEqual:QS,LucideSquareFunction:JS,LucideSquareGanttChart:j0,LucideSquareKanban:eC,LucideSquareLibrary:tC,LucideSquareM:sC,LucideSquareMenu:rC,LucideSquareMinus:nC,LucideSquareMousePointer:aC,LucideSquareParking:oC,LucideSquareParkingOff:iC,LucideSquarePen:sd,LucideSquarePercent:lC,LucideSquarePi:cC,LucideSquarePilcrow:dC,LucideSquarePlay:uC,LucideSquarePlus:hC,LucideSquarePower:mC,LucideSquareRadical:tie,LucideSquareScissors:fC,LucideSquareSigma:pC,LucideSquareSlash:xC,LucideSquareSplitHorizontal:gC,LucideSquareSplitVertical:yC,LucideSquareSquare:sie,LucideSquareStack:rie,LucideSquareTerminal:vC,LucideSquareUser:_C,LucideSquareUserRound:bC,LucideSquareX:wC,LucideSquircle:nie,LucideSquirrel:aie,LucideStamp:iie,LucideStar:Xn,LucideStarHalf:oie,LucideStarOff:lie,LucideStars:jr,LucideStepBack:cie,LucideStepForward:die,LucideStethoscope:uie,LucideSticker:hie,LucideStickyNote:mie,LucideStopCircle:Ck,LucideStore:fie,LucideStretchHorizontal:pie,LucideStretchVertical:xie,LucideStrikethrough:qR,LucideSubscript:gie,LucideSubtitles:GN,LucideSun:yb,LucideSunDim:yie,LucideSunMedium:vie,LucideSunMoon:bie,LucideSunSnow:_ie,LucideSunrise:wie,LucideSunset:jie,LucideSuperscript:Nie,LucideSwatchBook:kie,LucideSwissFranc:Sie,LucideSwitchCamera:Cie,LucideSword:Tie,LucideSwords:Eie,LucideSyringe:Aie,LucideTable:SA,LucideTable2:kA,LucideTableCellsMerge:Mie,LucideTableCellsSplit:Iie,LucideTableColumnsSplit:Lie,LucideTableOfContents:Pie,LucideTableProperties:Die,LucideTableRowsSplit:Rie,LucideTablet:Fie,LucideTabletSmartphone:Oie,LucideTablets:Bie,LucideTag:wh,LucideTags:zie,LucideTally1:$ie,LucideTally2:Uie,LucideTally3:qie,LucideTally4:Vie,LucideTally5:Hie,LucideTangent:Gie,LucideTarget:Pd,LucideTelescope:Wie,LucideTent:Yie,LucideTentTree:Kie,LucideTerminal:Zie,LucideTerminalSquare:vC,LucideTestTube:Xie,LucideTestTube2:jC,LucideTestTubeDiagonal:jC,LucideTestTubes:Qie,LucideText:roe,LucideTextCursor:eoe,LucideTextCursorInput:Jie,LucideTextQuote:toe,LucideTextSearch:soe,LucideTextSelect:NC,LucideTextSelection:NC,LucideTheater:noe,LucideThermometer:ooe,LucideThermometerSnowflake:aoe,LucideThermometerSun:ioe,LucideThumbsDown:VR,LucideThumbsUp:jh,LucideTicket:HR,LucideTicketCheck:loe,LucideTicketMinus:coe,LucideTicketPercent:doe,LucideTicketPlus:uoe,LucideTicketSlash:hoe,LucideTicketX:moe,LucideTickets:poe,LucideTicketsPlane:foe,LucideTimer:yoe,LucideTimerOff:xoe,LucideTimerReset:goe,LucideToggleLeft:voe,LucideToggleRight:boe,LucideToilet:_oe,LucideTornado:woe,LucideTorus:joe,LucideTouchpad:koe,LucideTouchpadOff:Noe,LucideTowerControl:Soe,LucideToyBrick:Coe,LucideTractor:Toe,LucideTrafficCone:Eoe,LucideTrain:kC,LucideTrainFront:Moe,LucideTrainFrontTunnel:Aoe,LucideTrainTrack:Ioe,LucideTramFront:kC,LucideTrash:Loe,LucideTrash2:yr,LucideTreeDeciduous:Poe,LucideTreePalm:SC,LucideTreePine:lj,LucideTrees:Doe,LucideTrello:Roe,LucideTrendingDown:vb,LucideTrendingUp:bo,LucideTrendingUpDown:Ooe,LucideTriangle:Boe,LucideTriangleAlert:id,LucideTriangleRight:Foe,LucideTrophy:Gi,LucideTruck:GR,LucideTurtle:zoe,LucideTv:Uoe,LucideTv2:CC,LucideTvMinimal:CC,LucideTvMinimalPlay:$oe,LucideTwitch:qoe,LucideTwitter:Voe,LucideType:Goe,LucideTypeOutline:Hoe,LucideUmbrella:Koe,LucideUmbrellaOff:Woe,LucideUnderline:CA,LucideUndo:cj,LucideUndo2:Yoe,LucideUndoDot:Zoe,LucideUnfoldHorizontal:Xoe,LucideUnfoldVertical:Qoe,LucideUngroup:Joe,LucideUniversity:TC,LucideUnlink:n3,LucideUnlink2:ele,LucideUnlock:nS,LucideUnlockKeyhole:rS,LucideUnplug:tle,LucideUpload:da,LucideUploadCloud:Lk,LucideUsb:sle,LucideUser:Di,LucideUser2:PC,LucideUserCheck:uv,LucideUserCheck2:EC,LucideUserCircle:Ek,LucideUserCircle2:Tk,LucideUserCog:WR,LucideUserCog2:AC,LucideUserMinus:KR,LucideUserMinus2:MC,LucideUserPen:rle,LucideUserPlus:sl,LucideUserPlus2:IC,LucideUserRound:PC,LucideUserRoundCheck:EC,LucideUserRoundCog:AC,LucideUserRoundMinus:MC,LucideUserRoundPen:nle,LucideUserRoundPlus:IC,LucideUserRoundSearch:ale,LucideUserRoundX:LC,LucideUserSearch:ile,LucideUserSquare:_C,LucideUserSquare2:bC,LucideUserX:ole,LucideUserX2:LC,LucideUsers:pr,LucideUsers2:DC,LucideUsersRound:DC,LucideUtensils:OC,LucideUtensilsCrossed:RC,LucideUtilityPole:lle,LucideVariable:TA,LucideVault:cle,LucideVegan:dle,LucideVenetianMask:ule,LucideVerified:$N,LucideVibrate:mle,LucideVibrateOff:hle,LucideVideo:Jr,LucideVideoOff:fle,LucideVideotape:ple,LucideView:xle,LucideVoicemail:gle,LucideVolleyball:yle,LucideVolume:_le,LucideVolume1:vle,LucideVolume2:YR,LucideVolumeOff:ble,LucideVolumeX:ZR,LucideVote:wle,LucideWallet:XR,LucideWallet2:FC,LucideWalletCards:jle,LucideWalletMinimal:FC,LucideWallpaper:Nle,LucideWand:kle,LucideWand2:Zx,LucideWandSparkles:Zx,LucideWarehouse:Sle,LucideWashingMachine:Cle,LucideWatch:Tle,LucideWaves:Ele,LucideWaypoints:Ale,LucideWebcam:Mle,LucideWebhook:Lle,LucideWebhookOff:Ile,LucideWeight:Ple,LucideWheat:Rle,LucideWheatOff:Dle,LucideWholeWord:Ole,LucideWifi:Ule,LucideWifiHigh:Fle,LucideWifiLow:Ble,LucideWifiOff:zle,LucideWifiZero:$le,LucideWind:Vle,LucideWindArrowDown:qle,LucideWine:Gle,LucideWineOff:Hle,LucideWorkflow:QR,LucideWorm:Wle,LucideWrapText:Kle,LucideWrench:Ay,LucideX:vr,LucideXCircle:Sc,LucideXOctagon:lS,LucideXSquare:wC,LucideYoutube:Yle,LucideZap:Ku,LucideZapOff:Zle,LucideZoomIn:dj,LucideZoomOut:EA,Luggage:pee,LuggageIcon:pee,MSquare:sC,MSquareIcon:sC,Magnet:xee,MagnetIcon:xee,Mail:Vs,MailCheck:gee,MailCheckIcon:gee,MailIcon:Vs,MailMinus:yee,MailMinusIcon:yee,MailOpen:NR,MailOpenIcon:NR,MailPlus:kR,MailPlusIcon:kR,MailQuestion:vee,MailQuestionIcon:vee,MailSearch:bee,MailSearchIcon:bee,MailWarning:_ee,MailWarningIcon:_ee,MailX:_A,MailXIcon:_A,Mailbox:wee,MailboxIcon:wee,Mails:jee,MailsIcon:jee,Map:H4,MapIcon:H4,MapPin:Ca,MapPinCheck:kee,MapPinCheckIcon:kee,MapPinCheckInside:Nee,MapPinCheckInsideIcon:Nee,MapPinHouse:See,MapPinHouseIcon:See,MapPinIcon:Ca,MapPinMinus:Tee,MapPinMinusIcon:Tee,MapPinMinusInside:Cee,MapPinMinusInsideIcon:Cee,MapPinOff:Eee,MapPinOffIcon:Eee,MapPinPlus:Mee,MapPinPlusIcon:Mee,MapPinPlusInside:Aee,MapPinPlusInsideIcon:Aee,MapPinX:Lee,MapPinXIcon:Lee,MapPinXInside:Iee,MapPinXInsideIcon:Iee,MapPinned:Pee,MapPinnedIcon:Pee,Martini:Dee,MartiniIcon:Dee,Maximize:SR,Maximize2:Ree,Maximize2Icon:Ree,MaximizeIcon:SR,Medal:xb,MedalIcon:xb,Megaphone:bu,MegaphoneIcon:bu,MegaphoneOff:Oee,MegaphoneOffIcon:Oee,Meh:Fee,MehIcon:Fee,MemoryStick:Bee,MemoryStickIcon:Bee,Menu:G4,MenuIcon:G4,MenuSquare:rC,MenuSquareIcon:rC,Merge:zee,MergeIcon:zee,MessageCircle:Jl,MessageCircleCode:$ee,MessageCircleCodeIcon:$ee,MessageCircleDashed:Uee,MessageCircleDashedIcon:Uee,MessageCircleHeart:wA,MessageCircleHeartIcon:wA,MessageCircleIcon:Jl,MessageCircleMore:qee,MessageCircleMoreIcon:qee,MessageCircleOff:Vee,MessageCircleOffIcon:Vee,MessageCirclePlus:Hee,MessageCirclePlusIcon:Hee,MessageCircleQuestion:CR,MessageCircleQuestionIcon:CR,MessageCircleReply:Gee,MessageCircleReplyIcon:Gee,MessageCircleWarning:Wee,MessageCircleWarningIcon:Wee,MessageCircleX:Kee,MessageCircleXIcon:Kee,MessageSquare:xi,MessageSquareCode:Yee,MessageSquareCodeIcon:Yee,MessageSquareDashed:Zee,MessageSquareDashedIcon:Zee,MessageSquareDiff:Xee,MessageSquareDiffIcon:Xee,MessageSquareDot:Qee,MessageSquareDotIcon:Qee,MessageSquareHeart:Jee,MessageSquareHeartIcon:Jee,MessageSquareIcon:xi,MessageSquareLock:ete,MessageSquareLockIcon:ete,MessageSquareMore:TR,MessageSquareMoreIcon:TR,MessageSquareOff:tte,MessageSquareOffIcon:tte,MessageSquarePlus:V0,MessageSquarePlusIcon:V0,MessageSquareQuote:ER,MessageSquareQuoteIcon:ER,MessageSquareReply:ste,MessageSquareReplyIcon:ste,MessageSquareShare:rte,MessageSquareShareIcon:rte,MessageSquareText:nte,MessageSquareTextIcon:nte,MessageSquareWarning:ate,MessageSquareWarningIcon:ate,MessageSquareX:ite,MessageSquareXIcon:ite,MessagesSquare:ote,MessagesSquareIcon:ote,Mic:W4,Mic2:aS,Mic2Icon:aS,MicIcon:W4,MicOff:lte,MicOffIcon:lte,MicVocal:aS,MicVocalIcon:aS,Microchip:cte,MicrochipIcon:cte,Microscope:dte,MicroscopeIcon:dte,Microwave:ute,MicrowaveIcon:ute,Milestone:hte,MilestoneIcon:hte,Milk:fte,MilkIcon:fte,MilkOff:mte,MilkOffIcon:mte,Minimize:xte,Minimize2:pte,Minimize2Icon:pte,MinimizeIcon:xte,Minus:av,MinusCircle:vk,MinusCircleIcon:vk,MinusIcon:av,MinusSquare:nC,MinusSquareIcon:nC,Monitor:rj,MonitorCheck:gte,MonitorCheckIcon:gte,MonitorCog:yte,MonitorCogIcon:yte,MonitorDot:vte,MonitorDotIcon:vte,MonitorDown:bte,MonitorDownIcon:bte,MonitorIcon:rj,MonitorOff:_te,MonitorOffIcon:_te,MonitorPause:wte,MonitorPauseIcon:wte,MonitorPlay:AR,MonitorPlayIcon:AR,MonitorSmartphone:jte,MonitorSmartphoneIcon:jte,MonitorSpeaker:Nte,MonitorSpeakerIcon:Nte,MonitorStop:kte,MonitorStopIcon:kte,MonitorUp:K4,MonitorUpIcon:K4,MonitorX:Ste,MonitorXIcon:Ste,Moon:Tte,MoonIcon:Tte,MoonStar:Cte,MoonStarIcon:Cte,MoreHorizontal:Lp,MoreHorizontalIcon:Lp,MoreVertical:Yx,MoreVerticalIcon:Yx,Mountain:Ate,MountainIcon:Ate,MountainSnow:Ete,MountainSnowIcon:Ete,Mouse:Pte,MouseIcon:Pte,MouseOff:Mte,MouseOffIcon:Mte,MousePointer:Bu,MousePointer2:Ite,MousePointer2Icon:Ite,MousePointerBan:Lte,MousePointerBanIcon:Lte,MousePointerClick:qc,MousePointerClickIcon:qc,MousePointerIcon:Bu,MousePointerSquareDashed:KS,MousePointerSquareDashedIcon:KS,Move:Wte,Move3D:iS,Move3DIcon:iS,Move3d:iS,Move3dIcon:iS,MoveDiagonal:Rte,MoveDiagonal2:Dte,MoveDiagonal2Icon:Dte,MoveDiagonalIcon:Rte,MoveDown:Bte,MoveDownIcon:Bte,MoveDownLeft:Ote,MoveDownLeftIcon:Ote,MoveDownRight:Fte,MoveDownRightIcon:Fte,MoveHorizontal:zte,MoveHorizontalIcon:zte,MoveIcon:Wte,MoveLeft:$te,MoveLeftIcon:$te,MoveRight:Ute,MoveRightIcon:Ute,MoveUp:Hte,MoveUpIcon:Hte,MoveUpLeft:qte,MoveUpLeftIcon:qte,MoveUpRight:Vte,MoveUpRightIcon:Vte,MoveVertical:Gte,MoveVerticalIcon:Gte,Music:Xte,Music2:Kte,Music2Icon:Kte,Music3:Yte,Music3Icon:Yte,Music4:Zte,Music4Icon:Zte,MusicIcon:Xte,Navigation:MR,Navigation2:Jte,Navigation2Icon:Jte,Navigation2Off:Qte,Navigation2OffIcon:Qte,NavigationIcon:MR,NavigationOff:ese,NavigationOffIcon:ese,Network:tse,NetworkIcon:tse,Newspaper:iv,NewspaperIcon:iv,Nfc:sse,NfcIcon:sse,Notebook:ise,NotebookIcon:ise,NotebookPen:rse,NotebookPenIcon:rse,NotebookTabs:nse,NotebookTabsIcon:nse,NotebookText:ase,NotebookTextIcon:ase,NotepadText:lse,NotepadTextDashed:ose,NotepadTextDashedIcon:ose,NotepadTextIcon:lse,Nut:dse,NutIcon:dse,NutOff:cse,NutOffIcon:cse,Octagon:hse,OctagonAlert:K1,OctagonAlertIcon:K1,OctagonIcon:hse,OctagonMinus:use,OctagonMinusIcon:use,OctagonPause:oS,OctagonPauseIcon:oS,OctagonX:lS,OctagonXIcon:lS,Omega:mse,OmegaIcon:mse,Option:fse,OptionIcon:fse,Orbit:pse,OrbitIcon:pse,Origami:xse,OrigamiIcon:xse,Outdent:eS,OutdentIcon:eS,Package:Il,Package2:gse,Package2Icon:gse,PackageCheck:yse,PackageCheckIcon:yse,PackageIcon:Il,PackageMinus:vse,PackageMinusIcon:vse,PackageOpen:bse,PackageOpenIcon:bse,PackagePlus:_se,PackagePlusIcon:_se,PackageSearch:wse,PackageSearchIcon:wse,PackageX:jse,PackageXIcon:jse,PaintBucket:Nse,PaintBucketIcon:Nse,PaintRoller:kse,PaintRollerIcon:kse,Paintbrush:Sse,Paintbrush2:cS,Paintbrush2Icon:cS,PaintbrushIcon:Sse,PaintbrushVertical:cS,PaintbrushVerticalIcon:cS,Palette:fl,PaletteIcon:fl,Palmtree:SC,PalmtreeIcon:SC,PanelBottom:Ese,PanelBottomClose:Cse,PanelBottomCloseIcon:Cse,PanelBottomDashed:dS,PanelBottomDashedIcon:dS,PanelBottomIcon:Ese,PanelBottomInactive:dS,PanelBottomInactiveIcon:dS,PanelBottomOpen:Tse,PanelBottomOpenIcon:Tse,PanelLeft:fS,PanelLeftClose:uS,PanelLeftCloseIcon:uS,PanelLeftDashed:hS,PanelLeftDashedIcon:hS,PanelLeftIcon:fS,PanelLeftInactive:hS,PanelLeftInactiveIcon:hS,PanelLeftOpen:mS,PanelLeftOpenIcon:mS,PanelRight:Ise,PanelRightClose:Ase,PanelRightCloseIcon:Ase,PanelRightDashed:pS,PanelRightDashedIcon:pS,PanelRightIcon:Ise,PanelRightInactive:pS,PanelRightInactiveIcon:pS,PanelRightOpen:Mse,PanelRightOpenIcon:Mse,PanelTop:Dse,PanelTopClose:Lse,PanelTopCloseIcon:Lse,PanelTopDashed:xS,PanelTopDashedIcon:xS,PanelTopIcon:Dse,PanelTopInactive:xS,PanelTopInactiveIcon:xS,PanelTopOpen:Pse,PanelTopOpenIcon:Pse,PanelsLeftBottom:Rse,PanelsLeftBottomIcon:Rse,PanelsLeftRight:Dk,PanelsLeftRightIcon:Dk,PanelsRightBottom:Ose,PanelsRightBottomIcon:Ose,PanelsTopBottom:_S,PanelsTopBottomIcon:_S,PanelsTopLeft:Y1,PanelsTopLeftIcon:Y1,Paperclip:nj,PaperclipIcon:nj,Parentheses:Fse,ParenthesesIcon:Fse,ParkingCircle:_k,ParkingCircleIcon:_k,ParkingCircleOff:bk,ParkingCircleOffIcon:bk,ParkingMeter:Bse,ParkingMeterIcon:Bse,ParkingSquare:oC,ParkingSquareIcon:oC,ParkingSquareOff:iC,ParkingSquareOffIcon:iC,PartyPopper:eu,PartyPopperIcon:eu,Pause:tm,PauseCircle:wk,PauseCircleIcon:wk,PauseIcon:tm,PauseOctagon:oS,PauseOctagonIcon:oS,PawPrint:zse,PawPrintIcon:zse,PcCase:$se,PcCaseIcon:$se,Pen:R0,PenBox:sd,PenBoxIcon:sd,PenIcon:R0,PenLine:D0,PenLineIcon:D0,PenOff:Use,PenOffIcon:Use,PenSquare:sd,PenSquareIcon:sd,PenTool:aj,PenToolIcon:aj,Pencil:Ea,PencilIcon:Ea,PencilLine:qse,PencilLineIcon:qse,PencilOff:Vse,PencilOffIcon:Vse,PencilRuler:Hse,PencilRulerIcon:Hse,Pentagon:Gse,PentagonIcon:Gse,Percent:Y4,PercentCircle:jk,PercentCircleIcon:jk,PercentDiamond:Ok,PercentDiamondIcon:Ok,PercentIcon:Y4,PercentSquare:lC,PercentSquareIcon:lC,PersonStanding:Wse,PersonStandingIcon:Wse,PhilippinePeso:Kse,PhilippinePesoIcon:Kse,Phone:Cn,PhoneCall:Yse,PhoneCallIcon:Yse,PhoneForwarded:Zse,PhoneForwardedIcon:Zse,PhoneIcon:Cn,PhoneIncoming:Xse,PhoneIncomingIcon:Xse,PhoneMissed:Qse,PhoneMissedIcon:Qse,PhoneOff:Jse,PhoneOffIcon:Jse,PhoneOutgoing:ere,PhoneOutgoingIcon:ere,Pi:tre,PiIcon:tre,PiSquare:cC,PiSquareIcon:cC,Piano:sre,PianoIcon:sre,Pickaxe:rre,PickaxeIcon:rre,PictureInPicture:are,PictureInPicture2:nre,PictureInPicture2Icon:nre,PictureInPictureIcon:are,PieChart:rk,PieChartIcon:rk,PiggyBank:ire,PiggyBankIcon:ire,Pilcrow:cre,PilcrowIcon:cre,PilcrowLeft:ore,PilcrowLeftIcon:ore,PilcrowRight:lre,PilcrowRightIcon:lre,PilcrowSquare:dC,PilcrowSquareIcon:dC,Pill:ure,PillBottle:dre,PillBottleIcon:dre,PillIcon:ure,Pin:ij,PinIcon:ij,PinOff:IR,PinOffIcon:IR,Pipette:hre,PipetteIcon:hre,Pizza:mre,PizzaIcon:mre,Plane:LR,PlaneIcon:LR,PlaneLanding:fre,PlaneLandingIcon:fre,PlaneTakeoff:pre,PlaneTakeoffIcon:pre,Play:Uo,PlayCircle:rf,PlayCircleIcon:rf,PlayIcon:Uo,PlaySquare:uC,PlaySquareIcon:uC,Plug:Z4,Plug2:xre,Plug2Icon:xre,PlugIcon:Z4,PlugZap:gS,PlugZap2:gS,PlugZap2Icon:gS,PlugZapIcon:gS,Plus:$s,PlusCircle:Nk,PlusCircleIcon:Nk,PlusIcon:$s,PlusSquare:hC,PlusSquareIcon:hC,Pocket:yre,PocketIcon:yre,PocketKnife:gre,PocketKnifeIcon:gre,Podcast:vre,PodcastIcon:vre,Pointer:_re,PointerIcon:_re,PointerOff:bre,PointerOffIcon:bre,Popcorn:wre,PopcornIcon:wre,Popsicle:jre,PopsicleIcon:jre,PoundSterling:Nre,PoundSterlingIcon:Nre,Power:PR,PowerCircle:kk,PowerCircleIcon:kk,PowerIcon:PR,PowerOff:kre,PowerOffIcon:kre,PowerSquare:mC,PowerSquareIcon:mC,Presentation:Ty,PresentationIcon:Ty,Printer:DR,PrinterCheck:Sre,PrinterCheckIcon:Sre,PrinterIcon:DR,Projector:Cre,ProjectorIcon:Cre,Proportions:Tre,ProportionsIcon:Tre,Puzzle:Ere,PuzzleIcon:Ere,Pyramid:Are,PyramidIcon:Are,QrCode:ov,QrCodeIcon:ov,Quote:X4,QuoteIcon:X4,Rabbit:Mre,RabbitIcon:Mre,Radar:jA,RadarIcon:jA,Radiation:Ire,RadiationIcon:Ire,Radical:Lre,RadicalIcon:Lre,Radio:gb,RadioIcon:gb,RadioReceiver:Pre,RadioReceiverIcon:Pre,RadioTower:Dre,RadioTowerIcon:Dre,Radius:Rre,RadiusIcon:Rre,RailSymbol:Ore,RailSymbolIcon:Ore,Rainbow:Fre,RainbowIcon:Fre,Rat:Bre,RatIcon:Bre,Ratio:zre,RatioIcon:zre,Receipt:Yre,ReceiptCent:$re,ReceiptCentIcon:$re,ReceiptEuro:Ure,ReceiptEuroIcon:Ure,ReceiptIcon:Yre,ReceiptIndianRupee:qre,ReceiptIndianRupeeIcon:qre,ReceiptJapaneseYen:Vre,ReceiptJapaneseYenIcon:Vre,ReceiptPoundSterling:Hre,ReceiptPoundSterlingIcon:Hre,ReceiptRussianRuble:Gre,ReceiptRussianRubleIcon:Gre,ReceiptSwissFranc:Wre,ReceiptSwissFrancIcon:Wre,ReceiptText:Kre,ReceiptTextIcon:Kre,RectangleEllipsis:yS,RectangleEllipsisIcon:yS,RectangleHorizontal:Zre,RectangleHorizontalIcon:Zre,RectangleVertical:Xre,RectangleVerticalIcon:Xre,Recycle:Qre,RecycleIcon:Qre,Redo:oj,Redo2:Jre,Redo2Icon:Jre,RedoDot:ene,RedoDotIcon:ene,RedoIcon:oj,RefreshCcw:NA,RefreshCcwDot:tne,RefreshCcwDotIcon:tne,RefreshCcwIcon:NA,RefreshCw:Mi,RefreshCwIcon:Mi,RefreshCwOff:sne,RefreshCwOffIcon:sne,Refrigerator:rne,RefrigeratorIcon:rne,Regex:nne,RegexIcon:nne,RemoveFormatting:ane,RemoveFormattingIcon:ane,Repeat:RR,Repeat1:ine,Repeat1Icon:ine,Repeat2:one,Repeat2Icon:one,RepeatIcon:RR,Replace:cne,ReplaceAll:lne,ReplaceAllIcon:lne,ReplaceIcon:cne,Reply:OR,ReplyAll:dne,ReplyAllIcon:dne,ReplyIcon:OR,Rewind:une,RewindIcon:une,Ribbon:hne,RibbonIcon:hne,Rocket:lv,RocketIcon:lv,RockingChair:mne,RockingChairIcon:mne,RollerCoaster:fne,RollerCoasterIcon:fne,Rotate3D:vS,Rotate3DIcon:vS,Rotate3d:vS,Rotate3dIcon:vS,RotateCcw:cv,RotateCcwIcon:cv,RotateCcwSquare:pne,RotateCcwSquareIcon:pne,RotateCw:Q4,RotateCwIcon:Q4,RotateCwSquare:xne,RotateCwSquareIcon:xne,Route:yne,RouteIcon:yne,RouteOff:gne,RouteOffIcon:gne,Router:vne,RouterIcon:vne,Rows:bS,Rows2:bS,Rows2Icon:bS,Rows3:_S,Rows3Icon:_S,Rows4:bne,Rows4Icon:bne,RowsIcon:bS,Rss:_ne,RssIcon:_ne,Ruler:J4,RulerIcon:J4,RussianRuble:wne,RussianRubleIcon:wne,Sailboat:jne,SailboatIcon:jne,Salad:Nne,SaladIcon:Nne,Sandwich:kne,SandwichIcon:kne,Satellite:Cne,SatelliteDish:Sne,SatelliteDishIcon:Sne,SatelliteIcon:Cne,Save:Bl,SaveAll:Tne,SaveAllIcon:Tne,SaveIcon:Bl,SaveOff:Ene,SaveOffIcon:Ene,Scale:FR,Scale3D:wS,Scale3DIcon:wS,Scale3d:wS,Scale3dIcon:wS,ScaleIcon:FR,Scaling:Ane,ScalingIcon:Ane,Scan:Fne,ScanBarcode:Mne,ScanBarcodeIcon:Mne,ScanEye:Ine,ScanEyeIcon:Ine,ScanFace:Lne,ScanFaceIcon:Lne,ScanIcon:Fne,ScanLine:Pne,ScanLineIcon:Pne,ScanQrCode:Dne,ScanQrCodeIcon:Dne,ScanSearch:Rne,ScanSearchIcon:Rne,ScanText:One,ScanTextIcon:One,ScatterChart:nk,ScatterChartIcon:nk,School:Bne,School2:TC,School2Icon:TC,SchoolIcon:Bne,Scissors:$ne,ScissorsIcon:$ne,ScissorsLineDashed:zne,ScissorsLineDashedIcon:zne,ScissorsSquare:fC,ScissorsSquareDashedBottom:zS,ScissorsSquareDashedBottomIcon:zS,ScissorsSquareIcon:fC,ScreenShare:qne,ScreenShareIcon:qne,ScreenShareOff:Une,ScreenShareOffIcon:Une,Scroll:Hne,ScrollIcon:Hne,ScrollText:Vne,ScrollTextIcon:Vne,Search:yn,SearchCheck:Gne,SearchCheckIcon:Gne,SearchCode:Wne,SearchCodeIcon:Wne,SearchIcon:yn,SearchSlash:Kne,SearchSlashIcon:Kne,SearchX:BR,SearchXIcon:BR,Section:Yne,SectionIcon:Yne,Send:en,SendHorizonal:jS,SendHorizonalIcon:jS,SendHorizontal:jS,SendHorizontalIcon:jS,SendIcon:en,SendToBack:Zne,SendToBackIcon:Zne,SeparatorHorizontal:Xne,SeparatorHorizontalIcon:Xne,SeparatorVertical:Qne,SeparatorVerticalIcon:Qne,Server:sae,ServerCog:Jne,ServerCogIcon:Jne,ServerCrash:eae,ServerCrashIcon:eae,ServerIcon:sae,ServerOff:tae,ServerOffIcon:tae,Settings:oo,Settings2:zR,Settings2Icon:zR,SettingsIcon:oo,Shapes:rae,ShapesIcon:rae,Share:$R,Share2:Ec,Share2Icon:Ec,ShareIcon:$R,Sheet:nae,SheetIcon:nae,Shell:aae,ShellIcon:aae,Shield:Wu,ShieldAlert:UR,ShieldAlertIcon:UR,ShieldBan:iae,ShieldBanIcon:iae,ShieldCheck:Ey,ShieldCheckIcon:Ey,ShieldClose:NS,ShieldCloseIcon:NS,ShieldEllipsis:oae,ShieldEllipsisIcon:oae,ShieldHalf:lae,ShieldHalfIcon:lae,ShieldIcon:Wu,ShieldMinus:cae,ShieldMinusIcon:cae,ShieldOff:e3,ShieldOffIcon:e3,ShieldPlus:dae,ShieldPlusIcon:dae,ShieldQuestion:uae,ShieldQuestionIcon:uae,ShieldX:NS,ShieldXIcon:NS,Ship:mae,ShipIcon:mae,ShipWheel:hae,ShipWheelIcon:hae,Shirt:fae,ShirtIcon:fae,ShoppingBag:dv,ShoppingBagIcon:dv,ShoppingBasket:pae,ShoppingBasketIcon:pae,ShoppingCart:Hf,ShoppingCartIcon:Hf,Shovel:xae,ShovelIcon:xae,ShowerHead:gae,ShowerHeadIcon:gae,Shrink:yae,ShrinkIcon:yae,Shrub:vae,ShrubIcon:vae,Shuffle:t3,ShuffleIcon:t3,Sidebar:fS,SidebarClose:uS,SidebarCloseIcon:uS,SidebarIcon:fS,SidebarOpen:mS,SidebarOpenIcon:mS,Sigma:bae,SigmaIcon:bae,SigmaSquare:pC,SigmaSquareIcon:pC,Signal:kae,SignalHigh:_ae,SignalHighIcon:_ae,SignalIcon:kae,SignalLow:wae,SignalLowIcon:wae,SignalMedium:jae,SignalMediumIcon:jae,SignalZero:Nae,SignalZeroIcon:Nae,Signature:Sae,SignatureIcon:Sae,Signpost:Tae,SignpostBig:Cae,SignpostBigIcon:Cae,SignpostIcon:Tae,Siren:Eae,SirenIcon:Eae,SkipBack:Aae,SkipBackIcon:Aae,SkipForward:Mae,SkipForwardIcon:Mae,Skull:Iae,SkullIcon:Iae,Slack:Lae,SlackIcon:Lae,Slash:Pae,SlashIcon:Pae,SlashSquare:xC,SlashSquareIcon:xC,Slice:Dae,SliceIcon:Dae,Sliders:kS,SlidersHorizontal:s3,SlidersHorizontalIcon:s3,SlidersIcon:kS,SlidersVertical:kS,SlidersVerticalIcon:kS,Smartphone:ig,SmartphoneCharging:Rae,SmartphoneChargingIcon:Rae,SmartphoneIcon:ig,SmartphoneNfc:Oae,SmartphoneNfcIcon:Oae,Smile:Bae,SmileIcon:Bae,SmilePlus:Fae,SmilePlusIcon:Fae,Snail:zae,SnailIcon:zae,Snowflake:H0,SnowflakeIcon:H0,Sofa:$ae,SofaIcon:$ae,SortAsc:FN,SortAscIcon:FN,SortDesc:DN,SortDescIcon:DN,Soup:Uae,SoupIcon:Uae,Space:qae,SpaceIcon:qae,Spade:Vae,SpadeIcon:Vae,Sparkle:Hae,SparkleIcon:Hae,Sparkles:jr,SparklesIcon:jr,Speaker:Gae,SpeakerIcon:Gae,Speech:Wae,SpeechIcon:Wae,SpellCheck:Yae,SpellCheck2:Kae,SpellCheck2Icon:Kae,SpellCheckIcon:Yae,Spline:Zae,SplineIcon:Zae,Split:Xae,SplitIcon:Xae,SplitSquareHorizontal:gC,SplitSquareHorizontalIcon:gC,SplitSquareVertical:yC,SplitSquareVerticalIcon:yC,SprayCan:Qae,SprayCanIcon:Qae,Sprout:r3,SproutIcon:r3,Square:og,SquareActivity:SS,SquareActivityIcon:SS,SquareArrowDown:ES,SquareArrowDownIcon:ES,SquareArrowDownLeft:CS,SquareArrowDownLeftIcon:CS,SquareArrowDownRight:TS,SquareArrowDownRightIcon:TS,SquareArrowLeft:AS,SquareArrowLeftIcon:AS,SquareArrowOutDownLeft:MS,SquareArrowOutDownLeftIcon:MS,SquareArrowOutDownRight:IS,SquareArrowOutDownRightIcon:IS,SquareArrowOutUpLeft:LS,SquareArrowOutUpLeftIcon:LS,SquareArrowOutUpRight:PS,SquareArrowOutUpRightIcon:PS,SquareArrowRight:DS,SquareArrowRightIcon:DS,SquareArrowUp:FS,SquareArrowUpIcon:FS,SquareArrowUpLeft:RS,SquareArrowUpLeftIcon:RS,SquareArrowUpRight:OS,SquareArrowUpRightIcon:OS,SquareAsterisk:BS,SquareAsteriskIcon:BS,SquareBottomDashedScissors:zS,SquareBottomDashedScissorsIcon:zS,SquareChartGantt:j0,SquareChartGanttIcon:j0,SquareCheck:$S,SquareCheckBig:Z1,SquareCheckBigIcon:Z1,SquareCheckIcon:$S,SquareChevronDown:US,SquareChevronDownIcon:US,SquareChevronLeft:qS,SquareChevronLeftIcon:qS,SquareChevronRight:VS,SquareChevronRightIcon:VS,SquareChevronUp:HS,SquareChevronUpIcon:HS,SquareCode:GS,SquareCodeIcon:GS,SquareDashed:YS,SquareDashedBottom:eie,SquareDashedBottomCode:Jae,SquareDashedBottomCodeIcon:Jae,SquareDashedBottomIcon:eie,SquareDashedIcon:YS,SquareDashedKanban:WS,SquareDashedKanbanIcon:WS,SquareDashedMousePointer:KS,SquareDashedMousePointerIcon:KS,SquareDivide:ZS,SquareDivideIcon:ZS,SquareDot:XS,SquareDotIcon:XS,SquareEqual:QS,SquareEqualIcon:QS,SquareFunction:JS,SquareFunctionIcon:JS,SquareGanttChart:j0,SquareGanttChartIcon:j0,SquareIcon:og,SquareKanban:eC,SquareKanbanIcon:eC,SquareLibrary:tC,SquareLibraryIcon:tC,SquareM:sC,SquareMIcon:sC,SquareMenu:rC,SquareMenuIcon:rC,SquareMinus:nC,SquareMinusIcon:nC,SquareMousePointer:aC,SquareMousePointerIcon:aC,SquareParking:oC,SquareParkingIcon:oC,SquareParkingOff:iC,SquareParkingOffIcon:iC,SquarePen:sd,SquarePenIcon:sd,SquarePercent:lC,SquarePercentIcon:lC,SquarePi:cC,SquarePiIcon:cC,SquarePilcrow:dC,SquarePilcrowIcon:dC,SquarePlay:uC,SquarePlayIcon:uC,SquarePlus:hC,SquarePlusIcon:hC,SquarePower:mC,SquarePowerIcon:mC,SquareRadical:tie,SquareRadicalIcon:tie,SquareScissors:fC,SquareScissorsIcon:fC,SquareSigma:pC,SquareSigmaIcon:pC,SquareSlash:xC,SquareSlashIcon:xC,SquareSplitHorizontal:gC,SquareSplitHorizontalIcon:gC,SquareSplitVertical:yC,SquareSplitVerticalIcon:yC,SquareSquare:sie,SquareSquareIcon:sie,SquareStack:rie,SquareStackIcon:rie,SquareTerminal:vC,SquareTerminalIcon:vC,SquareUser:_C,SquareUserIcon:_C,SquareUserRound:bC,SquareUserRoundIcon:bC,SquareX:wC,SquareXIcon:wC,Squircle:nie,SquircleIcon:nie,Squirrel:aie,SquirrelIcon:aie,Stamp:iie,StampIcon:iie,Star:Xn,StarHalf:oie,StarHalfIcon:oie,StarIcon:Xn,StarOff:lie,StarOffIcon:lie,Stars:jr,StarsIcon:jr,StepBack:cie,StepBackIcon:cie,StepForward:die,StepForwardIcon:die,Stethoscope:uie,StethoscopeIcon:uie,Sticker:hie,StickerIcon:hie,StickyNote:mie,StickyNoteIcon:mie,StopCircle:Ck,StopCircleIcon:Ck,Store:fie,StoreIcon:fie,StretchHorizontal:pie,StretchHorizontalIcon:pie,StretchVertical:xie,StretchVerticalIcon:xie,Strikethrough:qR,StrikethroughIcon:qR,Subscript:gie,SubscriptIcon:gie,Subtitles:GN,SubtitlesIcon:GN,Sun:yb,SunDim:yie,SunDimIcon:yie,SunIcon:yb,SunMedium:vie,SunMediumIcon:vie,SunMoon:bie,SunMoonIcon:bie,SunSnow:_ie,SunSnowIcon:_ie,Sunrise:wie,SunriseIcon:wie,Sunset:jie,SunsetIcon:jie,Superscript:Nie,SuperscriptIcon:Nie,SwatchBook:kie,SwatchBookIcon:kie,SwissFranc:Sie,SwissFrancIcon:Sie,SwitchCamera:Cie,SwitchCameraIcon:Cie,Sword:Tie,SwordIcon:Tie,Swords:Eie,SwordsIcon:Eie,Syringe:Aie,SyringeIcon:Aie,Table:SA,Table2:kA,Table2Icon:kA,TableCellsMerge:Mie,TableCellsMergeIcon:Mie,TableCellsSplit:Iie,TableCellsSplitIcon:Iie,TableColumnsSplit:Lie,TableColumnsSplitIcon:Lie,TableIcon:SA,TableOfContents:Pie,TableOfContentsIcon:Pie,TableProperties:Die,TablePropertiesIcon:Die,TableRowsSplit:Rie,TableRowsSplitIcon:Rie,Tablet:Fie,TabletIcon:Fie,TabletSmartphone:Oie,TabletSmartphoneIcon:Oie,Tablets:Bie,TabletsIcon:Bie,Tag:wh,TagIcon:wh,Tags:zie,TagsIcon:zie,Tally1:$ie,Tally1Icon:$ie,Tally2:Uie,Tally2Icon:Uie,Tally3:qie,Tally3Icon:qie,Tally4:Vie,Tally4Icon:Vie,Tally5:Hie,Tally5Icon:Hie,Tangent:Gie,TangentIcon:Gie,Target:Pd,TargetIcon:Pd,Telescope:Wie,TelescopeIcon:Wie,Tent:Yie,TentIcon:Yie,TentTree:Kie,TentTreeIcon:Kie,Terminal:Zie,TerminalIcon:Zie,TerminalSquare:vC,TerminalSquareIcon:vC,TestTube:Xie,TestTube2:jC,TestTube2Icon:jC,TestTubeDiagonal:jC,TestTubeDiagonalIcon:jC,TestTubeIcon:Xie,TestTubes:Qie,TestTubesIcon:Qie,Text:roe,TextCursor:eoe,TextCursorIcon:eoe,TextCursorInput:Jie,TextCursorInputIcon:Jie,TextIcon:roe,TextQuote:toe,TextQuoteIcon:toe,TextSearch:soe,TextSearchIcon:soe,TextSelect:NC,TextSelectIcon:NC,TextSelection:NC,TextSelectionIcon:NC,Theater:noe,TheaterIcon:noe,Thermometer:ooe,ThermometerIcon:ooe,ThermometerSnowflake:aoe,ThermometerSnowflakeIcon:aoe,ThermometerSun:ioe,ThermometerSunIcon:ioe,ThumbsDown:VR,ThumbsDownIcon:VR,ThumbsUp:jh,ThumbsUpIcon:jh,Ticket:HR,TicketCheck:loe,TicketCheckIcon:loe,TicketIcon:HR,TicketMinus:coe,TicketMinusIcon:coe,TicketPercent:doe,TicketPercentIcon:doe,TicketPlus:uoe,TicketPlusIcon:uoe,TicketSlash:hoe,TicketSlashIcon:hoe,TicketX:moe,TicketXIcon:moe,Tickets:poe,TicketsIcon:poe,TicketsPlane:foe,TicketsPlaneIcon:foe,Timer:yoe,TimerIcon:yoe,TimerOff:xoe,TimerOffIcon:xoe,TimerReset:goe,TimerResetIcon:goe,ToggleLeft:voe,ToggleLeftIcon:voe,ToggleRight:boe,ToggleRightIcon:boe,Toilet:_oe,ToiletIcon:_oe,Tornado:woe,TornadoIcon:woe,Torus:joe,TorusIcon:joe,Touchpad:koe,TouchpadIcon:koe,TouchpadOff:Noe,TouchpadOffIcon:Noe,TowerControl:Soe,TowerControlIcon:Soe,ToyBrick:Coe,ToyBrickIcon:Coe,Tractor:Toe,TractorIcon:Toe,TrafficCone:Eoe,TrafficConeIcon:Eoe,Train:kC,TrainFront:Moe,TrainFrontIcon:Moe,TrainFrontTunnel:Aoe,TrainFrontTunnelIcon:Aoe,TrainIcon:kC,TrainTrack:Ioe,TrainTrackIcon:Ioe,TramFront:kC,TramFrontIcon:kC,Trash:Loe,Trash2:yr,Trash2Icon:yr,TrashIcon:Loe,TreeDeciduous:Poe,TreeDeciduousIcon:Poe,TreePalm:SC,TreePalmIcon:SC,TreePine:lj,TreePineIcon:lj,Trees:Doe,TreesIcon:Doe,Trello:Roe,TrelloIcon:Roe,TrendingDown:vb,TrendingDownIcon:vb,TrendingUp:bo,TrendingUpDown:Ooe,TrendingUpDownIcon:Ooe,TrendingUpIcon:bo,Triangle:Boe,TriangleAlert:id,TriangleAlertIcon:id,TriangleIcon:Boe,TriangleRight:Foe,TriangleRightIcon:Foe,Trophy:Gi,TrophyIcon:Gi,Truck:GR,TruckIcon:GR,Turtle:zoe,TurtleIcon:zoe,Tv:Uoe,Tv2:CC,Tv2Icon:CC,TvIcon:Uoe,TvMinimal:CC,TvMinimalIcon:CC,TvMinimalPlay:$oe,TvMinimalPlayIcon:$oe,Twitch:qoe,TwitchIcon:qoe,Twitter:Voe,TwitterIcon:Voe,Type:Goe,TypeIcon:Goe,TypeOutline:Hoe,TypeOutlineIcon:Hoe,Umbrella:Koe,UmbrellaIcon:Koe,UmbrellaOff:Woe,UmbrellaOffIcon:Woe,Underline:CA,UnderlineIcon:CA,Undo:cj,Undo2:Yoe,Undo2Icon:Yoe,UndoDot:Zoe,UndoDotIcon:Zoe,UndoIcon:cj,UnfoldHorizontal:Xoe,UnfoldHorizontalIcon:Xoe,UnfoldVertical:Qoe,UnfoldVerticalIcon:Qoe,Ungroup:Joe,UngroupIcon:Joe,University:TC,UniversityIcon:TC,Unlink:n3,Unlink2:ele,Unlink2Icon:ele,UnlinkIcon:n3,Unlock:nS,UnlockIcon:nS,UnlockKeyhole:rS,UnlockKeyholeIcon:rS,Unplug:tle,UnplugIcon:tle,Upload:da,UploadCloud:Lk,UploadCloudIcon:Lk,UploadIcon:da,Usb:sle,UsbIcon:sle,User:Di,User2:PC,User2Icon:PC,UserCheck:uv,UserCheck2:EC,UserCheck2Icon:EC,UserCheckIcon:uv,UserCircle:Ek,UserCircle2:Tk,UserCircle2Icon:Tk,UserCircleIcon:Ek,UserCog:WR,UserCog2:AC,UserCog2Icon:AC,UserCogIcon:WR,UserIcon:Di,UserMinus:KR,UserMinus2:MC,UserMinus2Icon:MC,UserMinusIcon:KR,UserPen:rle,UserPenIcon:rle,UserPlus:sl,UserPlus2:IC,UserPlus2Icon:IC,UserPlusIcon:sl,UserRound:PC,UserRoundCheck:EC,UserRoundCheckIcon:EC,UserRoundCog:AC,UserRoundCogIcon:AC,UserRoundIcon:PC,UserRoundMinus:MC,UserRoundMinusIcon:MC,UserRoundPen:nle,UserRoundPenIcon:nle,UserRoundPlus:IC,UserRoundPlusIcon:IC,UserRoundSearch:ale,UserRoundSearchIcon:ale,UserRoundX:LC,UserRoundXIcon:LC,UserSearch:ile,UserSearchIcon:ile,UserSquare:_C,UserSquare2:bC,UserSquare2Icon:bC,UserSquareIcon:_C,UserX:ole,UserX2:LC,UserX2Icon:LC,UserXIcon:ole,Users:pr,Users2:DC,Users2Icon:DC,UsersIcon:pr,UsersRound:DC,UsersRoundIcon:DC,Utensils:OC,UtensilsCrossed:RC,UtensilsCrossedIcon:RC,UtensilsIcon:OC,UtilityPole:lle,UtilityPoleIcon:lle,Variable:TA,VariableIcon:TA,Vault:cle,VaultIcon:cle,Vegan:dle,VeganIcon:dle,VenetianMask:ule,VenetianMaskIcon:ule,Verified:$N,VerifiedIcon:$N,Vibrate:mle,VibrateIcon:mle,VibrateOff:hle,VibrateOffIcon:hle,Video:Jr,VideoIcon:Jr,VideoOff:fle,VideoOffIcon:fle,Videotape:ple,VideotapeIcon:ple,View:xle,ViewIcon:xle,Voicemail:gle,VoicemailIcon:gle,Volleyball:yle,VolleyballIcon:yle,Volume:_le,Volume1:vle,Volume1Icon:vle,Volume2:YR,Volume2Icon:YR,VolumeIcon:_le,VolumeOff:ble,VolumeOffIcon:ble,VolumeX:ZR,VolumeXIcon:ZR,Vote:wle,VoteIcon:wle,Wallet:XR,Wallet2:FC,Wallet2Icon:FC,WalletCards:jle,WalletCardsIcon:jle,WalletIcon:XR,WalletMinimal:FC,WalletMinimalIcon:FC,Wallpaper:Nle,WallpaperIcon:Nle,Wand:kle,Wand2:Zx,Wand2Icon:Zx,WandIcon:kle,WandSparkles:Zx,WandSparklesIcon:Zx,Warehouse:Sle,WarehouseIcon:Sle,WashingMachine:Cle,WashingMachineIcon:Cle,Watch:Tle,WatchIcon:Tle,Waves:Ele,WavesIcon:Ele,Waypoints:Ale,WaypointsIcon:Ale,Webcam:Mle,WebcamIcon:Mle,Webhook:Lle,WebhookIcon:Lle,WebhookOff:Ile,WebhookOffIcon:Ile,Weight:Ple,WeightIcon:Ple,Wheat:Rle,WheatIcon:Rle,WheatOff:Dle,WheatOffIcon:Dle,WholeWord:Ole,WholeWordIcon:Ole,Wifi:Ule,WifiHigh:Fle,WifiHighIcon:Fle,WifiIcon:Ule,WifiLow:Ble,WifiLowIcon:Ble,WifiOff:zle,WifiOffIcon:zle,WifiZero:$le,WifiZeroIcon:$le,Wind:Vle,WindArrowDown:qle,WindArrowDownIcon:qle,WindIcon:Vle,Wine:Gle,WineIcon:Gle,WineOff:Hle,WineOffIcon:Hle,Workflow:QR,WorkflowIcon:QR,Worm:Wle,WormIcon:Wle,WrapText:Kle,WrapTextIcon:Kle,Wrench:Ay,WrenchIcon:Ay,X:vr,XCircle:Sc,XCircleIcon:Sc,XIcon:vr,XOctagon:lS,XOctagonIcon:lS,XSquare:wC,XSquareIcon:wC,Youtube:Yle,YoutubeIcon:Yle,Zap:Ku,ZapIcon:Ku,ZapOff:Zle,ZapOffIcon:Zle,ZoomIn:dj,ZoomInIcon:dj,ZoomOut:EA,ZoomOutIcon:EA,createLucideIcon:J,icons:Yjt},Symbol.toStringTag,{value:"Module"})),oCe="-",Zjt=s=>{const t=Qjt(s),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=s;return{getClassGroupId:l=>{const o=l.split(oCe);return o[0]===""&&o.length!==1&&o.shift(),xYe(o,t)||Xjt(l)},getConflictingClassGroupIds:(l,o)=>{const c=r[l]||[];return o&&n[l]?[...c,...n[l]]:c}}},xYe=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const r=s[0],n=t.nextPart.get(r),a=n?xYe(s.slice(1),n):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(oCe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},rDe=/^\[(.+)\]$/,Xjt=s=>{if(rDe.test(s)){const t=rDe.exec(s)[1],r=t==null?void 0:t.substring(0,t.indexOf(":"));if(r)return"arbitrary.."+r}},Qjt=s=>{const{theme:t,prefix:r}=s,n={nextPart:new Map,validators:[]};return e2t(Object.entries(s.classGroups),r).forEach(([i,l])=>{owe(l,n,i,t)}),n},owe=(s,t,r,n)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:nDe(t,a);i.classGroupId=r;return}if(typeof a=="function"){if(Jjt(a)){owe(a(n),t,r,n);return}t.validators.push({validator:a,classGroupId:r});return}Object.entries(a).forEach(([i,l])=>{owe(l,nDe(t,i),r,n)})})},nDe=(s,t)=>{let r=s;return t.split(oCe).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},Jjt=s=>s.isThemeGetter,e2t=(s,t)=>t?s.map(([r,n])=>{const a=n.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[t+l,o])):i);return[r,a]}):s,t2t=s=>{if(s<1)return{get:()=>{},set:()=>{}};let t=0,r=new Map,n=new Map;const a=(i,l)=>{r.set(i,l),t++,t>s&&(t=0,n=r,r=new Map)};return{get(i){let l=r.get(i);if(l!==void 0)return l;if((l=n.get(i))!==void 0)return a(i,l),l},set(i,l){r.has(i)?r.set(i,l):a(i,l)}}},gYe="!",s2t=s=>{const{separator:t,experimentalParseClassName:r}=s,n=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,h=0,m;for(let b=0;bh?m-h:void 0;return{modifiers:c,hasImportantModifier:y,baseClassName:v,maybePostfixModifierPosition:w}};return r?o=>r({className:o,parseClassName:l}):l},r2t=s=>{if(s.length<=1)return s;const t=[];let r=[];return s.forEach(n=>{n[0]==="["?(t.push(...r.sort(),n),r=[]):r.push(n)}),t.push(...r.sort()),t},n2t=s=>({cache:t2t(s.cacheSize),parseClassName:s2t(s),...Zjt(s)}),a2t=/\s+/,i2t=(s,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(a2t);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:h,hasImportantModifier:m,baseClassName:x,maybePostfixModifierPosition:y}=r(d);let v=!!y,w=n(v?x.substring(0,y):x);if(!w){if(!v){o=d+(o.length>0?" "+o:o);continue}if(w=n(x),!w){o=d+(o.length>0?" "+o:o);continue}v=!1}const b=r2t(h).join(":"),N=m?b+gYe:b,S=N+w;if(i.includes(S))continue;i.push(S);const T=a(w,v);for(let A=0;A0?" "+o:o)}return o};function o2t(){let s=0,t,r,n="";for(;s{if(typeof s=="string")return s;let t,r="";for(let n=0;nm(h),s());return r=n2t(d),n=r.cache.get,a=r.cache.set,i=o,o(c)}function o(c){const d=n(c);if(d)return d;const h=i2t(c,r);return a(c,h),h}return function(){return i(o2t.apply(null,arguments))}}const bc=s=>{const t=r=>r[s]||[];return t.isThemeGetter=!0,t},vYe=/^\[(?:([a-z-]+):)?(.+)\]$/i,c2t=/^\d+\/\d+$/,d2t=new Set(["px","full","screen"]),u2t=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,h2t=/\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$/,m2t=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,f2t=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,p2t=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,S1=s=>AA(s)||d2t.has(s)||c2t.test(s),L_=s=>MI(s,"length",j2t),AA=s=>!!s&&!Number.isNaN(Number(s)),q0e=s=>MI(s,"number",AA),q6=s=>!!s&&Number.isInteger(Number(s)),x2t=s=>s.endsWith("%")&&AA(s.slice(0,-1)),Vi=s=>vYe.test(s),P_=s=>u2t.test(s),g2t=new Set(["length","size","percentage"]),y2t=s=>MI(s,g2t,bYe),v2t=s=>MI(s,"position",bYe),b2t=new Set(["image","url"]),_2t=s=>MI(s,b2t,k2t),w2t=s=>MI(s,"",N2t),V6=()=>!0,MI=(s,t,r)=>{const n=vYe.exec(s);return n?n[1]?typeof t=="string"?n[1]===t:t.has(n[1]):r(n[2]):!1},j2t=s=>h2t.test(s)&&!m2t.test(s),bYe=()=>!1,N2t=s=>f2t.test(s),k2t=s=>p2t.test(s),S2t=()=>{const s=bc("colors"),t=bc("spacing"),r=bc("blur"),n=bc("brightness"),a=bc("borderColor"),i=bc("borderRadius"),l=bc("borderSpacing"),o=bc("borderWidth"),c=bc("contrast"),d=bc("grayscale"),h=bc("hueRotate"),m=bc("invert"),x=bc("gap"),y=bc("gradientColorStops"),v=bc("gradientColorStopPositions"),w=bc("inset"),b=bc("margin"),N=bc("opacity"),S=bc("padding"),T=bc("saturate"),A=bc("scale"),I=bc("sepia"),D=bc("skew"),R=bc("space"),$=bc("translate"),F=()=>["auto","contain","none"],z=()=>["auto","hidden","clip","visible","scroll"],Q=()=>["auto",Vi,t],K=()=>[Vi,t],X=()=>["",S1,L_],Z=()=>["auto",AA,Vi],re=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],le=()=>["solid","dashed","dotted","double","none"],oe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ne=()=>["start","end","center","between","around","evenly","stretch"],ie=()=>["","0",Vi],ye=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ce=()=>[AA,Vi];return{cacheSize:500,separator:":",theme:{colors:[V6],spacing:[S1,L_],blur:["none","",P_,Vi],brightness:ce(),borderColor:[s],borderRadius:["none","","full",P_,Vi],borderSpacing:K(),borderWidth:X(),contrast:ce(),grayscale:ie(),hueRotate:ce(),invert:ie(),gap:K(),gradientColorStops:[s],gradientColorStopPositions:[x2t,L_],inset:Q(),margin:Q(),opacity:ce(),padding:K(),saturate:ce(),scale:ce(),sepia:ie(),skew:ce(),space:K(),translate:K()},classGroups:{aspect:[{aspect:["auto","square","video",Vi]}],container:["container"],columns:[{columns:[P_]}],"break-after":[{"break-after":ye()}],"break-before":[{"break-before":ye()}],"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:[...re(),Vi]}],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:[w]}],"inset-x":[{"inset-x":[w]}],"inset-y":[{"inset-y":[w]}],start:[{start:[w]}],end:[{end:[w]}],top:[{top:[w]}],right:[{right:[w]}],bottom:[{bottom:[w]}],left:[{left:[w]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",q6,Vi]}],basis:[{basis:Q()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Vi]}],grow:[{grow:ie()}],shrink:[{shrink:ie()}],order:[{order:["first","last","none",q6,Vi]}],"grid-cols":[{"grid-cols":[V6]}],"col-start-end":[{col:["auto",{span:["full",q6,Vi]},Vi]}],"col-start":[{"col-start":Z()}],"col-end":[{"col-end":Z()}],"grid-rows":[{"grid-rows":[V6]}],"row-start-end":[{row:["auto",{span:[q6,Vi]},Vi]}],"row-start":[{"row-start":Z()}],"row-end":[{"row-end":Z()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Vi]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Vi]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...ne()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ne(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ne(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[S]}],px:[{px:[S]}],py:[{py:[S]}],ps:[{ps:[S]}],pe:[{pe:[S]}],pt:[{pt:[S]}],pr:[{pr:[S]}],pb:[{pb:[S]}],pl:[{pl:[S]}],m:[{m:[b]}],mx:[{mx:[b]}],my:[{my:[b]}],ms:[{ms:[b]}],me:[{me:[b]}],mt:[{mt:[b]}],mr:[{mr:[b]}],mb:[{mb:[b]}],ml:[{ml:[b]}],"space-x":[{"space-x":[R]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[R]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Vi,t]}],"min-w":[{"min-w":[Vi,t,"min","max","fit"]}],"max-w":[{"max-w":[Vi,t,"none","full","min","max","fit","prose",{screen:[P_]},P_]}],h:[{h:[Vi,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Vi,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Vi,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Vi,t,"auto","min","max","fit"]}],"font-size":[{text:["base",P_,L_]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",q0e]}],"font-family":[{font:[V6]}],"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",Vi]}],"line-clamp":[{"line-clamp":["none",AA,q0e]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",S1,Vi]}],"list-image":[{"list-image":["none",Vi]}],"list-style-type":[{list:["none","disc","decimal",Vi]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[N]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[N]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...le(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",S1,L_]}],"underline-offset":[{"underline-offset":["auto",S1,Vi]}],"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:K()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Vi]}],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",Vi]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[N]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...re(),v2t]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",y2t]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},_2t]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[v]}],"gradient-via-pos":[{via:[v]}],"gradient-to-pos":[{to:[v]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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":[N]}],"border-style":[{border:[...le(),"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":[N]}],"divide-style":[{divide:le()}],"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:["",...le()]}],"outline-offset":[{"outline-offset":[S1,Vi]}],"outline-w":[{outline:[S1,L_]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:X()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[N]}],"ring-offset-w":[{"ring-offset":[S1,L_]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",P_,w2t]}],"shadow-color":[{shadow:[V6]}],opacity:[{opacity:[N]}],"mix-blend":[{"mix-blend":[...oe(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":oe()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",P_,Vi]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[T]}],sepia:[{sepia:[I]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[N]}],"backdrop-saturate":[{"backdrop-saturate":[T]}],"backdrop-sepia":[{"backdrop-sepia":[I]}],"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",Vi]}],duration:[{duration:ce()}],ease:[{ease:["linear","in","out","in-out",Vi]}],delay:[{delay:ce()}],animate:[{animate:["none","spin","ping","pulse","bounce",Vi]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[q6,Vi]}],"translate-x":[{"translate-x":[$]}],"translate-y":[{"translate-y":[$]}],"skew-x":[{"skew-x":[D]}],"skew-y":[{"skew-y":[D]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Vi]}],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",Vi]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":K()}],"scroll-mx":[{"scroll-mx":K()}],"scroll-my":[{"scroll-my":K()}],"scroll-ms":[{"scroll-ms":K()}],"scroll-me":[{"scroll-me":K()}],"scroll-mt":[{"scroll-mt":K()}],"scroll-mr":[{"scroll-mr":K()}],"scroll-mb":[{"scroll-mb":K()}],"scroll-ml":[{"scroll-ml":K()}],"scroll-p":[{"scroll-p":K()}],"scroll-px":[{"scroll-px":K()}],"scroll-py":[{"scroll-py":K()}],"scroll-ps":[{"scroll-ps":K()}],"scroll-pe":[{"scroll-pe":K()}],"scroll-pt":[{"scroll-pt":K()}],"scroll-pr":[{"scroll-pr":K()}],"scroll-pb":[{"scroll-pb":K()}],"scroll-pl":[{"scroll-pl":K()}],"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",Vi]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[S1,L_,q0e]}],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"]}}},C2t=l2t(S2t);function It(...s){return C2t(Fi(s))}function lc(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 aDe(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function r8(s){return s?s.replace(/<[^>]*>/g,""):""}const T2t=Gjt,_Ye=k.forwardRef(({className:s,...t},r)=>e.jsx(oYe,{ref:r,className:It("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}));_Ye.displayName=oYe.displayName;const E2t=r5("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"}}),wYe=k.forwardRef(({className:s,variant:t,...r},n)=>e.jsx(lYe,{ref:n,className:It(E2t({variant:t}),s),...r}));wYe.displayName=lYe.displayName;const A2t=k.forwardRef(({className:s,...t},r)=>e.jsx(uYe,{ref:r,className:It("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}));A2t.displayName=uYe.displayName;const jYe=k.forwardRef(({className:s,...t},r)=>e.jsx(hYe,{ref:r,className:It("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(vr,{className:"h-4 w-4"})}));jYe.displayName=hYe.displayName;const NYe=k.forwardRef(({className:s,...t},r)=>e.jsx(cYe,{ref:r,className:It("text-sm font-semibold",s),...t}));NYe.displayName=cYe.displayName;const kYe=k.forwardRef(({className:s,...t},r)=>e.jsx(dYe,{ref:r,className:It("text-sm opacity-90",s),...t}));kYe.displayName=dYe.displayName;function M2t(){const{toasts:s}=Ma();return e.jsxs(T2t,{children:[s.map(function({id:t,title:r,description:n,action:a,...i}){return e.jsxs(wYe,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[r&&e.jsx(NYe,{children:r}),n&&e.jsx(kYe,{children:n})]}),a,e.jsx(jYe,{})]},t)}),e.jsx(_Ye,{})]})}var iDe=["light","dark"],I2t="(prefers-color-scheme: dark)",L2t=k.createContext(void 0),P2t={setTheme:s=>{},themes:[]},D2t=()=>{var s;return(s=k.useContext(L2t))!=null?s:P2t};k.memo(({forcedTheme:s,storageKey:t,attribute:r,enableSystem:n,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",h=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(v=>`'${v}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,m=a?iDe.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",x=(v,w=!1,b=!0)=>{let N=l?l[v]:v,S=w?v+"|| ''":`'${N}'`,T="";return a&&b&&!w&&iDe.includes(v)&&(T+=`d.style.colorScheme = '${v}';`),r==="class"?w||N?T+=`c.add(${S})`:T+="null":N&&(T+=`d[s](n,${S})`),T},y=s?`!function(){${h}${x(s)}}()`:n?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${I2t}',m=window.matchMedia(t);if(m.media!==t||m.matches){${x("dark")}}else{${x("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${x(l?"x[e]":"e",!0)}}${d?"":"else{"+x(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${x(l?"x[e]":"e",!0)}}else{${x(i,!1,!1)};}${m}}catch(t){}}();`;return k.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:y}})});var R2t=s=>{switch(s){case"success":return B2t;case"info":return $2t;case"warning":return z2t;case"error":return U2t;default:return null}},O2t=Array(12).fill(0),F2t=({visible:s,className:t})=>wt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},wt.createElement("div",{className:"sonner-spinner"},O2t.map((r,n)=>wt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),B2t=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},wt.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"})),z2t=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},wt.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"})),$2t=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},wt.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"})),U2t=wt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},wt.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"})),q2t=wt.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"},wt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),wt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),V2t=()=>{let[s,t]=wt.useState(document.hidden);return wt.useEffect(()=>{let r=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),s},lwe=1,H2t=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let r=this.subscribers.indexOf(t);this.subscribers.splice(r,1)}),this.publish=t=>{this.subscribers.forEach(r=>r(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var r;let{message:n,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((r=t.id)==null?void 0:r.length)>0?t.id:lwe++,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:n}),{...c,...t,id:i,dismissible:o,title:n}):c):this.addToast({title:n,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(r=>{this.subscribers.forEach(n=>n({id:r.id,dismiss:!0}))}),this.subscribers.forEach(r=>r({id:t,dismiss:!0})),t),this.message=(t,r)=>this.create({...r,message:t}),this.error=(t,r)=>this.create({...r,message:t,type:"error"}),this.success=(t,r)=>this.create({...r,type:"success",message:t}),this.info=(t,r)=>this.create({...r,type:"info",message:t}),this.warning=(t,r)=>this.create({...r,type:"warning",message:t}),this.loading=(t,r)=>this.create({...r,type:"loading",message:t}),this.promise=(t,r)=>{if(!r)return;let n;r.loading!==void 0&&(n=this.create({...r,promise:t,type:"loading",message:r.loading,description:typeof r.description!="function"?r.description:void 0}));let a=t instanceof Promise?t:t(),i=n!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],wt.isValidElement(d))i=!1,this.create({id:n,type:"default",message:d});else if(W2t(d)&&!d.ok){i=!1;let h=typeof r.error=="function"?await r.error(`HTTP error! status: ${d.status}`):r.error,m=typeof r.description=="function"?await r.description(`HTTP error! status: ${d.status}`):r.description;this.create({id:n,type:"error",message:h,description:m})}else if(r.success!==void 0){i=!1;let h=typeof r.success=="function"?await r.success(d):r.success,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"success",message:h,description:m})}}).catch(async d=>{if(l=["reject",d],r.error!==void 0){i=!1;let h=typeof r.error=="function"?await r.error(d):r.error,m=typeof r.description=="function"?await r.description(d):r.description;this.create({id:n,type:"error",message:h,description:m})}}).finally(()=>{var d;i&&(this.dismiss(n),n=void 0),(d=r.finally)==null||d.call(r)}),c=()=>new Promise((d,h)=>o.then(()=>l[0]==="reject"?h(l[1]):d(l[1])).catch(h));return typeof n!="string"&&typeof n!="number"?{unwrap:c}:Object.assign(n,{unwrap:c})},this.custom=(t,r)=>{let n=(r==null?void 0:r.id)||lwe++;return this.create({jsx:t(n),id:n,...r}),n},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Ff=new H2t,G2t=(s,t)=>{let r=(t==null?void 0:t.id)||lwe++;return Ff.addToast({title:s,...t,id:r}),r},W2t=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",K2t=G2t,Y2t=()=>Ff.toasts,Z2t=()=>Ff.getActiveToasts(),ue=Object.assign(K2t,{success:Ff.success,info:Ff.info,warning:Ff.warning,error:Ff.error,custom:Ff.custom,message:Ff.message,promise:Ff.promise,dismiss:Ff.dismiss,loading:Ff.loading},{getHistory:Y2t,getToasts:Z2t});function X2t(s,{insertAt:t}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=s:n.appendChild(document.createTextNode(s))}X2t(`: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 M9(s){return s.label!==void 0}var Q2t=3,J2t="32px",eNt="16px",oDe=4e3,tNt=356,sNt=14,rNt=20,nNt=200;function Xg(...s){return s.filter(Boolean).join(" ")}function aNt(s){let[t,r]=s.split("-"),n=[];return t&&n.push(t),r&&n.push(r),n}var iNt=s=>{var t,r,n,a,i,l,o,c,d,h,m;let{invert:x,toast:y,unstyled:v,interacting:w,setHeights:b,visibleToasts:N,heights:S,index:T,toasts:A,expanded:I,removeToast:D,defaultRichColors:R,closeButton:$,style:F,cancelButtonStyle:z,actionButtonStyle:Q,className:K="",descriptionClassName:X="",duration:Z,position:re,gap:le,loadingIcon:oe,expandByDefault:ne,classNames:ie,icons:ye,closeButtonAriaLabel:ce="Close toast",pauseWhenPageIsHidden:ve}=s,[be,Ue]=wt.useState(null),[Be,De]=wt.useState(null),[Ae,He]=wt.useState(!1),[Le,Ie]=wt.useState(!1),[Te,xe]=wt.useState(!1),[et,fe]=wt.useState(!1),[it,Oe]=wt.useState(!1),[Ye,We]=wt.useState(0),[_e,Re]=wt.useState(0),tt=wt.useRef(y.duration||Z||oDe),Ke=wt.useRef(null),Ze=wt.useRef(null),lt=T===0,xt=T+1<=N,Xe=y.type,Je=y.dismissible!==!1,jt=y.className||"",ns=y.descriptionClassName||"",Ns=wt.useMemo(()=>S.findIndex(Cr=>Cr.toastId===y.id)||0,[S,y.id]),Ys=wt.useMemo(()=>{var Cr;return(Cr=y.closeButton)!=null?Cr:$},[y.closeButton,$]),rs=wt.useMemo(()=>y.duration||Z||oDe,[y.duration,Z]),bt=wt.useRef(0),cs=wt.useRef(0),yt=wt.useRef(0),is=wt.useRef(null),[Bs,ps]=re.split("-"),lr=wt.useMemo(()=>S.reduce((Cr,Xr,Ln)=>Ln>=Ns?Cr:Cr+Xr.height,0),[S,Ns]),kr=V2t(),Lr=y.invert||x,qr=Xe==="loading";cs.current=wt.useMemo(()=>Ns*le+lr,[Ns,lr]),wt.useEffect(()=>{tt.current=rs},[rs]),wt.useEffect(()=>{He(!0)},[]),wt.useEffect(()=>{let Cr=Ze.current;if(Cr){let Xr=Cr.getBoundingClientRect().height;return Re(Xr),b(Ln=>[{toastId:y.id,height:Xr,position:y.position},...Ln]),()=>b(Ln=>Ln.filter(Zs=>Zs.toastId!==y.id))}},[b,y.id]),wt.useLayoutEffect(()=>{if(!Ae)return;let Cr=Ze.current,Xr=Cr.style.height;Cr.style.height="auto";let Ln=Cr.getBoundingClientRect().height;Cr.style.height=Xr,Re(Ln),b(Zs=>Zs.find(Yr=>Yr.toastId===y.id)?Zs.map(Yr=>Yr.toastId===y.id?{...Yr,height:Ln}:Yr):[{toastId:y.id,height:Ln,position:y.position},...Zs])},[Ae,y.title,y.description,b,y.id]);let Ur=wt.useCallback(()=>{Ie(!0),We(cs.current),b(Cr=>Cr.filter(Xr=>Xr.toastId!==y.id)),setTimeout(()=>{D(y)},nNt)},[y,D,b,cs]);wt.useEffect(()=>{if(y.promise&&Xe==="loading"||y.duration===1/0||y.type==="loading")return;let Cr;return I||w||ve&&kr?(()=>{if(yt.current{var Xr;(Xr=y.onAutoClose)==null||Xr.call(y,y),Ur()},tt.current)),()=>clearTimeout(Cr)},[I,w,y,Xe,ve,kr,Ur]),wt.useEffect(()=>{y.delete&&Ur()},[Ur,y.delete]);function Mr(){var Cr,Xr,Ln;return ye!=null&&ye.loading?wt.createElement("div",{className:Xg(ie==null?void 0:ie.loader,(Cr=y==null?void 0:y.classNames)==null?void 0:Cr.loader,"sonner-loader"),"data-visible":Xe==="loading"},ye.loading):oe?wt.createElement("div",{className:Xg(ie==null?void 0:ie.loader,(Xr=y==null?void 0:y.classNames)==null?void 0:Xr.loader,"sonner-loader"),"data-visible":Xe==="loading"},oe):wt.createElement(F2t,{className:Xg(ie==null?void 0:ie.loader,(Ln=y==null?void 0:y.classNames)==null?void 0:Ln.loader),visible:Xe==="loading"})}return wt.createElement("li",{tabIndex:0,ref:Ze,className:Xg(K,jt,ie==null?void 0:ie.toast,(t=y==null?void 0:y.classNames)==null?void 0:t.toast,ie==null?void 0:ie.default,ie==null?void 0:ie[Xe],(r=y==null?void 0:y.classNames)==null?void 0:r[Xe]),"data-sonner-toast":"","data-rich-colors":(n=y.richColors)!=null?n:R,"data-styled":!(y.jsx||y.unstyled||v),"data-mounted":Ae,"data-promise":!!y.promise,"data-swiped":it,"data-removed":Le,"data-visible":xt,"data-y-position":Bs,"data-x-position":ps,"data-index":T,"data-front":lt,"data-swiping":Te,"data-dismissible":Je,"data-type":Xe,"data-invert":Lr,"data-swipe-out":et,"data-swipe-direction":Be,"data-expanded":!!(I||ne&&Ae),style:{"--index":T,"--toasts-before":T,"--z-index":A.length-T,"--offset":`${Le?Ye:cs.current}px`,"--initial-height":ne?"auto":`${_e}px`,...F,...y.style},onDragEnd:()=>{xe(!1),Ue(null),is.current=null},onPointerDown:Cr=>{qr||!Je||(Ke.current=new Date,We(cs.current),Cr.target.setPointerCapture(Cr.pointerId),Cr.target.tagName!=="BUTTON"&&(xe(!0),is.current={x:Cr.clientX,y:Cr.clientY}))},onPointerUp:()=>{var Cr,Xr,Ln,Zs;if(et||!Je)return;is.current=null;let Yr=Number(((Cr=Ze.current)==null?void 0:Cr.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ss=Number(((Xr=Ze.current)==null?void 0:Xr.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ta=new Date().getTime()-((Ln=Ke.current)==null?void 0:Ln.getTime()),nn=be==="x"?Yr:ss,hr=Math.abs(nn)/ta;if(Math.abs(nn)>=rNt||hr>.11){We(cs.current),(Zs=y.onDismiss)==null||Zs.call(y,y),De(be==="x"?Yr>0?"right":"left":ss>0?"down":"up"),Ur(),fe(!0),Oe(!1);return}xe(!1),Ue(null)},onPointerMove:Cr=>{var Xr,Ln,Zs,Yr;if(!is.current||!Je||((Xr=window.getSelection())==null?void 0:Xr.toString().length)>0)return;let ss=Cr.clientY-is.current.y,ta=Cr.clientX-is.current.x,nn=(Ln=s.swipeDirections)!=null?Ln:aNt(re);!be&&(Math.abs(ta)>1||Math.abs(ss)>1)&&Ue(Math.abs(ta)>Math.abs(ss)?"x":"y");let hr={x:0,y:0};be==="y"?(nn.includes("top")||nn.includes("bottom"))&&(nn.includes("top")&&ss<0||nn.includes("bottom")&&ss>0)&&(hr.y=ss):be==="x"&&(nn.includes("left")||nn.includes("right"))&&(nn.includes("left")&&ta<0||nn.includes("right")&&ta>0)&&(hr.x=ta),(Math.abs(hr.x)>0||Math.abs(hr.y)>0)&&Oe(!0),(Zs=Ze.current)==null||Zs.style.setProperty("--swipe-amount-x",`${hr.x}px`),(Yr=Ze.current)==null||Yr.style.setProperty("--swipe-amount-y",`${hr.y}px`)}},Ys&&!y.jsx?wt.createElement("button",{"aria-label":ce,"data-disabled":qr,"data-close-button":!0,onClick:qr||!Je?()=>{}:()=>{var Cr;Ur(),(Cr=y.onDismiss)==null||Cr.call(y,y)},className:Xg(ie==null?void 0:ie.closeButton,(a=y==null?void 0:y.classNames)==null?void 0:a.closeButton)},(i=ye==null?void 0:ye.close)!=null?i:q2t):null,y.jsx||k.isValidElement(y.title)?y.jsx?y.jsx:typeof y.title=="function"?y.title():y.title:wt.createElement(wt.Fragment,null,Xe||y.icon||y.promise?wt.createElement("div",{"data-icon":"",className:Xg(ie==null?void 0:ie.icon,(l=y==null?void 0:y.classNames)==null?void 0:l.icon)},y.promise||y.type==="loading"&&!y.icon?y.icon||Mr():null,y.type!=="loading"?y.icon||(ye==null?void 0:ye[Xe])||R2t(Xe):null):null,wt.createElement("div",{"data-content":"",className:Xg(ie==null?void 0:ie.content,(o=y==null?void 0:y.classNames)==null?void 0:o.content)},wt.createElement("div",{"data-title":"",className:Xg(ie==null?void 0:ie.title,(c=y==null?void 0:y.classNames)==null?void 0:c.title)},typeof y.title=="function"?y.title():y.title),y.description?wt.createElement("div",{"data-description":"",className:Xg(X,ns,ie==null?void 0:ie.description,(d=y==null?void 0:y.classNames)==null?void 0:d.description)},typeof y.description=="function"?y.description():y.description):null),k.isValidElement(y.cancel)?y.cancel:y.cancel&&M9(y.cancel)?wt.createElement("button",{"data-button":!0,"data-cancel":!0,style:y.cancelButtonStyle||z,onClick:Cr=>{var Xr,Ln;M9(y.cancel)&&Je&&((Ln=(Xr=y.cancel).onClick)==null||Ln.call(Xr,Cr),Ur())},className:Xg(ie==null?void 0:ie.cancelButton,(h=y==null?void 0:y.classNames)==null?void 0:h.cancelButton)},y.cancel.label):null,k.isValidElement(y.action)?y.action:y.action&&M9(y.action)?wt.createElement("button",{"data-button":!0,"data-action":!0,style:y.actionButtonStyle||Q,onClick:Cr=>{var Xr,Ln;M9(y.action)&&((Ln=(Xr=y.action).onClick)==null||Ln.call(Xr,Cr),!Cr.defaultPrevented&&Ur())},className:Xg(ie==null?void 0:ie.actionButton,(m=y==null?void 0:y.classNames)==null?void 0:m.actionButton)},y.action.label):null))};function lDe(){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 oNt(s,t){let r={};return[s,t].forEach((n,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?eNt:J2t;function c(d){["top","right","bottom","left"].forEach(h=>{r[`${l}-${h}`]=typeof d=="number"?`${d}px`:d})}typeof n=="number"||typeof n=="string"?c(n):typeof n=="object"?["top","right","bottom","left"].forEach(d=>{n[d]===void 0?r[`${l}-${d}`]=o:r[`${l}-${d}`]=typeof n[d]=="number"?`${n[d]}px`:n[d]}):c(o)}),r}var lNt=k.forwardRef(function(s,t){let{invert:r,position:n="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:h="light",richColors:m,duration:x,style:y,visibleToasts:v=Q2t,toastOptions:w,dir:b=lDe(),gap:N=sNt,loadingIcon:S,icons:T,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:I}=s,[D,R]=wt.useState([]),$=wt.useMemo(()=>Array.from(new Set([n].concat(D.filter(ve=>ve.position).map(ve=>ve.position)))),[D,n]),[F,z]=wt.useState([]),[Q,K]=wt.useState(!1),[X,Z]=wt.useState(!1),[re,le]=wt.useState(h!=="system"?h:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=wt.useRef(null),ne=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ie=wt.useRef(null),ye=wt.useRef(!1),ce=wt.useCallback(ve=>{R(be=>{var Ue;return(Ue=be.find(Be=>Be.id===ve.id))!=null&&Ue.delete||Ff.dismiss(ve.id),be.filter(({id:Be})=>Be!==ve.id)})},[]);return wt.useEffect(()=>Ff.subscribe(ve=>{if(ve.dismiss){R(be=>be.map(Ue=>Ue.id===ve.id?{...Ue,delete:!0}:Ue));return}setTimeout(()=>{tCe.flushSync(()=>{R(be=>{let Ue=be.findIndex(Be=>Be.id===ve.id);return Ue!==-1?[...be.slice(0,Ue),{...be[Ue],...ve},...be.slice(Ue+1)]:[ve,...be]})})})}),[]),wt.useEffect(()=>{if(h!=="system"){le(h);return}if(h==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?le("dark"):le("light")),typeof window>"u")return;let ve=window.matchMedia("(prefers-color-scheme: dark)");try{ve.addEventListener("change",({matches:be})=>{le(be?"dark":"light")})}catch{ve.addListener(({matches:Ue})=>{try{le(Ue?"dark":"light")}catch(Be){console.error(Be)}})}},[h]),wt.useEffect(()=>{D.length<=1&&K(!1)},[D]),wt.useEffect(()=>{let ve=be=>{var Ue,Be;a.every(De=>be[De]||be.code===De)&&(K(!0),(Ue=oe.current)==null||Ue.focus()),be.code==="Escape"&&(document.activeElement===oe.current||(Be=oe.current)!=null&&Be.contains(document.activeElement))&&K(!1)};return document.addEventListener("keydown",ve),()=>document.removeEventListener("keydown",ve)},[a]),wt.useEffect(()=>{if(oe.current)return()=>{ie.current&&(ie.current.focus({preventScroll:!0}),ie.current=null,ye.current=!1)}},[oe.current]),wt.createElement("section",{ref:t,"aria-label":`${A} ${ne}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},$.map((ve,be)=>{var Ue;let[Be,De]=ve.split("-");return D.length?wt.createElement("ol",{key:ve,dir:b==="auto"?lDe():b,tabIndex:-1,ref:oe,className:o,"data-sonner-toaster":!0,"data-theme":re,"data-y-position":Be,"data-lifted":Q&&D.length>1&&!i,"data-x-position":De,style:{"--front-toast-height":`${((Ue=F[0])==null?void 0:Ue.height)||0}px`,"--width":`${tNt}px`,"--gap":`${N}px`,...y,...oNt(c,d)},onBlur:Ae=>{ye.current&&!Ae.currentTarget.contains(Ae.relatedTarget)&&(ye.current=!1,ie.current&&(ie.current.focus({preventScroll:!0}),ie.current=null))},onFocus:Ae=>{Ae.target instanceof HTMLElement&&Ae.target.dataset.dismissible==="false"||ye.current||(ye.current=!0,ie.current=Ae.relatedTarget)},onMouseEnter:()=>K(!0),onMouseMove:()=>K(!0),onMouseLeave:()=>{X||K(!1)},onDragEnd:()=>K(!1),onPointerDown:Ae=>{Ae.target instanceof HTMLElement&&Ae.target.dataset.dismissible==="false"||Z(!0)},onPointerUp:()=>Z(!1)},D.filter(Ae=>!Ae.position&&be===0||Ae.position===ve).map((Ae,He)=>{var Le,Ie;return wt.createElement(iNt,{key:Ae.id,icons:T,index:He,toast:Ae,defaultRichColors:m,duration:(Le=w==null?void 0:w.duration)!=null?Le:x,className:w==null?void 0:w.className,descriptionClassName:w==null?void 0:w.descriptionClassName,invert:r,visibleToasts:v,closeButton:(Ie=w==null?void 0:w.closeButton)!=null?Ie:l,interacting:X,position:ve,style:w==null?void 0:w.style,unstyled:w==null?void 0:w.unstyled,classNames:w==null?void 0:w.classNames,cancelButtonStyle:w==null?void 0:w.cancelButtonStyle,actionButtonStyle:w==null?void 0:w.actionButtonStyle,removeToast:ce,toasts:D.filter(Te=>Te.position==Ae.position),heights:F.filter(Te=>Te.position==Ae.position),setHeights:z,expandByDefault:i,gap:N,loadingIcon:S,expanded:Q,pauseWhenPageIsHidden:I,swipeDirections:s.swipeDirections})})):null}))});const cNt=({...s})=>{const{theme:t="system"}=D2t();return e.jsx(lNt,{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 dNt=dSe[" useId ".trim().toString()]||(()=>{}),uNt=0;function Yu(s){const[t,r]=k.useState(dNt());return Dd(()=>{r(n=>n??String(uNt++))},[s]),t?`radix-${t}`:""}const hNt=["top","right","bottom","left"],Sj=Math.min,Pp=Math.max,ode=Math.round,I9=Math.floor,Cj=s=>({x:s,y:s}),mNt={left:"right",right:"left",bottom:"top",top:"bottom"},fNt={start:"end",end:"start"};function cwe(s,t,r){return Pp(s,Sj(t,r))}function Ab(s,t){return typeof s=="function"?s(t):s}function Mb(s){return s.split("-")[0]}function II(s){return s.split("-")[1]}function lCe(s){return s==="x"?"y":"x"}function cCe(s){return s==="y"?"height":"width"}function Tj(s){return["top","bottom"].includes(Mb(s))?"y":"x"}function dCe(s){return lCe(Tj(s))}function pNt(s,t,r){r===void 0&&(r=!1);const n=II(s),a=dCe(s),i=cCe(a);let l=a==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=lde(l)),[l,lde(l)]}function xNt(s){const t=lde(s);return[dwe(s),t,dwe(t)]}function dwe(s){return s.replace(/start|end/g,t=>fNt[t])}function gNt(s,t,r){const n=["left","right"],a=["right","left"],i=["top","bottom"],l=["bottom","top"];switch(s){case"top":case"bottom":return r?t?a:n:t?n:a;case"left":case"right":return t?i:l;default:return[]}}function yNt(s,t,r,n){const a=II(s);let i=gNt(Mb(s),r==="start",n);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(dwe)))),i}function lde(s){return s.replace(/left|right|bottom|top/g,t=>mNt[t])}function vNt(s){return{top:0,right:0,bottom:0,left:0,...s}}function SYe(s){return typeof s!="number"?vNt(s):{top:s,right:s,bottom:s,left:s}}function cde(s){const{x:t,y:r,width:n,height:a}=s;return{width:n,height:a,top:r,left:t,right:t+n,bottom:r+a,x:t,y:r}}function cDe(s,t,r){let{reference:n,floating:a}=s;const i=Tj(t),l=dCe(t),o=cCe(l),c=Mb(t),d=i==="y",h=n.x+n.width/2-a.width/2,m=n.y+n.height/2-a.height/2,x=n[o]/2-a[o]/2;let y;switch(c){case"top":y={x:h,y:n.y-a.height};break;case"bottom":y={x:h,y:n.y+n.height};break;case"right":y={x:n.x+n.width,y:m};break;case"left":y={x:n.x-a.width,y:m};break;default:y={x:n.x,y:n.y}}switch(II(t)){case"start":y[l]-=x*(r&&d?-1:1);break;case"end":y[l]+=x*(r&&d?-1:1);break}return y}const bNt=async(s,t,r)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:l}=r,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:h,y:m}=cDe(d,n,c),x=n,y={},v=0;for(let w=0;w({name:"arrow",options:s,async fn(t){const{x:r,y:n,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:h=0}=Ab(s,t)||{};if(d==null)return{};const m=SYe(h),x={x:r,y:n},y=dCe(a),v=cCe(y),w=await l.getDimensions(d),b=y==="y",N=b?"top":"left",S=b?"bottom":"right",T=b?"clientHeight":"clientWidth",A=i.reference[v]+i.reference[y]-x[y]-i.floating[v],I=x[y]-i.reference[y],D=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let R=D?D[T]:0;(!R||!await(l.isElement==null?void 0:l.isElement(D)))&&(R=o.floating[T]||i.floating[v]);const $=A/2-I/2,F=R/2-w[v]/2-1,z=Sj(m[N],F),Q=Sj(m[S],F),K=z,X=R-w[v]-Q,Z=R/2-w[v]/2+$,re=cwe(K,Z,X),le=!c.arrow&&II(a)!=null&&Z!==re&&i.reference[v]/2-(ZZ<=0)){var Q,K;const Z=(((Q=i.flip)==null?void 0:Q.index)||0)+1,re=R[Z];if(re)return{data:{index:Z,overflows:z},reset:{placement:re}};let le=(K=z.filter(oe=>oe.overflows[0]<=0).sort((oe,ne)=>oe.overflows[1]-ne.overflows[1])[0])==null?void 0:K.placement;if(!le)switch(y){case"bestFit":{var X;const oe=(X=z.filter(ne=>{if(D){const ie=Tj(ne.placement);return ie===S||ie==="y"}return!0}).map(ne=>[ne.placement,ne.overflows.filter(ie=>ie>0).reduce((ie,ye)=>ie+ye,0)]).sort((ne,ie)=>ne[1]-ie[1])[0])==null?void 0:X[0];oe&&(le=oe);break}case"initialPlacement":le=o;break}if(a!==le)return{reset:{placement:le}}}return{}}}};function dDe(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function uDe(s){return hNt.some(t=>s[t]>=0)}const jNt=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:r}=t,{strategy:n="referenceHidden",...a}=Ab(s,t);switch(n){case"referenceHidden":{const i=await n8(t,{...a,elementContext:"reference"}),l=dDe(i,r.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:uDe(l)}}}case"escaped":{const i=await n8(t,{...a,altBoundary:!0}),l=dDe(i,r.floating);return{data:{escapedOffsets:l,escaped:uDe(l)}}}default:return{}}}}};async function NNt(s,t){const{placement:r,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),l=Mb(r),o=II(r),c=Tj(r)==="y",d=["left","top"].includes(l)?-1:1,h=i&&c?-1:1,m=Ab(t,s);let{mainAxis:x,crossAxis:y,alignmentAxis:v}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:m.mainAxis||0,crossAxis:m.crossAxis||0,alignmentAxis:m.alignmentAxis};return o&&typeof v=="number"&&(y=o==="end"?v*-1:v),c?{x:y*h,y:x*d}:{x:x*d,y:y*h}}const kNt=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(t){var r,n;const{x:a,y:i,placement:l,middlewareData:o}=t,c=await NNt(t,s);return l===((r=o.offset)==null?void 0:r.placement)&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:l}}}}},SNt=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:r,y:n,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:b=>{let{x:N,y:S}=b;return{x:N,y:S}}},...c}=Ab(s,t),d={x:r,y:n},h=await n8(t,c),m=Tj(Mb(a)),x=lCe(m);let y=d[x],v=d[m];if(i){const b=x==="y"?"top":"left",N=x==="y"?"bottom":"right",S=y+h[b],T=y-h[N];y=cwe(S,y,T)}if(l){const b=m==="y"?"top":"left",N=m==="y"?"bottom":"right",S=v+h[b],T=v-h[N];v=cwe(S,v,T)}const w=o.fn({...t,[x]:y,[m]:v});return{...w,data:{x:w.x-r,y:w.y-n,enabled:{[x]:i,[m]:l}}}}}},CNt=function(s){return s===void 0&&(s={}),{options:s,fn(t){const{x:r,y:n,placement:a,rects:i,middlewareData:l}=t,{offset:o=0,mainAxis:c=!0,crossAxis:d=!0}=Ab(s,t),h={x:r,y:n},m=Tj(a),x=lCe(m);let y=h[x],v=h[m];const w=Ab(o,t),b=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:0,crossAxis:0,...w};if(c){const T=x==="y"?"height":"width",A=i.reference[x]-i.floating[T]+b.mainAxis,I=i.reference[x]+i.reference[T]-b.mainAxis;yI&&(y=I)}if(d){var N,S;const T=x==="y"?"width":"height",A=["top","left"].includes(Mb(a)),I=i.reference[m]-i.floating[T]+(A&&((N=l.offset)==null?void 0:N[m])||0)+(A?0:b.crossAxis),D=i.reference[m]+i.reference[T]+(A?0:((S=l.offset)==null?void 0:S[m])||0)-(A?b.crossAxis:0);vD&&(v=D)}return{[x]:y,[m]:v}}}},TNt=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){var r,n;const{placement:a,rects:i,platform:l,elements:o}=t,{apply:c=()=>{},...d}=Ab(s,t),h=await n8(t,d),m=Mb(a),x=II(a),y=Tj(a)==="y",{width:v,height:w}=i.floating;let b,N;m==="top"||m==="bottom"?(b=m,N=x===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(N=m,b=x==="end"?"top":"bottom");const S=w-h.top-h.bottom,T=v-h.left-h.right,A=Sj(w-h[b],S),I=Sj(v-h[N],T),D=!t.middlewareData.shift;let R=A,$=I;if((r=t.middlewareData.shift)!=null&&r.enabled.x&&($=T),(n=t.middlewareData.shift)!=null&&n.enabled.y&&(R=S),D&&!x){const z=Pp(h.left,0),Q=Pp(h.right,0),K=Pp(h.top,0),X=Pp(h.bottom,0);y?$=v-2*(z!==0||Q!==0?z+Q:Pp(h.left,h.right)):R=w-2*(K!==0||X!==0?K+X:Pp(h.top,h.bottom))}await c({...t,availableWidth:$,availableHeight:R});const F=await l.getDimensions(o.floating);return v!==F.width||w!==F.height?{reset:{rects:!0}}:{}}}};function Dme(){return typeof window<"u"}function LI(s){return CYe(s)?(s.nodeName||"").toLowerCase():"#document"}function Hp(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function Lv(s){var t;return(t=(CYe(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function CYe(s){return Dme()?s instanceof Node||s instanceof Hp(s).Node:!1}function Dy(s){return Dme()?s instanceof Element||s instanceof Hp(s).Element:!1}function bv(s){return Dme()?s instanceof HTMLElement||s instanceof Hp(s).HTMLElement:!1}function hDe(s){return!Dme()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof Hp(s).ShadowRoot}function $F(s){const{overflow:t,overflowX:r,overflowY:n,display:a}=Ry(s);return/auto|scroll|overlay|hidden|clip/.test(t+n+r)&&!["inline","contents"].includes(a)}function ENt(s){return["table","td","th"].includes(LI(s))}function Rme(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function uCe(s){const t=hCe(),r=Dy(s)?Ry(s):s;return r.transform!=="none"||r.perspective!=="none"||(r.containerType?r.containerType!=="normal":!1)||!t&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!t&&(r.filter?r.filter!=="none":!1)||["transform","perspective","filter"].some(n=>(r.willChange||"").includes(n))||["paint","layout","strict","content"].some(n=>(r.contain||"").includes(n))}function ANt(s){let t=Ej(s);for(;bv(t)&&!bM(t);){if(uCe(t))return t;if(Rme(t))return null;t=Ej(t)}return null}function hCe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function bM(s){return["html","body","#document"].includes(LI(s))}function Ry(s){return Hp(s).getComputedStyle(s)}function Ome(s){return Dy(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function Ej(s){if(LI(s)==="html")return s;const t=s.assignedSlot||s.parentNode||hDe(s)&&s.host||Lv(s);return hDe(t)?t.host:t}function TYe(s){const t=Ej(s);return bM(t)?s.ownerDocument?s.ownerDocument.body:s.body:bv(t)&&$F(t)?t:TYe(t)}function a8(s,t,r){var n;t===void 0&&(t=[]),r===void 0&&(r=!0);const a=TYe(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),l=Hp(a);if(i){const o=uwe(l);return t.concat(l,l.visualViewport||[],$F(a)?a:[],o&&r?a8(o):[])}return t.concat(a,a8(a,[],r))}function uwe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function EYe(s){const t=Ry(s);let r=parseFloat(t.width)||0,n=parseFloat(t.height)||0;const a=bv(s),i=a?s.offsetWidth:r,l=a?s.offsetHeight:n,o=ode(r)!==i||ode(n)!==l;return o&&(r=i,n=l),{width:r,height:n,$:o}}function mCe(s){return Dy(s)?s:s.contextElement}function MA(s){const t=mCe(s);if(!bv(t))return Cj(1);const r=t.getBoundingClientRect(),{width:n,height:a,$:i}=EYe(t);let l=(i?ode(r.width):r.width)/n,o=(i?ode(r.height):r.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const MNt=Cj(0);function AYe(s){const t=Hp(s);return!hCe()||!t.visualViewport?MNt:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function INt(s,t,r){return t===void 0&&(t=!1),!r||t&&r!==Hp(s)?!1:t}function k3(s,t,r,n){t===void 0&&(t=!1),r===void 0&&(r=!1);const a=s.getBoundingClientRect(),i=mCe(s);let l=Cj(1);t&&(n?Dy(n)&&(l=MA(n)):l=MA(s));const o=INt(i,r,n)?AYe(i):Cj(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,h=a.width/l.x,m=a.height/l.y;if(i){const x=Hp(i),y=n&&Dy(n)?Hp(n):n;let v=x,w=uwe(v);for(;w&&n&&y!==v;){const b=MA(w),N=w.getBoundingClientRect(),S=Ry(w),T=N.left+(w.clientLeft+parseFloat(S.paddingLeft))*b.x,A=N.top+(w.clientTop+parseFloat(S.paddingTop))*b.y;c*=b.x,d*=b.y,h*=b.x,m*=b.y,c+=T,d+=A,v=Hp(w),w=uwe(v)}}return cde({width:h,height:m,x:c,y:d})}function LNt(s){let{elements:t,rect:r,offsetParent:n,strategy:a}=s;const i=a==="fixed",l=Lv(n),o=t?Rme(t.floating):!1;if(n===l||o&&i)return r;let c={scrollLeft:0,scrollTop:0},d=Cj(1);const h=Cj(0),m=bv(n);if((m||!m&&!i)&&((LI(n)!=="body"||$F(l))&&(c=Ome(n)),bv(n))){const x=k3(n);d=MA(n),h.x=x.x+n.clientLeft,h.y=x.y+n.clientTop}return{width:r.width*d.x,height:r.height*d.y,x:r.x*d.x-c.scrollLeft*d.x+h.x,y:r.y*d.y-c.scrollTop*d.y+h.y}}function PNt(s){return Array.from(s.getClientRects())}function hwe(s,t){const r=Ome(s).scrollLeft;return t?t.left+r:k3(Lv(s)).left+r}function DNt(s){const t=Lv(s),r=Ome(s),n=s.ownerDocument.body,a=Pp(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),i=Pp(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight);let l=-r.scrollLeft+hwe(s);const o=-r.scrollTop;return Ry(n).direction==="rtl"&&(l+=Pp(t.clientWidth,n.clientWidth)-a),{width:a,height:i,x:l,y:o}}function RNt(s,t){const r=Hp(s),n=Lv(s),a=r.visualViewport;let i=n.clientWidth,l=n.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const d=hCe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function ONt(s,t){const r=k3(s,!0,t==="fixed"),n=r.top+s.clientTop,a=r.left+s.clientLeft,i=bv(s)?MA(s):Cj(1),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=n*i.y;return{width:l,height:o,x:c,y:d}}function mDe(s,t,r){let n;if(t==="viewport")n=RNt(s,r);else if(t==="document")n=DNt(Lv(s));else if(Dy(t))n=ONt(t,r);else{const a=AYe(s);n={...t,x:t.x-a.x,y:t.y-a.y}}return cde(n)}function MYe(s,t){const r=Ej(s);return r===t||!Dy(r)||bM(r)?!1:Ry(r).position==="fixed"||MYe(r,t)}function FNt(s,t){const r=t.get(s);if(r)return r;let n=a8(s,[],!1).filter(o=>Dy(o)&&LI(o)!=="body"),a=null;const i=Ry(s).position==="fixed";let l=i?Ej(s):s;for(;Dy(l)&&!bM(l);){const o=Ry(l),c=uCe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||$F(l)&&!c&&MYe(s,l))?n=n.filter(h=>h!==l):a=o,l=Ej(l)}return t.set(s,n),n}function BNt(s){let{element:t,boundary:r,rootBoundary:n,strategy:a}=s;const l=[...r==="clippingAncestors"?Rme(t)?[]:FNt(t,this._c):[].concat(r),n],o=l[0],c=l.reduce((d,h)=>{const m=mDe(t,h,a);return d.top=Pp(m.top,d.top),d.right=Sj(m.right,d.right),d.bottom=Sj(m.bottom,d.bottom),d.left=Pp(m.left,d.left),d},mDe(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function zNt(s){const{width:t,height:r}=EYe(s);return{width:t,height:r}}function $Nt(s,t,r){const n=bv(t),a=Lv(t),i=r==="fixed",l=k3(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=Cj(0);if(n||!n&&!i)if((LI(t)!=="body"||$F(a))&&(o=Ome(t)),n){const y=k3(t,!0,i,t);c.x=y.x+t.clientLeft,c.y=y.y+t.clientTop}else a&&(c.x=hwe(a));let d=0,h=0;if(a&&!n&&!i){const y=a.getBoundingClientRect();h=y.top+o.scrollTop,d=y.left+o.scrollLeft-hwe(a,y)}const m=l.left+o.scrollLeft-c.x-d,x=l.top+o.scrollTop-c.y-h;return{x:m,y:x,width:l.width,height:l.height}}function V0e(s){return Ry(s).position==="static"}function fDe(s,t){if(!bv(s)||Ry(s).position==="fixed")return null;if(t)return t(s);let r=s.offsetParent;return Lv(s)===r&&(r=r.ownerDocument.body),r}function IYe(s,t){const r=Hp(s);if(Rme(s))return r;if(!bv(s)){let a=Ej(s);for(;a&&!bM(a);){if(Dy(a)&&!V0e(a))return a;a=Ej(a)}return r}let n=fDe(s,t);for(;n&&ENt(n)&&V0e(n);)n=fDe(n,t);return n&&bM(n)&&V0e(n)&&!uCe(n)?r:n||ANt(s)||r}const UNt=async function(s){const t=this.getOffsetParent||IYe,r=this.getDimensions,n=await r(s.floating);return{reference:$Nt(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function qNt(s){return Ry(s).direction==="rtl"}const VNt={convertOffsetParentRelativeRectToViewportRelativeRect:LNt,getDocumentElement:Lv,getClippingRect:BNt,getOffsetParent:IYe,getElementRects:UNt,getClientRects:PNt,getDimensions:zNt,getScale:MA,isElement:Dy,isRTL:qNt};function HNt(s,t){let r=null,n;const a=Lv(s);function i(){var o;clearTimeout(n),(o=r)==null||o.disconnect(),r=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:h,width:m,height:x}=s.getBoundingClientRect();if(o||t(),!m||!x)return;const y=I9(h),v=I9(a.clientWidth-(d+m)),w=I9(a.clientHeight-(h+x)),b=I9(d),S={rootMargin:-y+"px "+-v+"px "+-w+"px "+-b+"px",threshold:Pp(0,Sj(1,c))||1};let T=!0;function A(I){const D=I[0].intersectionRatio;if(D!==c){if(!T)return l();D?l(!1,D):n=setTimeout(()=>{l(!1,1e-7)},1e3)}T=!1}try{r=new IntersectionObserver(A,{...S,root:a.ownerDocument})}catch{r=new IntersectionObserver(A,S)}r.observe(s)}return l(!0),i}function GNt(s,t,r,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,d=mCe(s),h=a||i?[...d?a8(d):[],...a8(t)]:[];h.forEach(N=>{a&&N.addEventListener("scroll",r,{passive:!0}),i&&N.addEventListener("resize",r)});const m=d&&o?HNt(d,r):null;let x=-1,y=null;l&&(y=new ResizeObserver(N=>{let[S]=N;S&&S.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(x),x=requestAnimationFrame(()=>{var T;(T=y)==null||T.observe(t)})),r()}),d&&!c&&y.observe(d),y.observe(t));let v,w=c?k3(s):null;c&&b();function b(){const N=k3(s);w&&(N.x!==w.x||N.y!==w.y||N.width!==w.width||N.height!==w.height)&&r(),w=N,v=requestAnimationFrame(b)}return r(),()=>{var N;h.forEach(S=>{a&&S.removeEventListener("scroll",r),i&&S.removeEventListener("resize",r)}),m==null||m(),(N=y)==null||N.disconnect(),y=null,c&&cancelAnimationFrame(v)}}const WNt=kNt,KNt=SNt,YNt=wNt,ZNt=TNt,XNt=jNt,pDe=_Nt,QNt=CNt,JNt=(s,t,r)=>{const n=new Map,a={platform:VNt,...r},i={...a.platform,_c:n};return bNt(s,t,{...a,platform:i})};var Xle=typeof document<"u"?k.useLayoutEffect:k.useEffect;function dde(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 r,n,a;if(s&&t&&typeof s=="object"){if(Array.isArray(s)){if(r=s.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!dde(s[n],t[n]))return!1;return!0}if(a=Object.keys(s),r=a.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(t,a[n]))return!1;for(n=r;n--!==0;){const i=a[n];if(!(i==="_owner"&&s.$$typeof)&&!dde(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function LYe(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function xDe(s,t){const r=LYe(s);return Math.round(t*r)/r}function H0e(s){const t=k.useRef(s);return Xle(()=>{t.current=s}),t}function ekt(s){s===void 0&&(s={});const{placement:t="bottom",strategy:r="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[h,m]=k.useState({x:0,y:0,strategy:r,placement:t,middlewareData:{},isPositioned:!1}),[x,y]=k.useState(n);dde(x,n)||y(n);const[v,w]=k.useState(null),[b,N]=k.useState(null),S=k.useCallback(ne=>{ne!==D.current&&(D.current=ne,w(ne))},[]),T=k.useCallback(ne=>{ne!==R.current&&(R.current=ne,N(ne))},[]),A=i||v,I=l||b,D=k.useRef(null),R=k.useRef(null),$=k.useRef(h),F=c!=null,z=H0e(c),Q=H0e(a),K=H0e(d),X=k.useCallback(()=>{if(!D.current||!R.current)return;const ne={placement:t,strategy:r,middleware:x};Q.current&&(ne.platform=Q.current),JNt(D.current,R.current,ne).then(ie=>{const ye={...ie,isPositioned:K.current!==!1};Z.current&&!dde($.current,ye)&&($.current=ye,Vf.flushSync(()=>{m(ye)}))})},[x,t,r,Q,K]);Xle(()=>{d===!1&&$.current.isPositioned&&($.current.isPositioned=!1,m(ne=>({...ne,isPositioned:!1})))},[d]);const Z=k.useRef(!1);Xle(()=>(Z.current=!0,()=>{Z.current=!1}),[]),Xle(()=>{if(A&&(D.current=A),I&&(R.current=I),A&&I){if(z.current)return z.current(A,I,X);X()}},[A,I,X,z,F]);const re=k.useMemo(()=>({reference:D,floating:R,setReference:S,setFloating:T}),[S,T]),le=k.useMemo(()=>({reference:A,floating:I}),[A,I]),oe=k.useMemo(()=>{const ne={position:r,left:0,top:0};if(!le.floating)return ne;const ie=xDe(le.floating,h.x),ye=xDe(le.floating,h.y);return o?{...ne,transform:"translate("+ie+"px, "+ye+"px)",...LYe(le.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:ie,top:ye}},[r,o,le.floating,h.x,h.y]);return k.useMemo(()=>({...h,update:X,refs:re,elements:le,floatingStyles:oe}),[h,X,re,le,oe])}const tkt=s=>{function t(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:s,fn(r){const{element:n,padding:a}=typeof s=="function"?s(r):s;return n&&t(n)?n.current!=null?pDe({element:n.current,padding:a}).fn(r):{}:n?pDe({element:n,padding:a}).fn(r):{}}}},skt=(s,t)=>({...WNt(s),options:[s,t]}),rkt=(s,t)=>({...KNt(s),options:[s,t]}),nkt=(s,t)=>({...QNt(s),options:[s,t]}),akt=(s,t)=>({...YNt(s),options:[s,t]}),ikt=(s,t)=>({...ZNt(s),options:[s,t]}),okt=(s,t)=>({...XNt(s),options:[s,t]}),lkt=(s,t)=>({...tkt(s),options:[s,t]});var ckt="Arrow",PYe=k.forwardRef((s,t)=>{const{children:r,width:n=10,height:a=5,...i}=s;return e.jsx(wn.svg,{...i,ref:t,width:n,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:s.asChild?r:e.jsx("polygon",{points:"0,0 30,0 15,10"})})});PYe.displayName=ckt;var dkt=PYe;function UF(s){const[t,r]=k.useState(void 0);return Dd(()=>{if(s){r({width:s.offsetWidth,height:s.offsetHeight});const n=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;r({width:l,height:o})});return n.observe(s,{box:"border-box"}),()=>n.unobserve(s)}else r(void 0)},[s]),t}var fCe="Popper",[DYe,Pv]=pd(fCe),[ukt,RYe]=DYe(fCe),OYe=s=>{const{__scopePopper:t,children:r}=s,[n,a]=k.useState(null);return e.jsx(ukt,{scope:t,anchor:n,onAnchorChange:a,children:r})};OYe.displayName=fCe;var FYe="PopperAnchor",BYe=k.forwardRef((s,t)=>{const{__scopePopper:r,virtualRef:n,...a}=s,i=RYe(FYe,r),l=k.useRef(null),o=Ga(t,l);return k.useEffect(()=>{i.onAnchorChange((n==null?void 0:n.current)||l.current)}),n?null:e.jsx(wn.div,{...a,ref:o})});BYe.displayName=FYe;var pCe="PopperContent",[hkt,mkt]=DYe(pCe),zYe=k.forwardRef((s,t)=>{var Ae,He,Le,Ie,Te,xe;const{__scopePopper:r,side:n="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:x=!1,updatePositionStrategy:y="optimized",onPlaced:v,...w}=s,b=RYe(pCe,r),[N,S]=k.useState(null),T=Ga(t,et=>S(et)),[A,I]=k.useState(null),D=UF(A),R=(D==null?void 0:D.width)??0,$=(D==null?void 0:D.height)??0,F=n+(i!=="center"?"-"+i:""),z=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},Q=Array.isArray(d)?d:[d],K=Q.length>0,X={padding:z,boundary:Q.filter(pkt),altBoundary:K},{refs:Z,floatingStyles:re,placement:le,isPositioned:oe,middlewareData:ne}=ekt({strategy:"fixed",placement:F,whileElementsMounted:(...et)=>GNt(...et,{animationFrame:y==="always"}),elements:{reference:b.anchor},middleware:[skt({mainAxis:a+$,alignmentAxis:l}),c&&rkt({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?nkt():void 0,...X}),c&&akt({...X}),ikt({...X,apply:({elements:et,rects:fe,availableWidth:it,availableHeight:Oe})=>{const{width:Ye,height:We}=fe.reference,_e=et.floating.style;_e.setProperty("--radix-popper-available-width",`${it}px`),_e.setProperty("--radix-popper-available-height",`${Oe}px`),_e.setProperty("--radix-popper-anchor-width",`${Ye}px`),_e.setProperty("--radix-popper-anchor-height",`${We}px`)}}),A&&lkt({element:A,padding:o}),xkt({arrowWidth:R,arrowHeight:$}),x&&okt({strategy:"referenceHidden",...X})]}),[ie,ye]=qYe(le),ce=Ed(v);Dd(()=>{oe&&(ce==null||ce())},[oe,ce]);const ve=(Ae=ne.arrow)==null?void 0:Ae.x,be=(He=ne.arrow)==null?void 0:He.y,Ue=((Le=ne.arrow)==null?void 0:Le.centerOffset)!==0,[Be,De]=k.useState();return Dd(()=>{N&&De(window.getComputedStyle(N).zIndex)},[N]),e.jsx("div",{ref:Z.setFloating,"data-radix-popper-content-wrapper":"",style:{...re,transform:oe?re.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Be,"--radix-popper-transform-origin":[(Ie=ne.transformOrigin)==null?void 0:Ie.x,(Te=ne.transformOrigin)==null?void 0:Te.y].join(" "),...((xe=ne.hide)==null?void 0:xe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(hkt,{scope:r,placedSide:ie,onArrowChange:I,arrowX:ve,arrowY:be,shouldHideArrow:Ue,children:e.jsx(wn.div,{"data-side":ie,"data-align":ye,...w,ref:T,style:{...w.style,animation:oe?void 0:"none"}})})})});zYe.displayName=pCe;var $Ye="PopperArrow",fkt={top:"bottom",right:"left",bottom:"top",left:"right"},UYe=k.forwardRef(function(t,r){const{__scopePopper:n,...a}=t,i=mkt($Ye,n),l=fkt[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(dkt,{...a,ref:r,style:{...a.style,display:"block"}})})});UYe.displayName=$Ye;function pkt(s){return s!==null}var xkt=s=>({name:"transformOrigin",options:s,fn(t){var b,N,S;const{placement:r,rects:n,middlewareData:a}=t,l=((b=a.arrow)==null?void 0:b.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,h]=qYe(r),m={start:"0%",center:"50%",end:"100%"}[h],x=(((N=a.arrow)==null?void 0:N.x)??0)+o/2,y=(((S=a.arrow)==null?void 0:S.y)??0)+c/2;let v="",w="";return d==="bottom"?(v=l?m:`${x}px`,w=`${-c}px`):d==="top"?(v=l?m:`${x}px`,w=`${n.floating.height+c}px`):d==="right"?(v=`${-c}px`,w=l?m:`${y}px`):d==="left"&&(v=`${n.floating.width+c}px`,w=l?m:`${y}px`),{data:{x:v,y:w}}}});function qYe(s){const[t,r="center"]=s.split("-");return[t,r]}var qF=OYe,PI=BYe,VF=zYe,HF=UYe,[Fme,oUs]=pd("Tooltip",[Pv]),Bme=Pv(),VYe="TooltipProvider",gkt=700,mwe="tooltip.open",[ykt,xCe]=Fme(VYe),HYe=s=>{const{__scopeTooltip:t,delayDuration:r=gkt,skipDelayDuration:n=300,disableHoverableContent:a=!1,children:i}=s,l=k.useRef(!0),o=k.useRef(!1),c=k.useRef(0);return k.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(ykt,{scope:t,isOpenDelayedRef:l,delayDuration:r,onOpen:k.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:k.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,n)},[n]),isPointerInTransitRef:o,onPointerInTransitChange:k.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};HYe.displayName=VYe;var i8="Tooltip",[vkt,zme]=Fme(i8),GYe=s=>{const{__scopeTooltip:t,children:r,open:n,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=xCe(i8,s.__scopeTooltip),d=Bme(t),[h,m]=k.useState(null),x=Yu(),y=k.useRef(0),v=l??c.disableHoverableContent,w=o??c.delayDuration,b=k.useRef(!1),[N,S]=Sh({prop:n,defaultProp:a??!1,onChange:R=>{R?(c.onOpen(),document.dispatchEvent(new CustomEvent(mwe))):c.onClose(),i==null||i(R)},caller:i8}),T=k.useMemo(()=>N?b.current?"delayed-open":"instant-open":"closed",[N]),A=k.useCallback(()=>{window.clearTimeout(y.current),y.current=0,b.current=!1,S(!0)},[S]),I=k.useCallback(()=>{window.clearTimeout(y.current),y.current=0,S(!1)},[S]),D=k.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{b.current=!0,S(!0),y.current=0},w)},[w,S]);return k.useEffect(()=>()=>{y.current&&(window.clearTimeout(y.current),y.current=0)},[]),e.jsx(qF,{...d,children:e.jsx(vkt,{scope:t,contentId:x,open:N,stateAttribute:T,trigger:h,onTriggerChange:m,onTriggerEnter:k.useCallback(()=>{c.isOpenDelayedRef.current?D():A()},[c.isOpenDelayedRef,D,A]),onTriggerLeave:k.useCallback(()=>{v?I():(window.clearTimeout(y.current),y.current=0)},[I,v]),onOpen:A,onClose:I,disableHoverableContent:v,children:r})})};GYe.displayName=i8;var fwe="TooltipTrigger",WYe=k.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=zme(fwe,r),i=xCe(fwe,r),l=Bme(r),o=k.useRef(null),c=Ga(t,o,a.onTriggerChange),d=k.useRef(!1),h=k.useRef(!1),m=k.useCallback(()=>d.current=!1,[]);return k.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),e.jsx(PI,{asChild:!0,...l,children:e.jsx(wn.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...n,ref:c,onPointerMove:Vr(s.onPointerMove,x=>{x.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),h.current=!0)}),onPointerLeave:Vr(s.onPointerLeave,()=>{a.onTriggerLeave(),h.current=!1}),onPointerDown:Vr(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:Vr(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:Vr(s.onBlur,a.onClose),onClick:Vr(s.onClick,a.onClose)})})});WYe.displayName=fwe;var bkt="TooltipPortal",[lUs,_kt]=Fme(bkt,{forceMount:void 0}),_M="TooltipContent",KYe=k.forwardRef((s,t)=>{const r=_kt(_M,s.__scopeTooltip),{forceMount:n=r.forceMount,side:a="top",...i}=s,l=zme(_M,s.__scopeTooltip);return e.jsx(ru,{present:n||l.open,children:l.disableHoverableContent?e.jsx(YYe,{side:a,...i,ref:t}):e.jsx(wkt,{side:a,...i,ref:t})})}),wkt=k.forwardRef((s,t)=>{const r=zme(_M,s.__scopeTooltip),n=xCe(_M,s.__scopeTooltip),a=k.useRef(null),i=Ga(t,a),[l,o]=k.useState(null),{trigger:c,onClose:d}=r,h=a.current,{onPointerInTransitChange:m}=n,x=k.useCallback(()=>{o(null),m(!1)},[m]),y=k.useCallback((v,w)=>{const b=v.currentTarget,N={x:v.clientX,y:v.clientY},S=Ckt(N,b.getBoundingClientRect()),T=Tkt(N,S),A=Ekt(w.getBoundingClientRect()),I=Mkt([...T,...A]);o(I),m(!0)},[m]);return k.useEffect(()=>()=>x(),[x]),k.useEffect(()=>{if(c&&h){const v=b=>y(b,h),w=b=>y(b,c);return c.addEventListener("pointerleave",v),h.addEventListener("pointerleave",w),()=>{c.removeEventListener("pointerleave",v),h.removeEventListener("pointerleave",w)}}},[c,h,y,x]),k.useEffect(()=>{if(l){const v=w=>{const b=w.target,N={x:w.clientX,y:w.clientY},S=(c==null?void 0:c.contains(b))||(h==null?void 0:h.contains(b)),T=!Akt(N,l);S?x():T&&(x(),d())};return document.addEventListener("pointermove",v),()=>document.removeEventListener("pointermove",v)}},[c,h,l,d,x]),e.jsx(YYe,{...s,ref:i})}),[jkt,Nkt]=Fme(i8,{isInside:!1}),kkt=qKe("TooltipContent"),YYe=k.forwardRef((s,t)=>{const{__scopeTooltip:r,children:n,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=zme(_M,r),d=Bme(r),{onClose:h}=c;return k.useEffect(()=>(document.addEventListener(mwe,h),()=>document.removeEventListener(mwe,h)),[h]),k.useEffect(()=>{if(c.trigger){const m=x=>{const y=x.target;y!=null&&y.contains(c.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[c.trigger,h]),e.jsx(Hj,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:m=>m.preventDefault(),onDismiss:h,children:e.jsxs(VF,{"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(kkt,{children:n}),e.jsx(jkt,{scope:r,isInside:!0,children:e.jsx(Tjt,{id:c.contentId,role:"tooltip",children:a||n})})]})})});KYe.displayName=_M;var ZYe="TooltipArrow",Skt=k.forwardRef((s,t)=>{const{__scopeTooltip:r,...n}=s,a=Bme(r);return Nkt(ZYe,r).isInside?null:e.jsx(HF,{...a,...n,ref:t})});Skt.displayName=ZYe;function Ckt(s,t){const r=Math.abs(t.top-s.y),n=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(r,n,a,i)){case i:return"left";case a:return"right";case r:return"top";case n:return"bottom";default:throw new Error("unreachable")}}function Tkt(s,t,r=5){const n=[];switch(t){case"top":n.push({x:s.x-r,y:s.y+r},{x:s.x+r,y:s.y+r});break;case"bottom":n.push({x:s.x-r,y:s.y-r},{x:s.x+r,y:s.y-r});break;case"left":n.push({x:s.x+r,y:s.y-r},{x:s.x+r,y:s.y+r});break;case"right":n.push({x:s.x-r,y:s.y-r},{x:s.x-r,y:s.y+r});break}return n}function Ekt(s){const{top:t,right:r,bottom:n,left:a}=s;return[{x:a,y:t},{x:r,y:t},{x:r,y:n},{x:a,y:n}]}function Akt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=x>n&&r<(m-d)*(n-h)/(x-h)+d&&(a=!a)}return a}function Mkt(s){const t=s.slice();return t.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),Ikt(t)}function Ikt(s){if(s.length<=1)return s.slice();const t=[];for(let n=0;n=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 r=[];for(let n=s.length-1;n>=0;n--){const a=s[n];for(;r.length>=2;){const i=r[r.length-1],l=r[r.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))r.pop();else break}r.push(a)}return r.pop(),t.length===1&&r.length===1&&t[0].x===r[0].x&&t[0].y===r[0].y?t:t.concat(r)}var Lkt=HYe,Pkt=GYe,Dkt=WYe,XYe=KYe;const Ub=Lkt,cc=Pkt,dc=Dkt,Gl=k.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(XYe,{ref:n,sideOffset:t,className:It("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),...r}));Gl.displayName=XYe.displayName;var DI=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(){}},S3=typeof window>"u"||"Deno"in globalThis;function tf(){}function Rkt(s,t){return typeof s=="function"?s(t):s}function pwe(s){return typeof s=="number"&&s>=0&&s!==1/0}function QYe(s,t){return Math.max(s+(t||0)-Date.now(),0)}function uj(s,t){return typeof s=="function"?s(t):s}function Ux(s,t){return typeof s=="function"?s(t):s}function gDe(s,t){const{type:r="all",exact:n,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(n){if(t.queryHash!==gCe(l,t.options))return!1}else if(!o8(t.queryKey,l))return!1}if(r!=="all"){const c=t.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function yDe(s,t){const{exact:r,status:n,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(r){if(C3(t.options.mutationKey)!==C3(i))return!1}else if(!o8(t.options.mutationKey,i))return!1}return!(n&&t.state.status!==n||a&&!a(t))}function gCe(s,t){return((t==null?void 0:t.queryKeyHashFn)||C3)(s)}function C3(s){return JSON.stringify(s,(t,r)=>xwe(r)?Object.keys(r).sort().reduce((n,a)=>(n[a]=r[a],n),{}):r)}function o8(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(r=>o8(s[r],t[r])):!1}function JYe(s,t){if(s===t)return s;const r=vDe(s)&&vDe(t);if(r||xwe(s)&&xwe(t)){const n=r?s:Object.keys(s),a=n.length,i=r?t:Object.keys(t),l=i.length,o=r?[]:{},c=new Set(n);let d=0;for(let h=0;h{setTimeout(t,s)})}function gwe(s,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(s,t):r.structuralSharing!==!1?JYe(s,t):t}function Fkt(s,t,r=0){const n=[...s,t];return r&&n.length>r?n.slice(1):n}function Bkt(s,t,r=0){const n=[t,...s];return r&&n.length>r?n.slice(0,-1):n}var yCe=Symbol();function eZe(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===yCe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function tZe(s,t){return typeof s=="function"?s(...t):!!s}var x4,_w,tM,yGe,zkt=(yGe=class extends DI{constructor(){super();Ja(this,x4);Ja(this,_w);Ja(this,tM);na(this,tM,t=>{if(!S3&&window.addEventListener){const r=()=>t();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Ss(this,_w)||this.setEventListener(Ss(this,tM))}onUnsubscribe(){var t;this.hasListeners()||((t=Ss(this,_w))==null||t.call(this),na(this,_w,void 0))}setEventListener(t){var r;na(this,tM,t),(r=Ss(this,_w))==null||r.call(this),na(this,_w,t(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(t){Ss(this,x4)!==t&&(na(this,x4,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(r=>{r(t)})}isFocused(){var t;return typeof Ss(this,x4)=="boolean"?Ss(this,x4):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},x4=new WeakMap,_w=new WeakMap,tM=new WeakMap,yGe),vCe=new zkt,sM,ww,rM,vGe,$kt=(vGe=class extends DI{constructor(){super();Ja(this,sM,!0);Ja(this,ww);Ja(this,rM);na(this,rM,t=>{if(!S3&&window.addEventListener){const r=()=>t(!0),n=()=>t(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Ss(this,ww)||this.setEventListener(Ss(this,rM))}onUnsubscribe(){var t;this.hasListeners()||((t=Ss(this,ww))==null||t.call(this),na(this,ww,void 0))}setEventListener(t){var r;na(this,rM,t),(r=Ss(this,ww))==null||r.call(this),na(this,ww,t(this.setOnline.bind(this)))}setOnline(t){Ss(this,sM)!==t&&(na(this,sM,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return Ss(this,sM)}},sM=new WeakMap,ww=new WeakMap,rM=new WeakMap,vGe),hde=new $kt;function ywe(){let s,t;const r=new Promise((a,i)=>{s=a,t=i});r.status="pending",r.catch(()=>{});function n(a){Object.assign(r,a),delete r.resolve,delete r.reject}return r.resolve=a=>{n({status:"fulfilled",value:a}),s(a)},r.reject=a=>{n({status:"rejected",reason:a}),t(a)},r}function Ukt(s){return Math.min(1e3*2**s,3e4)}function sZe(s){return(s??"online")==="online"?hde.isOnline():!0}var rZe=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function G0e(s){return s instanceof rZe}function nZe(s){let t=!1,r=0,n=!1,a;const i=ywe(),l=w=>{var b;n||(x(new rZe(w)),(b=s.abort)==null||b.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>vCe.isFocused()&&(s.networkMode==="always"||hde.isOnline())&&s.canRun(),h=()=>sZe(s.networkMode)&&s.canRun(),m=w=>{var b;n||(n=!0,(b=s.onSuccess)==null||b.call(s,w),a==null||a(),i.resolve(w))},x=w=>{var b;n||(n=!0,(b=s.onError)==null||b.call(s,w),a==null||a(),i.reject(w))},y=()=>new Promise(w=>{var b;a=N=>{(n||d())&&w(N)},(b=s.onPause)==null||b.call(s)}).then(()=>{var w;a=void 0,n||(w=s.onContinue)==null||w.call(s)}),v=()=>{if(n)return;let w;const b=r===0?s.initialPromise:void 0;try{w=b??s.fn()}catch(N){w=Promise.reject(N)}Promise.resolve(w).then(m).catch(N=>{var D;if(n)return;const S=s.retry??(S3?0:3),T=s.retryDelay??Ukt,A=typeof T=="function"?T(r,N):T,I=S===!0||typeof S=="number"&&rd()?void 0:y()).then(()=>{t?x(N):v()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:h,start:()=>(h()?v():y().then(v),i)}}var qkt=s=>setTimeout(s,0);function Vkt(){let s=[],t=0,r=o=>{o()},n=o=>{o()},a=qkt;const i=o=>{t?s.push(o):a(()=>{r(o)})},l=()=>{const o=s;s=[],o.length&&a(()=>{n(()=>{o.forEach(c=>{r(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=>{r=o},setBatchNotifyFunction:o=>{n=o},setScheduler:o=>{a=o}}}var Fu=Vkt(),g4,bGe,aZe=(bGe=class{constructor(){Ja(this,g4)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pwe(this.gcTime)&&na(this,g4,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(S3?1/0:5*60*1e3))}clearGcTimeout(){Ss(this,g4)&&(clearTimeout(Ss(this,g4)),na(this,g4,void 0))}},g4=new WeakMap,bGe),nM,y4,$x,v4,mm,AF,b4,iy,R1,_Ge,Hkt=(_Ge=class extends aZe{constructor(t){super();Ja(this,iy);Ja(this,nM);Ja(this,y4);Ja(this,$x);Ja(this,v4);Ja(this,mm);Ja(this,AF);Ja(this,b4);na(this,b4,!1),na(this,AF,t.defaultOptions),this.setOptions(t.options),this.observers=[],na(this,v4,t.client),na(this,$x,Ss(this,v4).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,na(this,nM,Gkt(this.options)),this.state=t.state??Ss(this,nM),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=Ss(this,mm))==null?void 0:t.promise}setOptions(t){this.options={...Ss(this,AF),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Ss(this,$x).remove(this)}setData(t,r){const n=gwe(this.state.data,t,this.options);return Zi(this,iy,R1).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(t,r){Zi(this,iy,R1).call(this,{type:"setState",state:t,setStateOptions:r})}cancel(t){var n,a;const r=(n=Ss(this,mm))==null?void 0:n.promise;return(a=Ss(this,mm))==null||a.cancel(t),r?r.then(tf).catch(tf):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Ss(this,nM))}isActive(){return this.observers.some(t=>Ux(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===yCe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>uj(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:!QYe(this.state.dataUpdatedAt,t)}onFocus(){var r;const t=this.observers.find(n=>n.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(r=Ss(this,mm))==null||r.continue()}onOnline(){var r;const t=this.observers.find(n=>n.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(r=Ss(this,mm))==null||r.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Ss(this,$x).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(r=>r!==t),this.observers.length||(Ss(this,mm)&&(Ss(this,b4)?Ss(this,mm).cancel({revert:!0}):Ss(this,mm).cancelRetry()),this.scheduleGc()),Ss(this,$x).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Zi(this,iy,R1).call(this,{type:"invalidate"})}fetch(t,r){var d,h,m;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Ss(this,mm))return Ss(this,mm).continueRetry(),Ss(this,mm).promise}if(t&&this.setOptions(t),!this.options.queryFn){const x=this.observers.find(y=>y.options.queryFn);x&&this.setOptions(x.options)}const n=new AbortController,a=x=>{Object.defineProperty(x,"signal",{enumerable:!0,get:()=>(na(this,b4,!0),n.signal)})},i=()=>{const x=eZe(this.options,r),v=(()=>{const w={client:Ss(this,v4),queryKey:this.queryKey,meta:this.meta};return a(w),w})();return na(this,b4,!1),this.options.persister?this.options.persister(x,v,this):x(v)},o=(()=>{const x={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Ss(this,v4),state:this.state,fetchFn:i};return a(x),x})();(d=this.options.behavior)==null||d.onFetch(o,this),na(this,y4,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=o.fetchOptions)==null?void 0:h.meta))&&Zi(this,iy,R1).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta});const c=x=>{var y,v,w,b;G0e(x)&&x.silent||Zi(this,iy,R1).call(this,{type:"error",error:x}),G0e(x)||((v=(y=Ss(this,$x).config).onError)==null||v.call(y,x,this),(b=(w=Ss(this,$x).config).onSettled)==null||b.call(w,this.state.data,x,this)),this.scheduleGc()};return na(this,mm,nZe({initialPromise:r==null?void 0:r.initialPromise,fn:o.fetchFn,abort:n.abort.bind(n),onSuccess:x=>{var y,v,w,b;if(x===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(x)}catch(N){c(N);return}(v=(y=Ss(this,$x).config).onSuccess)==null||v.call(y,x,this),(b=(w=Ss(this,$x).config).onSettled)==null||b.call(w,x,this.state.error,this),this.scheduleGc()},onError:c,onFail:(x,y)=>{Zi(this,iy,R1).call(this,{type:"failed",failureCount:x,error:y})},onPause:()=>{Zi(this,iy,R1).call(this,{type:"pause"})},onContinue:()=>{Zi(this,iy,R1).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),Ss(this,mm).start()}},nM=new WeakMap,y4=new WeakMap,$x=new WeakMap,v4=new WeakMap,mm=new WeakMap,AF=new WeakMap,b4=new WeakMap,iy=new WeakSet,R1=function(t){const r=n=>{switch(t.type){case"failed":return{...n,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...iZe(n.data,this.options),fetchMeta:t.meta??null};case"success":return na(this,y4,void 0),{...n,data:t.data,dataUpdateCount:n.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 G0e(a)&&a.revert&&Ss(this,y4)?{...Ss(this,y4),fetchStatus:"idle"}:{...n,error:a,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...t.state}}};this.state=r(this.state),Fu.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Ss(this,$x).notify({query:this,type:"updated",action:t})})},_Ge);function iZe(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:sZe(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function Gkt(s){const t=typeof s.initialData=="function"?s.initialData():s.initialData,r=t!==void 0,n=r?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var I0,wGe,Wkt=(wGe=class extends DI{constructor(t={}){super();Ja(this,I0);this.config=t,na(this,I0,new Map)}build(t,r,n){const a=r.queryKey,i=r.queryHash??gCe(a,r);let l=this.get(i);return l||(l=new Hkt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(r),state:n,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Ss(this,I0).has(t.queryHash)||(Ss(this,I0).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const r=Ss(this,I0).get(t.queryHash);r&&(t.destroy(),r===t&&Ss(this,I0).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Fu.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Ss(this,I0).get(t)}getAll(){return[...Ss(this,I0).values()]}find(t){const r={exact:!0,...t};return this.getAll().find(n=>gDe(r,n))}findAll(t={}){const r=this.getAll();return Object.keys(t).length>0?r.filter(n=>gDe(t,n)):r}notify(t){Fu.batch(()=>{this.listeners.forEach(r=>{r(t)})})}onFocus(){Fu.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Fu.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},I0=new WeakMap,wGe),L0,Qm,_4,P0,H_,jGe,Kkt=(jGe=class extends aZe{constructor(t){super();Ja(this,P0);Ja(this,L0);Ja(this,Qm);Ja(this,_4);this.mutationId=t.mutationId,na(this,Qm,t.mutationCache),na(this,L0,[]),this.state=t.state||oZe(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Ss(this,L0).includes(t)||(Ss(this,L0).push(t),this.clearGcTimeout(),Ss(this,Qm).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){na(this,L0,Ss(this,L0).filter(r=>r!==t)),this.scheduleGc(),Ss(this,Qm).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Ss(this,L0).length||(this.state.status==="pending"?this.scheduleGc():Ss(this,Qm).remove(this))}continue(){var t;return((t=Ss(this,_4))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,h,m,x,y,v,w,b,N,S,T,A,I,D,R,$;const r=()=>{Zi(this,P0,H_).call(this,{type:"continue"})};na(this,_4,nZe({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(F,z)=>{Zi(this,P0,H_).call(this,{type:"failed",failureCount:F,error:z})},onPause:()=>{Zi(this,P0,H_).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Ss(this,Qm).canRun(this)}));const n=this.state.status==="pending",a=!Ss(this,_4).canStart();try{if(n)r();else{Zi(this,P0,H_).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=Ss(this,Qm).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&&Zi(this,P0,H_).call(this,{type:"pending",context:z,variables:t,isPaused:a})}const F=await Ss(this,_4).start();return await((h=(d=Ss(this,Qm).config).onSuccess)==null?void 0:h.call(d,F,t,this.state.context,this)),await((x=(m=this.options).onSuccess)==null?void 0:x.call(m,F,t,this.state.context)),await((v=(y=Ss(this,Qm).config).onSettled)==null?void 0:v.call(y,F,null,this.state.variables,this.state.context,this)),await((b=(w=this.options).onSettled)==null?void 0:b.call(w,F,null,t,this.state.context)),Zi(this,P0,H_).call(this,{type:"success",data:F}),F}catch(F){try{throw await((S=(N=Ss(this,Qm).config).onError)==null?void 0:S.call(N,F,t,this.state.context,this)),await((A=(T=this.options).onError)==null?void 0:A.call(T,F,t,this.state.context)),await((D=(I=Ss(this,Qm).config).onSettled)==null?void 0:D.call(I,void 0,F,this.state.variables,this.state.context,this)),await(($=(R=this.options).onSettled)==null?void 0:$.call(R,void 0,F,t,this.state.context)),F}finally{Zi(this,P0,H_).call(this,{type:"error",error:F})}}finally{Ss(this,Qm).runNext(this)}}},L0=new WeakMap,Qm=new WeakMap,_4=new WeakMap,P0=new WeakSet,H_=function(t){const r=n=>{switch(t.type){case"failed":return{...n,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,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{...n,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:t.error,failureCount:n.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Fu.batch(()=>{Ss(this,L0).forEach(n=>{n.onMutationUpdate(t)}),Ss(this,Qm).notify({mutation:this,type:"updated",action:t})})},jGe);function oZe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var X1,oy,MF,NGe,Ykt=(NGe=class extends DI{constructor(t={}){super();Ja(this,X1);Ja(this,oy);Ja(this,MF);this.config=t,na(this,X1,new Set),na(this,oy,new Map),na(this,MF,0)}build(t,r,n){const a=new Kkt({mutationCache:this,mutationId:++u9(this,MF)._,options:t.defaultMutationOptions(r),state:n});return this.add(a),a}add(t){Ss(this,X1).add(t);const r=L9(t);if(typeof r=="string"){const n=Ss(this,oy).get(r);n?n.push(t):Ss(this,oy).set(r,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Ss(this,X1).delete(t)){const r=L9(t);if(typeof r=="string"){const n=Ss(this,oy).get(r);if(n)if(n.length>1){const a=n.indexOf(t);a!==-1&&n.splice(a,1)}else n[0]===t&&Ss(this,oy).delete(r)}}this.notify({type:"removed",mutation:t})}canRun(t){const r=L9(t);if(typeof r=="string"){const n=Ss(this,oy).get(r),a=n==null?void 0:n.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var n;const r=L9(t);if(typeof r=="string"){const a=(n=Ss(this,oy).get(r))==null?void 0:n.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Fu.batch(()=>{Ss(this,X1).forEach(t=>{this.notify({type:"removed",mutation:t})}),Ss(this,X1).clear(),Ss(this,oy).clear()})}getAll(){return Array.from(Ss(this,X1))}find(t){const r={exact:!0,...t};return this.getAll().find(n=>yDe(r,n))}findAll(t={}){return this.getAll().filter(r=>yDe(t,r))}notify(t){Fu.batch(()=>{this.listeners.forEach(r=>{r(t)})})}resumePausedMutations(){const t=this.getAll().filter(r=>r.state.isPaused);return Fu.batch(()=>Promise.all(t.map(r=>r.continue().catch(tf))))}},X1=new WeakMap,oy=new WeakMap,MF=new WeakMap,NGe);function L9(s){var t;return(t=s.options.scope)==null?void 0:t.id}function mde(s){return{onFetch:(t,r)=>{var h,m,x,y,v;const n=t.options,a=(x=(m=(h=t.fetchOptions)==null?void 0:h.meta)==null?void 0:m.fetchMore)==null?void 0:x.direction,i=((y=t.state.data)==null?void 0:y.pages)||[],l=((v=t.state.data)==null?void 0:v.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let w=!1;const b=T=>{Object.defineProperty(T,"signal",{enumerable:!0,get:()=>(t.signal.aborted?w=!0:t.signal.addEventListener("abort",()=>{w=!0}),t.signal)})},N=eZe(t.options,t.fetchOptions),S=async(T,A,I)=>{if(w)return Promise.reject();if(A==null&&T.pages.length)return Promise.resolve(T);const R=(()=>{const Q={client:t.client,queryKey:t.queryKey,pageParam:A,direction:I?"backward":"forward",meta:t.options.meta};return b(Q),Q})(),$=await N(R),{maxPages:F}=t.options,z=I?Bkt:Fkt;return{pages:z(T.pages,$,F),pageParams:z(T.pageParams,A,F)}};if(a&&i.length){const T=a==="backward",A=T?lZe:vwe,I={pages:i,pageParams:l},D=A(n,I);o=await S(I,D,T)}else{const T=s??i.length;do{const A=c===0?l[0]??n.initialPageParam:vwe(n,o);if(c>0&&A==null)break;o=await S(o,A),c++}while(c{var w,b;return(b=(w=t.options).persister)==null?void 0:b.call(w,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r)}:t.fetchFn=d}}}function vwe(s,{pages:t,pageParams:r}){const n=t.length-1;return t.length>0?s.getNextPageParam(t[n],t,r[n],r):void 0}function lZe(s,{pages:t,pageParams:r}){var n;return t.length>0?(n=s.getPreviousPageParam)==null?void 0:n.call(s,t[0],t,r[0],r):void 0}function Zkt(s,t){return t?vwe(s,t)!=null:!1}function Xkt(s,t){return!t||!s.getPreviousPageParam?!1:lZe(s,t)!=null}var wd,jw,Nw,aM,iM,kw,oM,lM,kGe,Qkt=(kGe=class{constructor(s={}){Ja(this,wd);Ja(this,jw);Ja(this,Nw);Ja(this,aM);Ja(this,iM);Ja(this,kw);Ja(this,oM);Ja(this,lM);na(this,wd,s.queryCache||new Wkt),na(this,jw,s.mutationCache||new Ykt),na(this,Nw,s.defaultOptions||{}),na(this,aM,new Map),na(this,iM,new Map),na(this,kw,0)}mount(){u9(this,kw)._++,Ss(this,kw)===1&&(na(this,oM,vCe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Ss(this,wd).onFocus())})),na(this,lM,hde.subscribe(async s=>{s&&(await this.resumePausedMutations(),Ss(this,wd).onOnline())})))}unmount(){var s,t;u9(this,kw)._--,Ss(this,kw)===0&&((s=Ss(this,oM))==null||s.call(this),na(this,oM,void 0),(t=Ss(this,lM))==null||t.call(this),na(this,lM,void 0))}isFetching(s){return Ss(this,wd).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Ss(this,jw).findAll({...s,status:"pending"}).length}getQueryData(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Ss(this,wd).get(t.queryHash))==null?void 0:r.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),r=Ss(this,wd).build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(s):(s.revalidateIfStale&&r.isStaleByTime(uj(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(s){return Ss(this,wd).findAll(s).map(({queryKey:t,state:r})=>{const n=r.data;return[t,n]})}setQueryData(s,t,r){const n=this.defaultQueryOptions({queryKey:s}),a=Ss(this,wd).get(n.queryHash),i=a==null?void 0:a.state.data,l=Rkt(t,i);if(l!==void 0)return Ss(this,wd).build(this,n).setData(l,{...r,manual:!0})}setQueriesData(s,t,r){return Fu.batch(()=>Ss(this,wd).findAll(s).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(s){var r;const t=this.defaultQueryOptions({queryKey:s});return(r=Ss(this,wd).get(t.queryHash))==null?void 0:r.state}removeQueries(s){const t=Ss(this,wd);Fu.batch(()=>{t.findAll(s).forEach(r=>{t.remove(r)})})}resetQueries(s,t){const r=Ss(this,wd);return Fu.batch(()=>(r.findAll(s).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const r={revert:!0,...t},n=Fu.batch(()=>Ss(this,wd).findAll(s).map(a=>a.cancel(r)));return Promise.all(n).then(tf).catch(tf)}invalidateQueries(s,t={}){return Fu.batch(()=>(Ss(this,wd).findAll(s).forEach(r=>{r.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 r={...t,cancelRefetch:t.cancelRefetch??!0},n=Fu.batch(()=>Ss(this,wd).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,r);return r.throwOnError||(i=i.catch(tf)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(n).then(tf)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const r=Ss(this,wd).build(this,t);return r.isStaleByTime(uj(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(tf).catch(tf)}fetchInfiniteQuery(s){return s.behavior=mde(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(tf).catch(tf)}ensureInfiniteQueryData(s){return s.behavior=mde(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return hde.isOnline()?Ss(this,jw).resumePausedMutations():Promise.resolve()}getQueryCache(){return Ss(this,wd)}getMutationCache(){return Ss(this,jw)}getDefaultOptions(){return Ss(this,Nw)}setDefaultOptions(s){na(this,Nw,s)}setQueryDefaults(s,t){Ss(this,aM).set(C3(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Ss(this,aM).values()],r={};return t.forEach(n=>{o8(s,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(s,t){Ss(this,iM).set(C3(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Ss(this,iM).values()],r={};return t.forEach(n=>{o8(s,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Ss(this,Nw).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=gCe(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===yCe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Ss(this,Nw).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Ss(this,wd).clear(),Ss(this,jw).clear()}},wd=new WeakMap,jw=new WeakMap,Nw=new WeakMap,aM=new WeakMap,iM=new WeakMap,kw=new WeakMap,oM=new WeakMap,lM=new WeakMap,kGe),Df,ko,IF,Jm,w4,cM,Sw,Cw,LF,dM,uM,j4,N4,Tw,hM,_l,TD,bwe,_we,wwe,jwe,Nwe,kwe,Swe,dZe,SGe,cZe=(SGe=class extends DI{constructor(t,r){super();Ja(this,_l);Ja(this,Df);Ja(this,ko);Ja(this,IF);Ja(this,Jm);Ja(this,w4);Ja(this,cM);Ja(this,Sw);Ja(this,Cw);Ja(this,LF);Ja(this,dM);Ja(this,uM);Ja(this,j4);Ja(this,N4);Ja(this,Tw);Ja(this,hM,new Set);this.options=r,na(this,Df,t),na(this,Cw,null),na(this,Sw,ywe()),this.options.experimental_prefetchInRender||Ss(this,Sw).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Ss(this,ko).addObserver(this),_De(Ss(this,ko),this.options)?Zi(this,_l,TD).call(this):this.updateResult(),Zi(this,_l,jwe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Cwe(Ss(this,ko),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Cwe(Ss(this,ko),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Zi(this,_l,Nwe).call(this),Zi(this,_l,kwe).call(this),Ss(this,ko).removeObserver(this)}setOptions(t){const r=this.options,n=Ss(this,ko);if(this.options=Ss(this,Df).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ux(this.options.enabled,Ss(this,ko))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Zi(this,_l,Swe).call(this),Ss(this,ko).setOptions(this.options),r._defaulted&&!ude(this.options,r)&&Ss(this,Df).getQueryCache().notify({type:"observerOptionsUpdated",query:Ss(this,ko),observer:this});const a=this.hasListeners();a&&wDe(Ss(this,ko),n,this.options,r)&&Zi(this,_l,TD).call(this),this.updateResult(),a&&(Ss(this,ko)!==n||Ux(this.options.enabled,Ss(this,ko))!==Ux(r.enabled,Ss(this,ko))||uj(this.options.staleTime,Ss(this,ko))!==uj(r.staleTime,Ss(this,ko)))&&Zi(this,_l,bwe).call(this);const i=Zi(this,_l,_we).call(this);a&&(Ss(this,ko)!==n||Ux(this.options.enabled,Ss(this,ko))!==Ux(r.enabled,Ss(this,ko))||i!==Ss(this,Tw))&&Zi(this,_l,wwe).call(this,i)}getOptimisticResult(t){const r=Ss(this,Df).getQueryCache().build(Ss(this,Df),t),n=this.createResult(r,t);return eSt(this,n)&&(na(this,Jm,n),na(this,cM,this.options),na(this,w4,Ss(this,ko).state)),n}getCurrentResult(){return Ss(this,Jm)}trackResult(t,r){return new Proxy(t,{get:(n,a)=>(this.trackProp(a),r==null||r(a),Reflect.get(n,a))})}trackProp(t){Ss(this,hM).add(t)}getCurrentQuery(){return Ss(this,ko)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const r=Ss(this,Df).defaultQueryOptions(t),n=Ss(this,Df).getQueryCache().build(Ss(this,Df),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(t){return Zi(this,_l,TD).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Ss(this,Jm)))}createResult(t,r){var F;const n=Ss(this,ko),a=this.options,i=Ss(this,Jm),l=Ss(this,w4),o=Ss(this,cM),d=t!==n?t.state:Ss(this,IF),{state:h}=t;let m={...h},x=!1,y;if(r._optimisticResults){const z=this.hasListeners(),Q=!z&&_De(t,r),K=z&&wDe(t,n,r,a);(Q||K)&&(m={...m,...iZe(h.data,t.options)}),r._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:v,errorUpdatedAt:w,status:b}=m;y=m.data;let N=!1;if(r.placeholderData!==void 0&&y===void 0&&b==="pending"){let z;i!=null&&i.isPlaceholderData&&r.placeholderData===(o==null?void 0:o.placeholderData)?(z=i.data,N=!0):z=typeof r.placeholderData=="function"?r.placeholderData((F=Ss(this,uM))==null?void 0:F.state.data,Ss(this,uM)):r.placeholderData,z!==void 0&&(b="success",y=gwe(i==null?void 0:i.data,z,r),x=!0)}if(r.select&&y!==void 0&&!N)if(i&&y===(l==null?void 0:l.data)&&r.select===Ss(this,LF))y=Ss(this,dM);else try{na(this,LF,r.select),y=r.select(y),y=gwe(i==null?void 0:i.data,y,r),na(this,dM,y),na(this,Cw,null)}catch(z){na(this,Cw,z)}Ss(this,Cw)&&(v=Ss(this,Cw),y=Ss(this,dM),w=Date.now(),b="error");const S=m.fetchStatus==="fetching",T=b==="pending",A=b==="error",I=T&&S,D=y!==void 0,$={status:b,fetchStatus:m.fetchStatus,isPending:T,isSuccess:b==="success",isError:A,isInitialLoading:I,isLoading:I,data:y,dataUpdatedAt:m.dataUpdatedAt,error:v,errorUpdatedAt:w,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>d.dataUpdateCount||m.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!T,isLoadingError:A&&!D,isPaused:m.fetchStatus==="paused",isPlaceholderData:x,isRefetchError:A&&D,isStale:bCe(t,r),refetch:this.refetch,promise:Ss(this,Sw),isEnabled:Ux(r.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const z=X=>{$.status==="error"?X.reject($.error):$.data!==void 0&&X.resolve($.data)},Q=()=>{const X=na(this,Sw,$.promise=ywe());z(X)},K=Ss(this,Sw);switch(K.status){case"pending":t.queryHash===n.queryHash&&z(K);break;case"fulfilled":($.status==="error"||$.data!==K.value)&&Q();break;case"rejected":($.status!=="error"||$.error!==K.reason)&&Q();break}}return $}updateResult(){const t=Ss(this,Jm),r=this.createResult(Ss(this,ko),this.options);if(na(this,w4,Ss(this,ko).state),na(this,cM,this.options),Ss(this,w4).data!==void 0&&na(this,uM,Ss(this,ko)),ude(r,t))return;na(this,Jm,r);const n=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Ss(this,hM).size)return!0;const l=new Set(i??Ss(this,hM));return this.options.throwOnError&&l.add("error"),Object.keys(Ss(this,Jm)).some(o=>{const c=o;return Ss(this,Jm)[c]!==t[c]&&l.has(c)})};Zi(this,_l,dZe).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Zi(this,_l,jwe).call(this)}},Df=new WeakMap,ko=new WeakMap,IF=new WeakMap,Jm=new WeakMap,w4=new WeakMap,cM=new WeakMap,Sw=new WeakMap,Cw=new WeakMap,LF=new WeakMap,dM=new WeakMap,uM=new WeakMap,j4=new WeakMap,N4=new WeakMap,Tw=new WeakMap,hM=new WeakMap,_l=new WeakSet,TD=function(t){Zi(this,_l,Swe).call(this);let r=Ss(this,ko).fetch(this.options,t);return t!=null&&t.throwOnError||(r=r.catch(tf)),r},bwe=function(){Zi(this,_l,Nwe).call(this);const t=uj(this.options.staleTime,Ss(this,ko));if(S3||Ss(this,Jm).isStale||!pwe(t))return;const n=QYe(Ss(this,Jm).dataUpdatedAt,t)+1;na(this,j4,setTimeout(()=>{Ss(this,Jm).isStale||this.updateResult()},n))},_we=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Ss(this,ko)):this.options.refetchInterval)??!1},wwe=function(t){Zi(this,_l,kwe).call(this),na(this,Tw,t),!(S3||Ux(this.options.enabled,Ss(this,ko))===!1||!pwe(Ss(this,Tw))||Ss(this,Tw)===0)&&na(this,N4,setInterval(()=>{(this.options.refetchIntervalInBackground||vCe.isFocused())&&Zi(this,_l,TD).call(this)},Ss(this,Tw)))},jwe=function(){Zi(this,_l,bwe).call(this),Zi(this,_l,wwe).call(this,Zi(this,_l,_we).call(this))},Nwe=function(){Ss(this,j4)&&(clearTimeout(Ss(this,j4)),na(this,j4,void 0))},kwe=function(){Ss(this,N4)&&(clearInterval(Ss(this,N4)),na(this,N4,void 0))},Swe=function(){const t=Ss(this,Df).getQueryCache().build(Ss(this,Df),this.options);if(t===Ss(this,ko))return;const r=Ss(this,ko);na(this,ko,t),na(this,IF,t.state),this.hasListeners()&&(r==null||r.removeObserver(this),t.addObserver(this))},dZe=function(t){Fu.batch(()=>{t.listeners&&this.listeners.forEach(r=>{r(Ss(this,Jm))}),Ss(this,Df).getQueryCache().notify({query:Ss(this,ko),type:"observerResultsUpdated"})})},SGe);function Jkt(s,t){return Ux(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function _De(s,t){return Jkt(s,t)||s.state.data!==void 0&&Cwe(s,t,t.refetchOnMount)}function Cwe(s,t,r){if(Ux(t.enabled,s)!==!1&&uj(t.staleTime,s)!=="static"){const n=typeof r=="function"?r(s):r;return n==="always"||n!==!1&&bCe(s,t)}return!1}function wDe(s,t,r,n){return(s!==t||Ux(n.enabled,s)===!1)&&(!r.suspense||s.state.status!=="error")&&bCe(s,r)}function bCe(s,t){return Ux(t.enabled,s)!==!1&&s.isStaleByTime(uj(t.staleTime,s))}function eSt(s,t){return!ude(s.getCurrentResult(),t)}var tSt=class extends cZe{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:mde()})}getOptimisticResult(s){return s.behavior=mde(),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 v,w;const{state:r}=s,n=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=n,c=(w=(v=r.fetchMeta)==null?void 0:v.fetchMore)==null?void 0:w.direction,d=l&&c==="forward",h=a&&c==="forward",m=l&&c==="backward",x=a&&c==="backward";return{...n,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Zkt(t,r.data),hasPreviousPage:Xkt(t,r.data),isFetchNextPageError:d,isFetchingNextPage:h,isFetchPreviousPageError:m,isFetchingPreviousPage:x,isRefetchError:o&&!d&&!m,isRefetching:i&&!h&&!x}}},Ew,Aw,Rf,Q1,Nb,Qle,Twe,CGe,sSt=(CGe=class extends DI{constructor(r,n){super();Ja(this,Nb);Ja(this,Ew);Ja(this,Aw);Ja(this,Rf);Ja(this,Q1);na(this,Ew,r),this.setOptions(n),this.bindMethods(),Zi(this,Nb,Qle).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var a;const n=this.options;this.options=Ss(this,Ew).defaultMutationOptions(r),ude(this.options,n)||Ss(this,Ew).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Ss(this,Rf),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&C3(n.mutationKey)!==C3(this.options.mutationKey)?this.reset():((a=Ss(this,Rf))==null?void 0:a.state.status)==="pending"&&Ss(this,Rf).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Ss(this,Rf))==null||r.removeObserver(this)}onMutationUpdate(r){Zi(this,Nb,Qle).call(this),Zi(this,Nb,Twe).call(this,r)}getCurrentResult(){return Ss(this,Aw)}reset(){var r;(r=Ss(this,Rf))==null||r.removeObserver(this),na(this,Rf,void 0),Zi(this,Nb,Qle).call(this),Zi(this,Nb,Twe).call(this)}mutate(r,n){var a;return na(this,Q1,n),(a=Ss(this,Rf))==null||a.removeObserver(this),na(this,Rf,Ss(this,Ew).getMutationCache().build(Ss(this,Ew),this.options)),Ss(this,Rf).addObserver(this),Ss(this,Rf).execute(r)}},Ew=new WeakMap,Aw=new WeakMap,Rf=new WeakMap,Q1=new WeakMap,Nb=new WeakSet,Qle=function(){var n;const r=((n=Ss(this,Rf))==null?void 0:n.state)??oZe();na(this,Aw,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},Twe=function(r){Fu.batch(()=>{var n,a,i,l,o,c,d,h;if(Ss(this,Q1)&&this.hasListeners()){const m=Ss(this,Aw).variables,x=Ss(this,Aw).context;(r==null?void 0:r.type)==="success"?((a=(n=Ss(this,Q1)).onSuccess)==null||a.call(n,r.data,m,x),(l=(i=Ss(this,Q1)).onSettled)==null||l.call(i,r.data,null,m,x)):(r==null?void 0:r.type)==="error"&&((c=(o=Ss(this,Q1)).onError)==null||c.call(o,r.error,m,x),(h=(d=Ss(this,Q1)).onSettled)==null||h.call(d,void 0,r.error,m,x))}this.listeners.forEach(m=>{m(Ss(this,Aw))})})},CGe),uZe=k.createContext(void 0),Xt=s=>{const t=k.useContext(uZe);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rSt=({client:s,children:t})=>(k.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(uZe.Provider,{value:s,children:t})),hZe=k.createContext(!1),nSt=()=>k.useContext(hZe);hZe.Provider;function aSt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var iSt=k.createContext(aSt()),oSt=()=>k.useContext(iSt),lSt=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},cSt=s=>{k.useEffect(()=>{s.clearReset()},[s])},dSt=({result:s,errorResetBoundary:t,throwOnError:r,query:n,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&n&&(a&&s.data===void 0||tZe(r,[s.error,n])),uSt=s=>{if(s.suspense){const t=n=>n==="static"?n:Math.max(n??1e3,1e3),r=s.staleTime;s.staleTime=typeof r=="function"?(...n)=>t(r(...n)):t(r),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},hSt=(s,t)=>s.isLoading&&s.isFetching&&!t,mSt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,jDe=(s,t,r)=>t.fetchOptimistic(s).catch(()=>{r.clearReset()});function mZe(s,t,r){var m,x,y,v,w;const n=nSt(),a=oSt(),i=Xt(),l=i.defaultQueryOptions(s);(x=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||x.call(m,l),l._optimisticResults=n?"isRestoring":"optimistic",uSt(l),lSt(l,a),cSt(a);const o=!i.getQueryCache().get(l.queryHash),[c]=k.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),h=!n&&s.subscribed!==!1;if(k.useSyncExternalStore(k.useCallback(b=>{const N=h?c.subscribe(Fu.batchCalls(b)):tf;return c.updateResult(),N},[c,h]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),k.useEffect(()=>{c.setOptions(l)},[l,c]),mSt(l,d))throw jDe(l,c,a);if(dSt({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((v=(y=i.getDefaultOptions().queries)==null?void 0:y._experimental_afterQuery)==null||v.call(y,l,d),l.experimental_prefetchInRender&&!S3&&hSt(d,n)){const b=o?jDe(l,c,a):(w=i.getQueryCache().get(l.queryHash))==null?void 0:w.promise;b==null||b.catch(tf).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function mt(s,t){return mZe(s,cZe)}function Ct(s,t){const r=Xt(),[n]=k.useState(()=>new sSt(r,s));k.useEffect(()=>{n.setOptions(s)},[n,s]);const a=k.useSyncExternalStore(k.useCallback(l=>n.subscribe(Fu.batchCalls(l)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),i=k.useCallback((l,o)=>{n.mutate(l,o).catch(tf)},[n]);if(a.error&&tZe(n.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function fSt(s,t){return mZe(s,tSt)}/** * @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 l8(){return l8=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function fZe(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function xSt(){return Math.random().toString(36).substr(2,8)}function kDe(s,t){return{usr:s.state,key:s.key,idx:t}}function Ewe(s,t,r,n){return r===void 0&&(r=null),l8({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?RI(t):t,{state:r,key:t&&t.key||n||xSt()})}function fde(s){let{pathname:t="/",search:r="",hash:n=""}=s;return r&&r!=="?"&&(t+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(t+=n.charAt(0)==="#"?n:"#"+n),t}function RI(s){let t={};if(s){let r=s.indexOf("#");r>=0&&(t.hash=s.substr(r),s=s.substr(0,r));let n=s.indexOf("?");n>=0&&(t.search=s.substr(n),s=s.substr(0,n)),s&&(t.pathname=s)}return t}function gSt(s,t,r,n){n===void 0&&(n={});let{window:a=document.defaultView,v5Compat:i=!1}=n,l=a.history,o=Lw.Pop,c=null,d=h();d==null&&(d=0,l.replaceState(l8({},l.state,{idx:d}),""));function h(){return(l.state||{idx:null}).idx}function m(){o=Lw.Pop;let b=h(),N=b==null?null:b-d;d=b,c&&c({action:o,location:w.location,delta:N})}function x(b,N){o=Lw.Push;let S=Ewe(w.location,b,N);d=h()+1;let T=kDe(S,d),A=w.createHref(S);try{l.pushState(T,"",A)}catch(I){if(I instanceof DOMException&&I.name==="DataCloneError")throw I;a.location.assign(A)}i&&c&&c({action:o,location:w.location,delta:1})}function y(b,N){o=Lw.Replace;let S=Ewe(w.location,b,N);d=h();let T=kDe(S,d),A=w.createHref(S);l.replaceState(T,"",A),i&&c&&c({action:o,location:w.location,delta:0})}function v(b){let N=a.location.origin!=="null"?a.location.origin:a.location.href,S=typeof b=="string"?b:fde(b);return S=S.replace(/ $/,"%20"),tu(N,"No window.location.(origin|href) available to create URL for href: "+S),new URL(S,N)}let w={get action(){return o},get location(){return s(a,l)},listen(b){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(NDe,m),c=b,()=>{a.removeEventListener(NDe,m),c=null}},createHref(b){return t(a,b)},createURL:v,encodeLocation(b){let N=v(b);return{pathname:N.pathname,search:N.search,hash:N.hash}},push:x,replace:y,go(b){return l.go(b)}};return w}var SDe;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(SDe||(SDe={}));function ySt(s,t,r){return r===void 0&&(r="/"),vSt(s,t,r,!1)}function vSt(s,t,r,n){let a=typeof t=="string"?RI(t):t,i=_Ce(a.pathname||"/",r);if(i==null)return null;let l=pZe(s);bSt(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("/")&&(tu(c.relativePath.startsWith(n),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(n.length));let d=hj([n,c.relativePath]),h=r.concat(c);i.children&&i.children.length>0&&(tu(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),pZe(i.children,t,h,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:CSt(d,i.index),routesMeta:h})};return s.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of xZe(i.path))a(i,l,c)}),t}function xZe(s){let t=s.split("/");if(t.length===0)return[];let[r,...n]=t,a=r.endsWith("?"),i=r.replace(/\?$/,"");if(n.length===0)return a?[i,""]:[i];let l=xZe(n.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 bSt(s){s.sort((t,r)=>t.score!==r.score?r.score-t.score:TSt(t.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const _St=/^:[\w-]+$/,wSt=3,jSt=2,NSt=1,kSt=10,SSt=-2,CDe=s=>s==="*";function CSt(s,t){let r=s.split("/"),n=r.length;return r.some(CDe)&&(n+=SSt),t&&(n+=jSt),r.filter(a=>!CDe(a)).reduce((a,i)=>a+(_St.test(i)?wSt:i===""?NSt:kSt),n)}function TSt(s,t){return s.length===t.length&&s.slice(0,-1).every((n,a)=>n===t[a])?s[s.length-1]-t[t.length-1]:0}function ESt(s,t,r){let{routesMeta:n}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:x,isOptional:y}=h;if(x==="*"){let w=o[m]||"";l=i.slice(0,i.length-w.length).replace(/(.)\/+$/,"$1")}const v=o[m];return y&&!v?d[x]=void 0:d[x]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function ASt(s,t,r){t===void 0&&(t=!1),r===void 0&&(r=!0),fZe(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 n=[],a="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(n.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return s.endsWith("*")?(n.push({paramName:"*"}),a+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?a+="\\/*$":s!==""&&s!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),n]}function MSt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return fZe(!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 _Ce(s,t){if(t==="/")return s;if(!s.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,n=s.charAt(r);return n&&n!=="/"?null:s.slice(r)||"/"}function ISt(s,t){t===void 0&&(t="/");let{pathname:r,search:n="",hash:a=""}=typeof s=="string"?RI(s):s;return{pathname:r?r.startsWith("/")?r:LSt(r,t):t,search:RSt(n),hash:OSt(a)}}function LSt(s,t){let r=t.replace(/\/+$/,"").split("/");return s.split("/").forEach(a=>{a===".."?r.length>1&&r.pop():a!=="."&&r.push(a)}),r.length>1?r.join("/"):"/"}function W0e(s,t,r,n){return"Cannot include a '"+s+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function PSt(s){return s.filter((t,r)=>r===0||t.route.path&&t.route.path.length>0)}function wCe(s,t){let r=PSt(s);return t?r.map((n,a)=>a===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function jCe(s,t,r,n){n===void 0&&(n=!1);let a;typeof s=="string"?a=RI(s):(a=l8({},s),tu(!a.pathname||!a.pathname.includes("?"),W0e("?","pathname","search",a)),tu(!a.pathname||!a.pathname.includes("#"),W0e("#","pathname","hash",a)),tu(!a.search||!a.search.includes("#"),W0e("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=r;else{let m=t.length-1;if(!n&&l.startsWith("..")){let x=l.split("/");for(;x[0]==="..";)x.shift(),m-=1;a.pathname=x.join("/")}o=m>=0?t[m]:"/"}let c=ISt(a,o),d=l&&l!=="/"&&l.endsWith("/"),h=(i||l===".")&&r.endsWith("/");return!c.pathname.endsWith("/")&&(d||h)&&(c.pathname+="/"),c}const hj=s=>s.join("/").replace(/\/\/+/g,"/"),DSt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),RSt=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,OSt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function FSt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const gZe=["post","put","patch","delete"];new Set(gZe);const BSt=["get",...gZe];new Set(BSt);/** * 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 c8(){return c8=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),k.useCallback(function(d,h){if(h===void 0&&(h={}),!o.current)return;if(typeof d=="number"){n.go(d);return}let m=jCe(d,JSON.parse(l),i,h.relative==="path");s==null&&t!=="/"&&(m.pathname=m.pathname==="/"?t:hj([t,m.pathname])),(h.replace?n.replace:n.push)(m,h.state,h)},[t,n,l,i,s])}const qSt=k.createContext(null);function VSt(s){let t=k.useContext(Dv).outlet;return t&&k.createElement(qSt.Provider,{value:s},t)}function Ki(){let{matches:s}=k.useContext(Dv),t=s[s.length-1];return t?t.params:{}}function bZe(s,t){let{relative:r}=t===void 0?{}:t,{future:n}=k.useContext(Gj),{matches:a}=k.useContext(Dv),{pathname:i}=ec(),l=JSON.stringify(wCe(a,n.v7_relativeSplatPath));return k.useMemo(()=>jCe(s,JSON.parse(l),i,r==="path"),[s,l,i,r])}function HSt(s,t){return GSt(s,t)}function GSt(s,t,r,n){OI()||tu(!1);let{navigator:a}=k.useContext(Gj),{matches:i}=k.useContext(Dv),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=ec(),h;if(t){var m;let b=typeof t=="string"?RI(t):t;c==="/"||(m=b.pathname)!=null&&m.startsWith(c)||tu(!1),h=b}else h=d;let x=h.pathname||"/",y=x;if(c!=="/"){let b=c.replace(/^\//,"").split("/");y="/"+x.replace(/^\//,"").split("/").slice(b.length).join("/")}let v=ySt(s,{pathname:y}),w=XSt(v&&v.map(b=>Object.assign({},b,{params:Object.assign({},o,b.params),pathname:hj([c,a.encodeLocation?a.encodeLocation(b.pathname).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:hj([c,a.encodeLocation?a.encodeLocation(b.pathnameBase).pathname:b.pathnameBase])})),i,r,n);return t&&w?k.createElement($me.Provider,{value:{location:c8({pathname:"/",search:"",hash:"",state:null,key:"default"},h),navigationType:Lw.Pop}},w):w}function WSt(){let s=tCt(),t=FSt(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),r=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},t),r?k.createElement("pre",{style:a},r):null,null)}const KSt=k.createElement(WSt,null);class YSt extends k.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,r){return r.location!==t.location||r.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:r.error,location:r.location,revalidation:t.revalidation||r.revalidation}}componentDidCatch(t,r){console.error("React Router caught the following error during render",t,r)}render(){return this.state.error!==void 0?k.createElement(Dv.Provider,{value:this.props.routeContext},k.createElement(yZe.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function ZSt(s){let{routeContext:t,match:r,children:n}=s,a=k.useContext(NCe);return a&&a.static&&a.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=r.route.id),k.createElement(Dv.Provider,{value:t},n)}function XSt(s,t,r,n){var a;if(t===void 0&&(t=[]),r===void 0&&(r=null),n===void 0&&(n=null),s==null){var i;if(!r)return null;if(r.errors)s=r.matches;else if((i=n)!=null&&i.v7_partialHydration&&t.length===0&&!r.initialized&&r.matches.length>0)s=r.matches;else return null}let l=s,o=(a=r)==null?void 0:a.errors;if(o!=null){let h=l.findIndex(m=>m.route.id&&(o==null?void 0:o[m.route.id])!==void 0);h>=0||tu(!1),l=l.slice(0,Math.min(l.length,h+1))}let c=!1,d=-1;if(r&&n&&n.v7_partialHydration)for(let h=0;h=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((h,m,x)=>{let y,v=!1,w=null,b=null;r&&(y=o&&m.route.id?o[m.route.id]:void 0,w=m.route.errorElement||KSt,c&&(d<0&&x===0?(v=!0,b=null):d===x&&(v=!0,b=m.route.hydrateFallbackElement||null)));let N=t.concat(l.slice(0,x+1)),S=()=>{let T;return y?T=w:v?T=b:m.route.Component?T=k.createElement(m.route.Component,null):m.route.element?T=m.route.element:T=h,k.createElement(ZSt,{match:m,routeContext:{outlet:h,matches:N,isDataRoute:r!=null},children:T})};return r&&(m.route.ErrorBoundary||m.route.errorElement||x===0)?k.createElement(YSt,{location:r.location,revalidation:r.revalidation,component:w,error:y,children:S(),routeContext:{outlet:null,matches:N,isDataRoute:!0}}):S()},null)}var _Ze=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(_Ze||{}),pde=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}(pde||{});function QSt(s){let t=k.useContext(NCe);return t||tu(!1),t}function JSt(s){let t=k.useContext(zSt);return t||tu(!1),t}function eCt(s){let t=k.useContext(Dv);return t||tu(!1),t}function wZe(s){let t=eCt(),r=t.matches[t.matches.length-1];return r.route.id||tu(!1),r.route.id}function tCt(){var s;let t=k.useContext(yZe),r=JSt(pde.UseRouteError),n=wZe(pde.UseRouteError);return t!==void 0?t:(s=r.errors)==null?void 0:s[n]}function sCt(){let{router:s}=QSt(_Ze.UseNavigateStable),t=wZe(pde.UseNavigateStable),r=k.useRef(!1);return vZe(()=>{r.current=!0}),k.useCallback(function(a,i){i===void 0&&(i={}),r.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,c8({fromRouteId:t},i)))},[s,t])}function rCt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function K0e(s){let{to:t,replace:r,state:n,relative:a}=s;OI()||tu(!1);let{future:i,static:l}=k.useContext(Gj),{matches:o}=k.useContext(Dv),{pathname:c}=ec(),d=br(),h=jCe(t,wCe(o,i.v7_relativeSplatPath),c,a==="path"),m=JSON.stringify(h);return k.useEffect(()=>d(JSON.parse(m),{replace:r,state:n,relative:a}),[d,m,a,r,n]),null}function nCt(s){return VSt(s.context)}function ds(s){tu(!1)}function aCt(s){let{basename:t="/",children:r=null,location:n,navigationType:a=Lw.Pop,navigator:i,static:l=!1,future:o}=s;OI()&&tu(!1);let c=t.replace(/^\/*/,"/"),d=k.useMemo(()=>({basename:c,navigator:i,static:l,future:c8({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof n=="string"&&(n=RI(n));let{pathname:h="/",search:m="",hash:x="",state:y=null,key:v="default"}=n,w=k.useMemo(()=>{let b=_Ce(h,c);return b==null?null:{location:{pathname:b,search:m,hash:x,state:y,key:v},navigationType:a}},[c,h,m,x,y,v,a]);return w==null?null:k.createElement(Gj.Provider,{value:d},k.createElement($me.Provider,{children:r,value:w}))}function xde(s){let{children:t,location:r}=s;return HSt(Awe(t),r)}new Promise(()=>{});function Awe(s,t){t===void 0&&(t=[]);let r=[];return k.Children.forEach(s,(n,a)=>{if(!k.isValidElement(n))return;let i=[...t,a];if(n.type===k.Fragment){r.push.apply(r,Awe(n.props.children,i));return}n.type!==ds&&tu(!1),!n.props.index||!n.props.children||tu(!1);let l={id:n.props.id||i.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(l.children=Awe(n.props.children,i)),r.push(l)}),r}/** * 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 Mwe(){return Mwe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(r[a]=s[a]);return r}function oCt(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function lCt(s,t){return s.button===0&&(!t||t==="_self")&&!oCt(s)}function Iwe(s){return s===void 0&&(s=""),new URLSearchParams(typeof s=="string"||Array.isArray(s)||s instanceof URLSearchParams?s:Object.keys(s).reduce((t,r)=>{let n=s[r];return t.concat(Array.isArray(n)?n.map(a=>[r,a]):[[r,n]])},[]))}function cCt(s,t){let r=Iwe(s);return t&&t.forEach((n,a)=>{r.has(a)||t.getAll(a).forEach(i=>{r.append(a,i)})}),r}const dCt=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],uCt="6";try{window.__reactRouterVersion=uCt}catch{}const hCt="startTransition",EDe=dSe[hCt];function mCt(s){let{basename:t,children:r,future:n,window:a}=s,i=k.useRef();i.current==null&&(i.current=pSt({window:a,v5Compat:!0}));let l=i.current,[o,c]=k.useState({action:l.action,location:l.location}),{v7_startTransition:d}=n||{},h=k.useCallback(m=>{d&&EDe?EDe(()=>c(m)):c(m)},[c,d]);return k.useLayoutEffect(()=>l.listen(h),[l,h]),k.useEffect(()=>rCt(n),[n]),k.createElement(aCt,{basename:t,children:r,location:o.location,navigationType:o.action,navigator:l,future:n})}const fCt=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",pCt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Yn=k.forwardRef(function(t,r){let{onClick:n,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:h,viewTransition:m}=t,x=iCt(t,dCt),{basename:y}=k.useContext(Gj),v,w=!1;if(typeof d=="string"&&pCt.test(d)&&(v=d,fCt))try{let T=new URL(window.location.href),A=d.startsWith("//")?new URL(T.protocol+d):new URL(d),I=_Ce(A.pathname,y);A.origin===T.origin&&I!=null?d=I+A.search+A.hash:w=!0}catch{}let b=$St(d,{relative:a}),N=xCt(d,{replace:l,state:o,target:c,preventScrollReset:h,relative:a,viewTransition:m});function S(T){n&&n(T),T.defaultPrevented||N(T)}return k.createElement("a",Mwe({},x,{href:v||b,onClick:w||i?n:S,ref:r,target:c}))});var ADe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(ADe||(ADe={}));var MDe;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(MDe||(MDe={}));function xCt(s,t){let{target:r,replace:n,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=br(),d=ec(),h=bZe(s,{relative:l});return k.useCallback(m=>{if(lCt(m,r)){m.preventDefault();let x=n!==void 0?n:fde(d)===fde(h);c(s,{replace:x,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,h,n,a,r,s,i,l,o])}function Ac(s){let t=k.useRef(Iwe(s)),r=k.useRef(!1),n=ec(),a=k.useMemo(()=>cCt(n.search,r.current?null:t.current),[n.search]),i=br(),l=k.useCallback((o,c)=>{const d=Iwe(typeof o=="function"?o(a):o);r.current=!0,i("?"+d,c)},[i,a]);return[a,l]}var gCt=typeof Element<"u",yCt=typeof Map=="function",vCt=typeof Set=="function",bCt=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function Jle(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var r,n,a;if(Array.isArray(s)){if(r=s.length,r!=t.length)return!1;for(n=r;n--!==0;)if(!Jle(s[n],t[n]))return!1;return!0}var i;if(yCt&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!t.has(n.value[0]))return!1;for(i=s.entries();!(n=i.next()).done;)if(!Jle(n.value[1],t.get(n.value[0])))return!1;return!0}if(vCt&&s instanceof Set&&t instanceof Set){if(s.size!==t.size)return!1;for(i=s.entries();!(n=i.next()).done;)if(!t.has(n.value[0]))return!1;return!0}if(bCt&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(t)){if(r=s.length,r!=t.length)return!1;for(n=r;n--!==0;)if(s[n]!==t[n])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),r=a.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[n]))return!1;if(gCt&&s instanceof Element)return!1;for(n=r;n--!==0;)if(!((a[n]==="_owner"||a[n]==="__v"||a[n]==="__o")&&s.$$typeof)&&!Jle(s[a[n]],t[a[n]]))return!1;return!0}return s!==s&&t!==t}var _Ct=function(t,r){try{return Jle(t,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const wCt=Ao(_Ct);var jCt=function(s,t,r,n,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=[r,n,a,i,l,o],h=0;c=new Error(t.replace(/%s/g,function(){return d[h++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},NCt=jCt;const IDe=Ao(NCt);var kCt=function(t,r,n,a){var i=n?n.call(a,t,r):void 0;if(i!==void 0)return!!i;if(t===r)return!0;if(typeof t!="object"||!t||typeof r!="object"||!r)return!1;var l=Object.keys(t),o=Object.keys(r);if(l.length!==o.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(r),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))(jZe||{}),Y0e={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"]}},LDe=Object.values(jZe),kCe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},CCt=Object.entries(kCe).reduce((s,[t,r])=>(s[r]=t,s),{}),by="data-rh",IA={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},LA=(s,t)=>{for(let r=s.length-1;r>=0;r-=1){const n=s[r];if(Object.prototype.hasOwnProperty.call(n,t))return n[t]}return null},TCt=s=>{let t=LA(s,"title");const r=LA(s,IA.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),r&&t)return r.replace(/%s/g,()=>t);const n=LA(s,IA.DEFAULT_TITLE);return t||n||void 0},ECt=s=>LA(s,IA.ON_CHANGE_CLIENT_STATE)||(()=>{}),Z0e=(s,t)=>t.filter(r=>typeof r[s]<"u").map(r=>r[s]).reduce((r,n)=>({...r,...n}),{}),ACt=(s,t)=>t.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const a=Object.keys(n);for(let i=0;iconsole&&typeof console.warn=="function"&&console.warn(s),H6=(s,t,r)=>{const n={};return r.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&MCt(`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 h=Object.keys(c);for(let x=0;xa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let r=0;r({baseTag:ACt(["href"],s),bodyAttributes:Z0e("bodyAttributes",s),defer:LA(s,IA.DEFER),encode:LA(s,IA.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:Z0e("htmlAttributes",s),linkTags:H6("link",["rel","href"],s),metaTags:H6("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:H6("noscript",["innerHTML"],s),onChangeClientState:ECt(s),scriptTags:H6("script",["src","innerHTML"],s),styleTags:H6("style",["cssText"],s),title:TCt(s),titleAttributes:Z0e("titleAttributes",s),prioritizeSeoTags:ICt(s,IA.PRIORITIZE_SEO_TAGS)}),NZe=s=>Array.isArray(s)?s.join(""):s,PCt=(s,t)=>{const r=Object.keys(s);for(let n=0;nArray.isArray(s)?s.reduce((r,n)=>(PCt(n,t)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:s,priority:[]},PDe=(s,t)=>({...s,[t]:void 0}),DCt=["noscript","script","style"],Lwe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),kZe=s=>Object.keys(s).reduce((t,r)=>{const n=typeof s[r]<"u"?`${r}="${s[r]}"`:`${r}`;return t?`${t} ${n}`:n},""),RCt=(s,t,r,n)=>{const a=kZe(r),i=NZe(t);return a?`<${s} ${by}="true" ${a}>${Lwe(i,n)}`:`<${s} ${by}="true">${Lwe(i,n)}`},OCt=(s,t,r=!0)=>t.reduce((n,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,h)=>{const m=typeof i[h]>"u"?h:`${h}="${Lwe(i[h],r)}"`;return d?`${d} ${m}`:m},""),o=i.innerHTML||i.cssText||"",c=DCt.indexOf(s)===-1;return`${n}<${s} ${by}="true" ${l}${c?"/>":`>${o}`}`},""),SZe=(s,t={})=>Object.keys(s).reduce((r,n)=>{const a=kCe[n];return r[a||n]=s[n],r},t),FCt=(s,t,r)=>{const n={key:t,[by]:!0},a=SZe(r,n);return[wt.createElement("title",a,t)]},ece=(s,t)=>t.map((r,n)=>{const a={key:n,[by]:!0};return Object.keys(r).forEach(i=>{const o=kCe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=r.innerHTML||r.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=r[i]}),wt.createElement(s,a)}),zx=(s,t,r=!0)=>{switch(s){case"title":return{toComponent:()=>FCt(s,t.title,t.titleAttributes),toString:()=>RCt(s,t.title,t.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>SZe(t),toString:()=>kZe(t)};default:return{toComponent:()=>ece(s,t),toString:()=>OCt(s,t,r)}}},BCt=({metaTags:s,linkTags:t,scriptTags:r,encode:n})=>{const a=X0e(s,Y0e.meta),i=X0e(t,Y0e.link),l=X0e(r,Y0e.script);return{priorityMethods:{toComponent:()=>[...ece("meta",a.priority),...ece("link",i.priority),...ece("script",l.priority)],toString:()=>`${zx("meta",a.priority,n)} ${zx("link",i.priority,n)} ${zx("script",l.priority,n)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},zCt=s=>{const{baseTag:t,bodyAttributes:r,encode:n=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:h,metaTags:m,scriptTags:x}=s,y={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:y,linkTags:h,metaTags:m,scriptTags:x}=BCt(s)),{priority:y,base:zx("base",t,n),bodyAttributes:zx("bodyAttributes",r,n),htmlAttributes:zx("htmlAttributes",a,n),link:zx("link",h,n),meta:zx("meta",m,n),noscript:zx("noscript",i,n),script:zx("script",x,n),style:zx("style",l,n),title:zx("title",{title:o,titleAttributes:c},n)}},Pwe=zCt,P9=[],CZe=!!(typeof window<"u"&&window.document&&window.document.createElement),Dwe=class{constructor(s,t){Gn(this,"instances",[]);Gn(this,"canUseDOM",CZe);Gn(this,"context");Gn(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?P9:this.instances,add:s=>{(this.canUseDOM?P9:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?P9:this.instances).indexOf(s);(this.canUseDOM?P9:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=Pwe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},$Ct={},TZe=wt.createContext($Ct),k4,EZe=(k4=class extends k.Component{constructor(r){super(r);Gn(this,"helmetData");this.helmetData=new Dwe(this.props.context||{},k4.canUseDOM)}render(){return wt.createElement(TZe.Provider,{value:this.helmetData.value},this.props.children)}},Gn(k4,"canUseDOM",CZe),k4),zT=(s,t)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${s}[${by}]`),a=[].slice.call(n),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 h=d,m=typeof o[h]>"u"?"":o[h];c.setAttribute(d,m)}c.setAttribute(by,"true"),a.some((d,h)=>(l=h,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=>r.appendChild(o)),{oldTags:a,newTags:i}},Rwe=(s,t)=>{const r=document.getElementsByTagName(s)[0];if(!r)return;const n=r.getAttribute(by),a=n?n.split(","):[],i=[...a],l=Object.keys(t);for(const o of l){const c=t[o]||"";r.getAttribute(o)!==c&&r.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)r.removeAttribute(i[o]);a.length===i.length?r.removeAttribute(by):r.getAttribute(by)!==l.join(",")&&r.setAttribute(by,l.join(","))},UCt=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=NZe(s)),Rwe("title",t)},DDe=(s,t)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:h,title:m,titleAttributes:x}=s;Rwe("body",n),Rwe("html",a),UCt(m,x);const y={baseTag:zT("base",r),linkTags:zT("link",i),metaTags:zT("meta",l),noscriptTags:zT("noscript",o),scriptTags:zT("script",d),styleTags:zT("style",h)},v={},w={};Object.keys(y).forEach(b=>{const{newTags:N,oldTags:S}=y[b];N.length&&(v[b]=N),S.length&&(w[b]=y[b].oldTags)}),t&&t(),c(s,v,w)},G6=null,qCt=s=>{G6&&cancelAnimationFrame(G6),s.defer?G6=requestAnimationFrame(()=>{DDe(s,()=>{G6=null})}):(DDe(s),G6=null)},VCt=qCt,RDe=class extends k.Component{constructor(){super(...arguments);Gn(this,"rendered",!1)}shouldComponentUpdate(t){return!SCt(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:r}=this.props.context;let n=null;const a=LCt(t.get().map(i=>{const l={...i.props};return delete l.context,l}));EZe.canUseDOM?VCt(a):Pwe&&(n=Pwe(a)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},d_e,nl=(d_e=class extends k.Component{shouldComponentUpdate(s){return!wCt(PDe(this.props,"helmetData"),PDe(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,r,n){return{...t,[s.type]:[...t[s.type]||[],{...r,...this.mapNestedChildrenToProps(s,n)}]}}mapObjectTypeChildren(s,t,r,n){switch(s.type){case"title":return{...t,[s.type]:n,titleAttributes:{...r}};case"body":return{...t,bodyAttributes:{...r}};case"html":return{...t,htmlAttributes:{...r}};default:return{...t,[s.type]:{...r}}}}mapArrayTypeChildrenToProps(s,t){let r={...t};return Object.keys(s).forEach(n=>{r={...r,[n]:s[n]}}),r}warnOnInvalidChildren(s,t){return IDe(LDe.some(r=>s.type===r),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 ${LDe.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),IDe(!t||typeof t=="string"||Array.isArray(t)&&!t.some(r=>typeof r!="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 r={};return wt.Children.forEach(s,n=>{if(!n||!n.props)return;const{children:a,...i}=n.props,l=Object.keys(i).reduce((c,d)=>(c[CCt[d]||d]=i[d],c),{});let{type:o}=n;switch(typeof o=="symbol"?o=o.toString():this.warnOnInvalidChildren(n,a),o){case"Symbol(react.fragment)":t=this.mapChildrenToProps(a,t);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,l,a);break;default:t=this.mapObjectTypeChildren(n,t,l,a);break}}),this.mapArrayTypeChildrenToProps(r,t)}render(){const{children:s,...t}=this.props;let r={...t},{helmetData:n}=t;if(s&&(r=this.mapChildrenToProps(s,r)),n&&!(n instanceof Dwe)){const a=n;n=new Dwe(a.context,!0),delete r.helmetData}return n?wt.createElement(RDe,{...r,context:n.value}):wt.createElement(TZe.Consumer,null,a=>wt.createElement(RDe,{...r,context:a}))}},Gn(d_e,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),d_e);const HCt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>ti(async()=>{const{default:n}=await Promise.resolve().then(()=>FI);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)};class SCe extends Error{constructor(t,r="FunctionsError",n){super(t),this.name=r,this.context=n}}class GCt extends SCe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class WCt extends SCe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class KCt extends SCe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var Owe;(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"})(Owe||(Owe={}));var YCt=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class ZCt{constructor(t,{headers:r={},customFetch:n,region:a=Owe.Any}={}){this.url=t,this.headers=r,this.region=a,this.fetch=HCt(n)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,r={}){var n;return YCt(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=r;let o={},{region:c}=r;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 h=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(v=>{throw new GCt(v)}),m=h.headers.get("x-relay-error");if(m&&m==="true")throw new WCt(h);if(!h.ok)throw new KCt(h);let x=((n=h.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),y;return x==="application/json"?y=yield h.json():x==="application/octet-stream"?y=yield h.blob():x==="text/event-stream"?y=h:x==="multipart/form-data"?y=yield h.formData():y=yield h.text(),{data:y,error:null}}catch(a){return{data:null,error:a}}})}}var $f={},CCe={},Ume={},GF={},qme={},Vme={},XCt=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")},wM=XCt();const QCt=wM.fetch,AZe=wM.fetch.bind(wM),MZe=wM.Headers,JCt=wM.Request,e4t=wM.Response,FI=Object.freeze(Object.defineProperty({__proto__:null,Headers:MZe,Request:JCt,Response:e4t,default:AZe,fetch:QCt},Symbol.toStringTag,{value:"Module"})),t4t=Tbt(FI);var Hme={};Object.defineProperty(Hme,"__esModule",{value:!0});let s4t=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};Hme.default=s4t;var IZe=Zd&&Zd.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Vme,"__esModule",{value:!0});const r4t=IZe(t4t),n4t=IZe(Hme);let a4t=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=r4t.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,r){return this.headers=Object.assign({},this.headers),this.headers[t]=r,this}then(t,r){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 n=this.fetch;let a=n(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,h=null,m=null,x=i.status,y=i.statusText;if(i.ok){if(this.method!=="HEAD"){const N=await i.text();N===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?h=N:h=JSON.parse(N))}const w=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),b=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");w&&b&&b.length>1&&(m=parseInt(b[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(h)&&(h.length>1?(d={code:"PGRST116",details:`Results contain ${h.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},h=null,m=null,x=406,y="Not Acceptable"):h.length===1?h=h[0]:h=null)}else{const w=await i.text();try{d=JSON.parse(w),Array.isArray(d)&&i.status===404&&(h=[],d=null,x=200,y="OK")}catch{i.status===404&&w===""?(x=204,y="No Content"):d={message:w}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,x=200,y="OK"),d&&this.shouldThrowOnError)throw new n4t.default(d)}return{error:d,data:h,count:m,status:x,statusText:y}});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,r)}returns(){return this}overrideTypes(){return this}};Vme.default=a4t;var i4t=Zd&&Zd.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(qme,"__esModule",{value:!0});const o4t=i4t(Vme);let l4t=class extends o4t.default{select(t){let r=!1;const n=(t??"*").split("").map(a=>/\s/.test(a)&&!r?"":(a==='"'&&(r=!r),a)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:r=!0,nullsFirst:n,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}.${r?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:r,referencedTable:n=r}={}){const a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,r,{foreignTable:n,referencedTable:a=n}={}){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,`${r-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:r=!1,settings:n=!1,buffers:a=!1,wal:i=!1,format:l="text"}={}){var o;const c=[t?"analyze":null,r?"verbose":null,n?"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}};qme.default=l4t;var c4t=Zd&&Zd.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(GF,"__esModule",{value:!0});const d4t=c4t(qme);let u4t=class extends d4t.default{eq(t,r){return this.url.searchParams.append(t,`eq.${r}`),this}neq(t,r){return this.url.searchParams.append(t,`neq.${r}`),this}gt(t,r){return this.url.searchParams.append(t,`gt.${r}`),this}gte(t,r){return this.url.searchParams.append(t,`gte.${r}`),this}lt(t,r){return this.url.searchParams.append(t,`lt.${r}`),this}lte(t,r){return this.url.searchParams.append(t,`lte.${r}`),this}like(t,r){return this.url.searchParams.append(t,`like.${r}`),this}likeAllOf(t,r){return this.url.searchParams.append(t,`like(all).{${r.join(",")}}`),this}likeAnyOf(t,r){return this.url.searchParams.append(t,`like(any).{${r.join(",")}}`),this}ilike(t,r){return this.url.searchParams.append(t,`ilike.${r}`),this}ilikeAllOf(t,r){return this.url.searchParams.append(t,`ilike(all).{${r.join(",")}}`),this}ilikeAnyOf(t,r){return this.url.searchParams.append(t,`ilike(any).{${r.join(",")}}`),this}is(t,r){return this.url.searchParams.append(t,`is.${r}`),this}in(t,r){const n=Array.from(new Set(r)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${n})`),this}contains(t,r){return typeof r=="string"?this.url.searchParams.append(t,`cs.${r}`):Array.isArray(r)?this.url.searchParams.append(t,`cs.{${r.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(r)}`),this}containedBy(t,r){return typeof r=="string"?this.url.searchParams.append(t,`cd.${r}`):Array.isArray(r)?this.url.searchParams.append(t,`cd.{${r.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(r)}`),this}rangeGt(t,r){return this.url.searchParams.append(t,`sr.${r}`),this}rangeGte(t,r){return this.url.searchParams.append(t,`nxl.${r}`),this}rangeLt(t,r){return this.url.searchParams.append(t,`sl.${r}`),this}rangeLte(t,r){return this.url.searchParams.append(t,`nxr.${r}`),this}rangeAdjacent(t,r){return this.url.searchParams.append(t,`adj.${r}`),this}overlaps(t,r){return typeof r=="string"?this.url.searchParams.append(t,`ov.${r}`):this.url.searchParams.append(t,`ov.{${r.join(",")}}`),this}textSearch(t,r,{config:n,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const l=n===void 0?"":`(${n})`;return this.url.searchParams.append(t,`${i}fts${l}.${r}`),this}match(t){return Object.entries(t).forEach(([r,n])=>{this.url.searchParams.append(r,`eq.${n}`)}),this}not(t,r,n){return this.url.searchParams.append(t,`not.${r}.${n}`),this}or(t,{foreignTable:r,referencedTable:n=r}={}){const a=n?`${n}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,r,n){return this.url.searchParams.append(t,`${r}.${n}`),this}};GF.default=u4t;var h4t=Zd&&Zd.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Ume,"__esModule",{value:!0});const W6=h4t(GF);let m4t=class{constructor(t,{headers:r={},schema:n,fetch:a}){this.url=t,this.headers=r,this.schema=n,this.fetch=a}select(t,{head:r=!1,count:n}={}){const a=r?"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),n&&(this.headers.Prefer=`count=${n}`),new W6.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:r,defaultToNull:n=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),r&&i.push(`count=${r}`),n||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 W6.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:r,ignoreDuplicates:n=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),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,h)=>d.concat(Object.keys(h)),[]);if(c.length>0){const d=[...new Set(c)].map(h=>`"${h}"`);this.url.searchParams.set("columns",d.join(","))}}return new W6.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:r}={}){const n="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),this.headers.Prefer=a.join(","),new W6.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const r="DELETE",n=[];return t&&n.push(`count=${t}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new W6.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Ume.default=m4t;var Gme={},Wme={};Object.defineProperty(Wme,"__esModule",{value:!0});Wme.version=void 0;Wme.version="0.0.0-automated";Object.defineProperty(Gme,"__esModule",{value:!0});Gme.DEFAULT_HEADERS=void 0;const f4t=Wme;Gme.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${f4t.version}`};var LZe=Zd&&Zd.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(CCe,"__esModule",{value:!0});const p4t=LZe(Ume),x4t=LZe(GF),g4t=Gme;let y4t=class PZe{constructor(t,{headers:r={},schema:n,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},g4t.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=a}from(t){const r=new URL(`${this.url}/${t}`);return new p4t.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new PZe(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,r={},{head:n=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;n||a?(l=n?"HEAD":"GET",Object.entries(r).filter(([h,m])=>m!==void 0).map(([h,m])=>[h,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([h,m])=>{o.searchParams.append(h,m)})):(l="POST",c=r);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new x4t.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};CCe.default=y4t;var BI=Zd&&Zd.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($f,"__esModule",{value:!0});$f.PostgrestError=$f.PostgrestBuilder=$f.PostgrestTransformBuilder=$f.PostgrestFilterBuilder=$f.PostgrestQueryBuilder=$f.PostgrestClient=void 0;const DZe=BI(CCe);$f.PostgrestClient=DZe.default;const RZe=BI(Ume);$f.PostgrestQueryBuilder=RZe.default;const OZe=BI(GF);$f.PostgrestFilterBuilder=OZe.default;const FZe=BI(qme);$f.PostgrestTransformBuilder=FZe.default;const BZe=BI(Vme);$f.PostgrestBuilder=BZe.default;const zZe=BI(Hme);$f.PostgrestError=zZe.default;var v4t=$f.default={PostgrestClient:DZe.default,PostgrestQueryBuilder:RZe.default,PostgrestFilterBuilder:OZe.default,PostgrestTransformBuilder:FZe.default,PostgrestBuilder:BZe.default,PostgrestError:zZe.default};const{PostgrestClient:b4t,PostgrestQueryBuilder:pUs,PostgrestFilterBuilder:xUs,PostgrestTransformBuilder:gUs,PostgrestBuilder:yUs,PostgrestError:vUs}=v4t;let Fwe;typeof window>"u"?Fwe=require("ws"):Fwe=window.WebSocket;const _4t=Fwe,w4t="2.11.10",j4t={"X-Client-Info":`realtime-js/${w4t}`},N4t="1.0.0",$Ze=1e4,k4t=1e3;var PA;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(PA||(PA={}));var Xm;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Xm||(Xm={}));var cy;(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"})(cy||(cy={}));var Bwe;(function(s){s.websocket="websocket"})(Bwe||(Bwe={}));var WC;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(WC||(WC={}));class S4t{constructor(){this.HEADER_LENGTH=1}decode(t,r){return t.constructor===ArrayBuffer?r(this._binaryDecode(t)):r(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const r=new DataView(t),n=new TextDecoder;return this._decodeBroadcast(t,r,n)}_decodeBroadcast(t,r,n){const a=r.getUint8(1),i=r.getUint8(2);let l=this.HEADER_LENGTH+2;const o=n.decode(t.slice(l,l+a));l=l+a;const c=n.decode(t.slice(l,l+i));l=l+i;const d=JSON.parse(n.decode(t.slice(l,t.byteLength)));return{ref:null,topic:o,event:c,payload:d}}}class UZe{constructor(t,r){this.callback=t,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=r}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 ac;(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"})(ac||(ac={}));const ODe=(s,t,r={})=>{var n;const a=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(t).reduce((i,l)=>(i[l]=C4t(l,s,t,a),i),{})},C4t=(s,t,r,n)=>{const a=t.find(o=>o.name===s),i=a==null?void 0:a.type,l=r[s];return i&&!n.includes(i)?qZe(i,l):zwe(l)},qZe=(s,t)=>{if(s.charAt(0)==="_"){const r=s.slice(1,s.length);return M4t(t,r)}switch(s){case ac.bool:return T4t(t);case ac.float4:case ac.float8:case ac.int2:case ac.int4:case ac.int8:case ac.numeric:case ac.oid:return E4t(t);case ac.json:case ac.jsonb:return A4t(t);case ac.timestamp:return I4t(t);case ac.abstime:case ac.date:case ac.daterange:case ac.int4range:case ac.int8range:case ac.money:case ac.reltime:case ac.text:case ac.time:case ac.timestamptz:case ac.timetz:case ac.tsrange:case ac.tstzrange:return zwe(t);default:return zwe(t)}},zwe=s=>s,T4t=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},E4t=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},A4t=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},M4t=(s,t)=>{if(typeof s!="string")return s;const r=s.length-1,n=s[r];if(s[0]==="{"&&n==="}"){let i;const l=s.slice(1,r);try{i=JSON.parse("["+l+"]")}catch{i=l?l.split(","):[]}return i.map(o=>qZe(t,o))}return s},I4t=s=>typeof s=="string"?s.replace(" ","T"):s,VZe=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class Q0e{constructor(t,r,n={},a=$Ze){this.channel=t,this.event=r,this.payload=n,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,r){var n;return this._hasReceived(t)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:t,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:r})}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:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(r))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var FDe;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(FDe||(FDe={}));class JR{constructor(t,r){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=JR.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=JR.syncDiff(this.state,c,i,l)}),this.pendingDiffs=[],o()}),this.channel._on(n.diff,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=JR.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,r,n,a){const i=this.cloneDeep(t),l=this.transformState(r),o={},c={};return this.map(i,(d,h)=>{l[d]||(c[d]=h)}),this.map(l,(d,h)=>{const m=i[d];if(m){const x=h.map(b=>b.presence_ref),y=m.map(b=>b.presence_ref),v=h.filter(b=>y.indexOf(b.presence_ref)<0),w=m.filter(b=>x.indexOf(b.presence_ref)<0);v.length>0&&(o[d]=v),w.length>0&&(c[d]=w)}else o[d]=h}),this.syncDiff(i,{joins:o,leaves:c},n,a)}static syncDiff(t,r,n,a){const{joins:i,leaves:l}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const h=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),h.length>0){const m=t[o].map(y=>y.presence_ref),x=h.filter(y=>m.indexOf(y.presence_ref)<0);t[o].unshift(...x)}n(o,h,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const h=c.map(m=>m.presence_ref);d=d.filter(m=>h.indexOf(m.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,r){return Object.getOwnPropertyNames(t).map(n=>r(n,t[n]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((r,n)=>{const a=t[n];return"metas"in a?r[n]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=a,r},{})}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 BDe;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(BDe||(BDe={}));var zDe;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(zDe||(zDe={}));var z1;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(z1||(z1={}));class TCe{constructor(t,r={config:{}},n){this.topic=t,this.params=r,this.socket=n,this.bindings={},this.state=Xm.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},r.config),this.timeout=this.socket.timeout,this.joinPush=new Q0e(this,cy.join,this.params,this.timeout),this.rejoinTimer=new UZe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Xm.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=Xm.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Xm.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Xm.errored,this.rejoinTimer.scheduleTimeout())}),this._on(cy.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new JR(this),this.broadcastEndpointURL=VZe(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,r=this.timeout){var n,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(h=>t==null?void 0:t(z1.CHANNEL_ERROR,h)),this._onClose(()=>t==null?void 0:t(z1.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.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(r),this.joinPush.receive("ok",async({postgres_changes:h})=>{var m;if(this.socket.setAuth(),h===void 0){t==null||t(z1.SUBSCRIBED);return}else{const x=this.bindings.postgres_changes,y=(m=x==null?void 0:x.length)!==null&&m!==void 0?m:0,v=[];for(let w=0;w{this.state=Xm.errored,t==null||t(z1.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(z1.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,r={}){return await this.send({type:"presence",event:"track",payload:t},r.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,r,n){return this._on(t,r,n)}async send(t,r={}){var n,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,(n=r.timeout)!==null&&n!==void 0?n: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,r.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=Xm.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(cy.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const a=new Q0e(this,cy.leave,{},t);a.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("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,r,n){const a=new AbortController,i=setTimeout(()=>a.abort(),n),l=await this.socket.fetch(t,Object.assign(Object.assign({},r),{signal:a.signal}));return clearTimeout(i),l}_push(t,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new Q0e(this,t,r,n);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,r,n){return r}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,r,n){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:h}=cy;if(n&&[o,c,d,h].indexOf(l)>=0&&n!==this._joinRef())return;let x=this._onMessage(l,r,n);if(r&&!x)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(y=>{var v,w,b;return((v=y.filter)===null||v===void 0?void 0:v.event)==="*"||((b=(w=y.filter)===null||w===void 0?void 0:w.event)===null||b===void 0?void 0:b.toLocaleLowerCase())===l}).map(y=>y.callback(x,n)):(i=this.bindings[l])===null||i===void 0||i.filter(y=>{var v,w,b,N,S,T;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in y){const A=y.id,I=(v=y.filter)===null||v===void 0?void 0:v.event;return A&&((w=r.ids)===null||w===void 0?void 0:w.includes(A))&&(I==="*"||(I==null?void 0:I.toLocaleLowerCase())===((b=r.data)===null||b===void 0?void 0:b.type.toLocaleLowerCase()))}else{const A=(S=(N=y==null?void 0:y.filter)===null||N===void 0?void 0:N.event)===null||S===void 0?void 0:S.toLocaleLowerCase();return A==="*"||A===((T=r==null?void 0:r.event)===null||T===void 0?void 0:T.toLocaleLowerCase())}else return y.type.toLocaleLowerCase()===l}).map(y=>{if(typeof x=="object"&&"ids"in x){const v=x.data,{schema:w,table:b,commit_timestamp:N,type:S,errors:T}=v;x=Object.assign(Object.assign({},{schema:w,table:b,commit_timestamp:N,eventType:S,new:{},old:{},errors:T}),this._getPayloadRecords(v))}y.callback(x,n)})}_isClosed(){return this.state===Xm.closed}_isJoined(){return this.state===Xm.joined}_isJoining(){return this.state===Xm.joining}_isLeaving(){return this.state===Xm.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,r,n){const a=t.toLocaleLowerCase(),i={type:a,filter:r,callback:n};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,r){const n=t.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&TCe.isEqual(a.filter,r))}),this}static isEqual(t,r){if(Object.keys(t).length!==Object.keys(r).length)return!1;for(const n in t)if(t[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(cy.close,{},t)}_onError(t){this._on(cy.error,{},r=>t(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Xm.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const r={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(r.new=ODe(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(r.old=ODe(t.columns,t.old_record)),r}}const $De=()=>{},L4t=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class P4t{constructor(t,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=j4t,this.params={},this.timeout=$Ze,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=$De,this.ref=0,this.logger=$De,this.conn=null,this.sendBuffer=[],this.serializer=new S4t,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>ti(async()=>{const{default:c}=await Promise.resolve().then(()=>FI);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${Bwe.websocket}`,this.httpEndpoint=VZe(t),r!=null&&r.transport?this.transport=r.transport:this.transport=null,r!=null&&r.params&&(this.params=r.params),r!=null&&r.headers&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),r!=null&&r.timeout&&(this.timeout=r.timeout),r!=null&&r.logger&&(this.logger=r.logger),(r!=null&&r.logLevel||r!=null&&r.log_level)&&(this.logLevel=r.logLevel||r.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),r!=null&&r.heartbeatIntervalMs&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const a=(n=r==null?void 0:r.params)===null||n===void 0?void 0:n.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=r!=null&&r.reconnectAfterMs?r.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(i,l)=>l(JSON.stringify(i)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new UZe(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(r==null?void 0:r.fetch),r!=null&&r.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(r==null?void 0:r.worker)||!1,this.workerUrl=r==null?void 0:r.workerUrl}this.accessToken=(r==null?void 0:r.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=_4t),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 D4t(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:N4t}))}disconnect(t,r){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,r??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(t){const r=await t.unsubscribe();return this.channels=this.channels.filter(n=>n._joinRef!==t._joinRef),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const t=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,r,n){this.logger(t,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case PA.connecting:return WC.Connecting;case PA.open:return WC.Open;case PA.closing:return WC.Closing;default:return WC.Closed}}isConnected(){return this.connectionState()===WC.Open}channel(t,r={config:{}}){const n=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===n);if(a)return a;{const i=new TCe(`realtime:${t}`,r,this);return this.channels.push(i),i}}push(t){const{topic:r,event:n,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",`${r} ${n} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let r=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{r&&n.updateJoinPayload({access_token:r,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(cy.access_token,{access_token:r})}))}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(k4t,"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 r=this.channels.find(n=>n.topic===t&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${t}"`),r.unsubscribe())}_remove(t){this.channels=this.channels.filter(r=>r.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,r=>{let{topic:n,event:a,payload:i,ref:l}=r;n==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(r.payload.status=="ok"?"ok":"error"),l&&l===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${a} ${l&&"("+l+")"||""}`,i),Array.from(this.channels).filter(o=>o._isMember(n)).forEach(o=>o._trigger(a,i,l)),this.stateChangeCallbacks.message.forEach(o=>o(r))})}_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=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.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(r=>r(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(r=>r(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(cy.error))}_appendParams(t,r){if(Object.keys(r).length===0)return t;const n=t.match(/\?/)?"&":"?",a=new URLSearchParams(r);return`${t}${n}${a}`}_workerObjectUrl(t){let r;if(t)r=t;else{const n=new Blob([L4t],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class D4t{constructor(t,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=PA.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=n.close}}class ECe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function uh(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class R4t extends ECe{constructor(t,r){super(t),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class $we extends ECe{constructor(t,r){super(t),this.name="StorageUnknownError",this.originalError=r}}var O4t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const HZe=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>ti(async()=>{const{default:n}=await Promise.resolve().then(()=>FI);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},F4t=()=>O4t(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ti(()=>Promise.resolve().then(()=>FI),void 0)).Response:Response}),Uwe=s=>{if(Array.isArray(s))return s.map(r=>Uwe(r));if(typeof s=="function"||s!==Object(s))return s;const t={};return Object.entries(s).forEach(([r,n])=>{const a=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=Uwe(n)}),t};var n5=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const J0e=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),B4t=(s,t,r)=>n5(void 0,void 0,void 0,function*(){const n=yield F4t();s instanceof n&&!(r!=null&&r.noResolveJson)?s.json().then(a=>{t(new R4t(J0e(a),s.status||500))}).catch(a=>{t(new $we(J0e(a),a))}):t(new $we(J0e(s),s))}),z4t=(s,t,r,n)=>{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),n&&(a.body=JSON.stringify(n)),Object.assign(Object.assign({},a),r))};function WF(s,t,r,n,a,i){return n5(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(r,z4t(t,n,a,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>l(c)).catch(c=>B4t(c,o,n))})})}function gde(s,t,r,n){return n5(this,void 0,void 0,function*(){return WF(s,"GET",t,r,n)})}function tw(s,t,r,n,a){return n5(this,void 0,void 0,function*(){return WF(s,"POST",t,n,a,r)})}function $4t(s,t,r,n,a){return n5(this,void 0,void 0,function*(){return WF(s,"PUT",t,n,a,r)})}function U4t(s,t,r,n){return n5(this,void 0,void 0,function*(){return WF(s,"HEAD",t,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function GZe(s,t,r,n,a){return n5(this,void 0,void 0,function*(){return WF(s,"DELETE",t,n,a,r)})}var If=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const q4t={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},UDe={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class V4t{constructor(t,r={},n,a){this.url=t,this.headers=r,this.bucketId=n,this.fetch=HZe(a)}uploadOrUpdate(t,r,n,a){return If(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},UDe),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,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(r),h=this._getFinalPath(d),m=yield this.fetch(`${this.url}/object/${h}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),x=yield m.json();return m.ok?{data:{path:d,id:x.Id,fullPath:x.Key},error:null}:{data:null,error:x}}catch(i){if(uh(i))return{data:null,error:i};throw i}})}upload(t,r,n){return If(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,r,n)})}uploadToSignedUrl(t,r,n,a){return If(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",r);try{let c;const d=Object.assign({upsert:UDe.upsert},a),h=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",n)):typeof FormData<"u"&&n instanceof FormData?(c=n,c.append("cacheControl",d.cacheControl)):(c=n,h["cache-control"]=`max-age=${d.cacheControl}`,h["content-type"]=d.contentType);const m=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:h}),x=yield m.json();return m.ok?{data:{path:i,fullPath:x.Key},error:null}:{data:null,error:x}}catch(c){if(uh(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,r){return If(this,void 0,void 0,function*(){try{let n=this._getFinalPath(t);const a=Object.assign({},this.headers);r!=null&&r.upsert&&(a["x-upsert"]="true");const i=yield tw(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new ECe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(n){if(uh(n))return{data:null,error:n};throw n}})}update(t,r,n){return If(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,r,n)})}move(t,r,n){return If(this,void 0,void 0,function*(){try{return{data:yield tw(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(uh(a))return{data:null,error:a};throw a}})}copy(t,r,n){return If(this,void 0,void 0,function*(){try{return{data:{path:(yield tw(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(uh(a))return{data:null,error:a};throw a}})}createSignedUrl(t,r,n){return If(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield tw(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const l=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(uh(a))return{data:null,error:a};throw a}})}createSignedUrls(t,r,n){return If(this,void 0,void 0,function*(){try{const a=yield tw(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:t},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.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(uh(a))return{data:null,error:a};throw a}})}download(t,r){return If(this,void 0,void 0,function*(){const a=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),l=i?`?${i}`:"";try{const o=this._getFinalPath(t);return{data:yield(yield gde(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(uh(o))return{data:null,error:o};throw o}})}info(t){return If(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{const n=yield gde(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:Uwe(n),error:null}}catch(n){if(uh(n))return{data:null,error:n};throw n}})}exists(t){return If(this,void 0,void 0,function*(){const r=this._getFinalPath(t);try{return yield U4t(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(uh(n)&&n instanceof $we){const a=n.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:n}}throw n}})}getPublicUrl(t,r){const n=this._getFinalPath(t),a=[],i=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";i!==""&&a.push(i);const o=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});c!==""&&a.push(c);let d=a.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${n}${d}`)}}}remove(t){return If(this,void 0,void 0,function*(){try{return{data:yield GZe(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(r){if(uh(r))return{data:null,error:r};throw r}})}list(t,r,n){return If(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},q4t),r),{prefix:t||""});return{data:yield tw(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},n),error:null}}catch(a){if(uh(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 r=[];return t.width&&r.push(`width=${t.width}`),t.height&&r.push(`height=${t.height}`),t.resize&&r.push(`resize=${t.resize}`),t.format&&r.push(`format=${t.format}`),t.quality&&r.push(`quality=${t.quality}`),r.join("&")}}const H4t="2.7.1",G4t={"X-Client-Info":`storage-js/${H4t}`};var $T=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class W4t{constructor(t,r={},n){this.url=t,this.headers=Object.assign(Object.assign({},G4t),r),this.fetch=HZe(n)}listBuckets(){return $T(this,void 0,void 0,function*(){try{return{data:yield gde(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(uh(t))return{data:null,error:t};throw t}})}getBucket(t){return $T(this,void 0,void 0,function*(){try{return{data:yield gde(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(r){if(uh(r))return{data:null,error:r};throw r}})}createBucket(t,r={public:!1}){return $T(this,void 0,void 0,function*(){try{return{data:yield tw(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(uh(n))return{data:null,error:n};throw n}})}updateBucket(t,r){return $T(this,void 0,void 0,function*(){try{return{data:yield $4t(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(uh(n))return{data:null,error:n};throw n}})}emptyBucket(t){return $T(this,void 0,void 0,function*(){try{return{data:yield tw(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(uh(r))return{data:null,error:r};throw r}})}deleteBucket(t){return $T(this,void 0,void 0,function*(){try{return{data:yield GZe(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(r){if(uh(r))return{data:null,error:r};throw r}})}}class K4t extends W4t{constructor(t,r={},n){super(t,r,n)}from(t){return new V4t(this.url,this.headers,t,this.fetch)}}const Y4t="2.49.10";let ED="";typeof Deno<"u"?ED="deno":typeof document<"u"?ED="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ED="react-native":ED="node";const Z4t={"X-Client-Info":`supabase-js-${ED}/${Y4t}`},X4t={headers:Z4t},Q4t={schema:"public"},J4t={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},e3t={};var t3t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};const s3t=s=>{let t;return s?t=s:typeof fetch>"u"?t=AZe:t=fetch,(...r)=>t(...r)},r3t=()=>typeof Headers>"u"?MZe:Headers,n3t=(s,t,r)=>{const n=s3t(r),a=r3t();return(i,l)=>t3t(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}`),n(i,Object.assign(Object.assign({},l),{headers:d}))})};var a3t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};function i3t(s){return s.endsWith("/")?s:s+"/"}function o3t(s,t){var r,n;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:h,global:m}=t,x={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},h),l),global:Object.assign(Object.assign(Object.assign({},m),o),{headers:Object.assign(Object.assign({},(r=m==null?void 0:m.headers)!==null&&r!==void 0?r:{}),(n=o==null?void 0:o.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>a3t(this,void 0,void 0,function*(){return""})};return s.accessToken?x.accessToken=s.accessToken:delete x.accessToken,x}const WZe="2.69.1",yE=30*1e3,qwe=3,eve=qwe*yE,l3t="http://localhost:9999",c3t="supabase.auth.token",d3t={"X-Client-Info":`gotrue-js/${WZe}`},Vwe="X-Supabase-Api-Version",KZe={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},u3t=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,h3t=6e5;class ACe extends Error{constructor(t,r,n){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Hi(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class m3t extends ACe{constructor(t,r,n){super(t,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function f3t(s){return Hi(s)&&s.name==="AuthApiError"}class YZe extends ACe{constructor(t,r){super(t),this.name="AuthUnknownError",this.originalError=r}}class Wj extends ACe{constructor(t,r,n,a){super(t,n,a),this.name=r,this.status=n}}class G_ extends Wj{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function p3t(s){return Hi(s)&&s.name==="AuthSessionMissingError"}class tve extends Wj{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class D9 extends Wj{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class R9 extends Wj{constructor(t,r=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function x3t(s){return Hi(s)&&s.name==="AuthImplicitGrantRedirectError"}class qDe extends Wj{constructor(t,r=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Hwe extends Wj{constructor(t,r){super(t,"AuthRetryableFetchError",r,void 0)}}function sve(s){return Hi(s)&&s.name==="AuthRetryableFetchError"}class VDe extends Wj{constructor(t,r,n){super(t,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class eO extends Wj{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const HDe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),GDe=` \r=`.split(""),g3t=(()=>{const s=new Array(128);for(let t=0;t-1)for(t.queue=t.queue<<6|n,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function WDe(s){const t=[],r=l=>{t.push(String.fromCodePoint(l))},n={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{b3t(l,n,r)};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 v3t(s,t){for(let r=0;r55295&&n<=56319){const a=(n-55296)*1024&65535;n=(s.charCodeAt(r+1)-56320&65535|a)+65536,r+=1}y3t(n,t)}}function b3t(s,t,r){if(t.utf8seq===0){if(s<=127){r(s);return}for(let n=1;n<6;n+=1)if(!(s>>7-n&1)){t.utf8seq=n;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&&r(t.codepoint)}}function _3t(s){const t=[],r={queue:0,queuedBits:0},n=a=>{t.push(a)};for(let a=0;at.push(r)),new Uint8Array(t)}function j3t(s){return Math.round(Date.now()/1e3)+s}function N3t(){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 N0=()=>typeof window<"u"&&typeof document<"u",vN={tested:!1,writable:!1},tO=()=>{if(!N0())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(vN.tested)return vN.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),vN.tested=!0,vN.writable=!0}catch{vN.tested=!0,vN.writable=!1}return vN.writable};function k3t(s){const t={},r=new URL(s);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return r.searchParams.forEach((n,a)=>{t[a]=n}),t}const XZe=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...r)=>ti(async()=>{const{default:n}=await Promise.resolve().then(()=>FI);return{default:n}},void 0).then(({default:n})=>n(...r)):t=fetch,(...r)=>t(...r)},S3t=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",QZe=async(s,t,r)=>{await s.setItem(t,JSON.stringify(r))},O9=async(s,t)=>{const r=await s.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return r}},F9=async(s,t)=>{await s.removeItem(t)};class Kme{constructor(){this.promise=new Kme.promiseConstructor((t,r)=>{this.resolve=t,this.reject=r})}}Kme.promiseConstructor=Promise;function rve(s){const t=s.split(".");if(t.length!==3)throw new eO("Invalid JWT structure");for(let n=0;n{setTimeout(()=>t(null),s)})}function T3t(s,t){return new Promise((n,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const l=await s(i);if(!t(i,null,l)){n(l);return}}catch(l){if(!t(i,l)){a(l);return}}})()})}function E3t(s){return("0"+s.toString(16)).substr(-2)}function A3t(){const t=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let a="";for(let i=0;i<56;i++)a+=r.charAt(Math.floor(Math.random()*n));return a}return crypto.getRandomValues(t),Array.from(t,E3t).join("")}async function M3t(s){const r=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",r),a=new Uint8Array(n);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function I3t(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 r=await M3t(s);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function UT(s,t,r=!1){const n=A3t();let a=n;r&&(a+="/PASSWORD_RECOVERY"),await QZe(s,`${t}-code-verifier`,a);const i=await I3t(n);return[i,n===i?"plain":"s256"]}const L3t=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function P3t(s){const t=s.headers.get(Vwe);if(!t||!t.match(L3t))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function D3t(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 R3t(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 O3t=function(s,t){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),F3t=[502,503,504];async function KDe(s){var t;if(!S3t(s))throw new Hwe(BC(s),0);if(F3t.includes(s.status))throw new Hwe(BC(s),s.status);let r;try{r=await s.json()}catch(i){throw new YZe(BC(i),i)}let n;const a=P3t(s);if(a&&a.getTime()>=KZe["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new VDe(BC(r),s.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(n==="session_not_found")throw new G_}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,l)=>i&&typeof l=="string",!0))throw new VDe(BC(r),s.status,r.weak_password.reasons);throw new m3t(BC(r),s.status||500,n)}const B3t=(s,t,r,n)=>{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(n),Object.assign(Object.assign({},a),r))};async function vo(s,t,r,n){var a;const i=Object.assign({},n==null?void 0:n.headers);i[Vwe]||(i[Vwe]=KZe["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);const l=(a=n==null?void 0:n.query)!==null&&a!==void 0?a:{};n!=null&&n.redirectTo&&(l.redirect_to=n.redirectTo);const o=Object.keys(l).length?"?"+new URLSearchParams(l).toString():"",c=await z3t(s,t,r+o,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function z3t(s,t,r,n,a,i){const l=B3t(t,n,a,i);let o;try{o=await s(r,Object.assign({},l))}catch(c){throw console.error(c),new Hwe(BC(c),0)}if(o.ok||await KDe(o),n!=null&&n.noResolveJson)return o;try{return await o.json()}catch(c){await KDe(c)}}function W_(s){var t;let r=null;V3t(s)&&(r=Object.assign({},s),s.expires_at||(r.expires_at=j3t(s.expires_in)));const n=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:r,user:n},error:null}}function YDe(s){const t=W_(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((r,n)=>r&&typeof n=="string",!0)&&(t.data.weak_password=s.weak_password),t}function pw(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function $3t(s){return{data:s,error:null}}function U3t(s){const{action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i}=s,l=O3t(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:r,hashed_token:n,redirect_to:a,verification_type:i},c=Object.assign({},l);return{data:{properties:o,user:c},error:null}}function q3t(s){return s}function V3t(s){return s.access_token&&s.refresh_token&&s.expires_in}var H3t=function(s,t){var r={};for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(s);a0&&(y.forEach(v=>{const w=parseInt(v.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(v.split(";")[1].split("=")[1]);d[`${b}Page`]=w}),d.total=parseInt(x)),{data:Object.assign(Object.assign({},m),d),error:null}}catch(d){if(Hi(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await vo(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:pw})}catch(r){if(Hi(r))return{data:{user:null},error:r};throw r}}async updateUserById(t,r){try{return await vo(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:r,headers:this.headers,xform:pw})}catch(n){if(Hi(n))return{data:{user:null},error:n};throw n}}async deleteUser(t,r=!1){try{return await vo(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:r},xform:pw})}catch(n){if(Hi(n))return{data:{user:null},error:n};throw n}}async _listFactors(t){try{const{data:r,error:n}=await vo(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:r,error:n}}catch(r){if(Hi(r))return{data:null,error:r};throw r}}async _deleteFactor(t){try{return{data:await vo(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(r){if(Hi(r))return{data:null,error:r};throw r}}}const W3t={getItem:s=>tO()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{tO()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{tO()&&globalThis.localStorage.removeItem(s)}};function ZDe(s={}){return{getItem:t=>s[t]||null,setItem:(t,r)=>{s[t]=r},removeItem:t=>{delete s[t]}}}function K3t(){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 qT={debug:!!(globalThis&&tO()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class JZe extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class Y3t extends JZe{}async function Z3t(s,t,r){qT.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),qT.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:n.signal},async a=>{if(a){qT.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await r()}finally{qT.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw qT.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Y3t(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(qT.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 r()}}))}K3t();const X3t={url:l3t,storageKey:c3t,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:d3t,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function XDe(s,t,r){return await r()}class d8{constructor(t){var r,n;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=d8.nextInstanceID,d8.nextInstanceID+=1,this.instanceID>0&&N0()&&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({},X3t),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 G3t({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=XZe(a.fetch),this.lock=a.lock||XDe,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:N0()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Z3t:this.lock=XDe,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:tO()?this.storage=W3t:(this.memoryStorage={},this.storage=ZDe(this.memoryStorage)):(this.memoryStorage={},this.storage=ZDe(this.memoryStorage)),N0()&&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)}(n=this.broadcastChannel)===null||n===void 0||n.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} (${WZe}) ${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 r=k3t(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),N0()&&this.detectSessionInUrl&&n!=="none"){const{data:a,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),x3t(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(r){return Hi(r)?{error:r}:{error:new YZe("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var r,n,a;try{const i=await vo(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=t==null?void 0:t.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:W_}),{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(Hi(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var r,n,a;try{let i;if("email"in t){const{email:h,password:m,options:x}=t;let y=null,v=null;this.flowType==="pkce"&&([y,v]=await UT(this.storage,this.storageKey)),i=await vo(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:x==null?void 0:x.emailRedirectTo,body:{email:h,password:m,data:(r=x==null?void 0:x.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:x==null?void 0:x.captchaToken},code_challenge:y,code_challenge_method:v},xform:W_})}else if("phone"in t){const{phone:h,password:m,options:x}=t;i=await vo(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=x==null?void 0:x.data)!==null&&n!==void 0?n:{},channel:(a=x==null?void 0:x.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:x==null?void 0:x.captchaToken}},xform:W_})}else throw new D9("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(Hi(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let r;if("email"in t){const{email:i,password:l,options:o}=t;r=await vo(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:YDe})}else if("phone"in t){const{phone:i,password:l,options:o}=t;r=await vo(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:YDe})}else throw new D9("You must provide either an email or phone number and a password");const{data:n,error:a}=r;return a?{data:{user:null,session:null},error:a}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new tve}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:a})}catch(r){if(Hi(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(t){var r,n,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(r=t.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=t.options)===null||n===void 0?void 0:n.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 r=await O9(this.storage,`${this.storageKey}-code-verifier`),[n,a]=(r??"").split("/");try{const{data:i,error:l}=await vo(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:n},xform:W_});if(await F9(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new tve}:(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(Hi(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:r,provider:n,token:a,access_token:i,nonce:l}=t,o=await vo(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:a,access_token:i,nonce:l,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:W_}),{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 tve}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(r){if(Hi(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(t){var r,n,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,h=null;this.flowType==="pkce"&&([d,h]=await UT(this.storage,this.storageKey));const{error:m}=await vo(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=c==null?void 0:c.data)!==null&&r!==void 0?r:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:h}=await vo(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:h}}throw new D9("You must provide either an email or phone number.")}catch(o){if(Hi(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(t){var r,n;try{let a,i;"options"in t&&(a=(r=t.options)===null||r===void 0?void 0:r.redirectTo,i=(n=t.options)===null||n===void 0?void 0:n.captchaToken);const{data:l,error:o}=await vo(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:W_});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(Hi(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(t){var r,n,a;try{let i=null,l=null;return this.flowType==="pkce"&&([i,l]=await UT(this.storage,this.storageKey)),await vo(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:(n=(r=t.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n: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:$3t})}catch(i){if(Hi(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:r},error:n}=t;if(n)throw n;if(!r)throw new G_;const{error:a}=await vo(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Hi(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const r=`${this.url}/resend`;if("email"in t){const{email:n,type:a,options:i}=t,{error:l}=await vo(this.fetch,"POST",r,{headers:this.headers,body:{email:n,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:n,type:a,options:i}=t,{data:l,error:o}=await vo(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,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 D9("You must provide either an email or phone number and a type")}catch(r){if(Hi(r))return{data:{user:null,session:null},error:r};throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(t,r){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await n,await r()))();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 n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await n}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 r=await this.__loadSession();return await t(r)}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 r=await O9(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const n=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,h))})}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 vo(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:pw}):await this._useSession(async r=>{var n,a,i;const{data:l,error:o}=r;if(o)throw o;return!(!((n=l.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new G_}:await vo(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:pw})})}catch(r){if(Hi(r))return p3t(r)&&(await this._removeSession(),await F9(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(t,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,r))}async _updateUser(t,r={}){try{return await this._useSession(async n=>{const{data:a,error:i}=n;if(i)throw i;if(!a.session)throw new G_;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await UT(this.storage,this.storageKey));const{data:d,error:h}=await vo(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:c}),jwt:l.access_token,xform:pw});if(h)throw h;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),{data:{user:l.user},error:null}})}catch(n){if(Hi(n))return{data:{user:null},error:n};throw n}}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 G_;const r=Date.now()/1e3;let n=r,a=!0,i=null;const{payload:l}=rve(t.access_token);if(l.exp&&(n=l.exp,a=n<=r),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:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(r){if(Hi(r))return{data:{session:null,user:null},error:r};throw r}}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 r=>{var n;if(!t){const{data:l,error:o}=r;if(o)throw o;t=(n=l.session)!==null&&n!==void 0?n:void 0}if(!(t!=null&&t.refresh_token))throw new G_;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(r){if(Hi(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(t,r){try{if(!N0())throw new R9("No browser detected.");if(t.error||t.error_description||t.error_code)throw new R9(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new qDe("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new R9("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new qDe("No code detected.");const{data:S,error:T}=await this._exchangeCodeForSession(t.code);if(T)throw T;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:S.session,redirectType:null},error:null}}const{provider_token:n,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 R9("No session defined in URL");const h=Math.round(Date.now()/1e3),m=parseInt(o);let x=h+m;c&&(x=parseInt(c));const y=x-h;y*1e3<=yE&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${y}s, should have been closer to ${m}s`);const v=x-m;h-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,x,h):h-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,x,h);const{data:w,error:b}=await this._getUser(i);if(b)throw b;const N={provider_token:n,provider_refresh_token:a,access_token:i,expires_in:m,expires_at:x,refresh_token:l,token_type:d,user:w.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:t.type},error:null}}catch(n){if(Hi(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const r=await O9(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&r)}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 r=>{var n;const{data:a,error:i}=r;if(i)return{error:i};const l=(n=a.session)===null||n===void 0?void 0:n.access_token;if(l){const{error:o}=await this.admin.signOut(l,t);if(o&&!(f3t(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await F9(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const r=N3t(),n={id:r,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(t){return await this._useSession(async r=>{var n,a;try{const{data:{session:i},error:l}=r;if(l)throw l;await((n=this.stateChangeEmitters.get(t))===null||n===void 0?void 0:n.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,r={}){let n=null,a=null;this.flowType==="pkce"&&([n,a]=await UT(this.storage,this.storageKey,!0));try{return await vo(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:n,code_challenge_method:a,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(Hi(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(t=r.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(r){if(Hi(r))return{data:null,error:r};throw r}}async linkIdentity(t){var r;try{const{data:n,error:a}=await this._useSession(async i=>{var l,o,c,d,h;const{data:m,error:x}=i;if(x)throw x;const y=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 vo(this.fetch,"GET",y,{headers:this.headers,jwt:(h=(d=m.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(a)throw a;return N0()&&!(!((r=t.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:t.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(Hi(n))return{data:{provider:t.provider,url:null},error:n};throw n}}async unlinkIdentity(t){try{return await this._useSession(async r=>{var n,a;const{data:i,error:l}=r;if(l)throw l;return await vo(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0})})}catch(r){if(Hi(r))return{data:null,error:r};throw r}}async _refreshAccessToken(t){const r=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await T3t(async a=>(a>0&&await C3t(200*Math.pow(2,a-1)),this._debug(r,"refreshing attempt",a),await vo(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:W_})),(a,i)=>{const l=200*Math.pow(2,a);return i&&sve(i)&&Date.now()+l-n{try{await o.callback(t,r)}catch(c){i.push(c)}});if(await Promise.all(l),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),yE);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 r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((n.expires_at*1e3-t)/yE);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${yE}ms, refresh threshold is ${qwe} ticks`),a<=qwe&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof JZe)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!N0()||!(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 r=`#_onVisibilityChanged(${t})`;this._debug(r,"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(r,"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,r,n){const a=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&a.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&a.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[i,l]=await UT(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(l)}`});a.push(o.toString())}if(n!=null&&n.queryParams){const i=new URLSearchParams(n.queryParams);a.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&a.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await vo(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Hi(r))return{data:null,error:r};throw r}}async _enroll(t){try{return await this._useSession(async r=>{var n,a;const{data:i,error:l}=r;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 vo(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.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(r){if(Hi(r))return{data:null,error:r};throw r}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;if(i)return{data:null,error:i};const{data:l,error:o}=await vo(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.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(r){if(Hi(r))return{data:null,error:r};throw r}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:a,error:i}=r;return i?{data:null,error:i}:await vo(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(Hi(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(t){const{data:r,error:n}=await this._challenge({factorId:t.factorId});return n?{data:null,error:n}:await this._verify({factorId:t.factorId,challengeId:r.id,code:t.code})}async _listFactors(){const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const n=(t==null?void 0:t.factors)||[],a=n.filter(l=>l.factor_type==="totp"&&l.status==="verified"),i=n.filter(l=>l.factor_type==="phone"&&l.status==="verified");return{data:{all:n,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var r,n;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}=rve(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((n=(r=a.user.factors)===null||r===void 0?void 0:r.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");const h=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:h},error:null}}))}async fetchJwk(t,r={keys:[]}){let n=r.keys.find(l=>l.kid===t);if(n||(n=this.jwks.keys.find(l=>l.kid===t),n&&this.jwks_cached_at+h3t>Date.now()))return n;const{data:a,error:i}=await vo(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 eO("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),n=a.keys.find(l=>l.kid===t),!n)throw new eO("No matching signing key found in JWKS");return n}async getClaims(t,r={keys:[]}){try{let n=t;if(!n){const{data:y,error:v}=await this.getSession();if(v||!y.session)return{data:null,error:v};n=y.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=rve(n);if(D3t(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:y}=await this.getUser(n);if(y)throw y;return{data:{claims:i,header:a,signature:l},error:null}}const d=R3t(a.alg),h=await this.fetchJwk(a.kid,r),m=await crypto.subtle.importKey("jwk",h,d,!0,["verify"]);if(!await crypto.subtle.verify(d,m,l,w3t(`${o}.${c}`)))throw new eO("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(n){if(Hi(n))return{data:null,error:n};throw n}}}d8.nextInstanceID=0;const Q3t=d8;class J3t extends Q3t{constructor(t){super(t)}}var e5t=function(s,t,r,n){function a(i){return i instanceof r?i:new r(function(l){l(i)})}return new(r||(r=Promise))(function(i,l){function o(h){try{d(n.next(h))}catch(m){l(m)}}function c(h){try{d(n.throw(h))}catch(m){l(m)}}function d(h){h.done?i(h.value):a(h.value).then(o,c)}d((n=n.apply(s,t||[])).next())})};class t5t{constructor(t,r,n){var a,i,l;if(this.supabaseUrl=t,this.supabaseKey=r,!t)throw new Error("supabaseUrl is required.");if(!r)throw new Error("supabaseKey is required.");const o=i3t(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`,h={db:Q4t,realtime:e3t,auth:Object.assign(Object.assign({},J4t),{storageKey:d}),global:X4t},m=o3t(n??{},h);this.storageKey=(a=m.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=m.global.headers)!==null&&i!==void 0?i:{},m.accessToken?(this.accessToken=m.accessToken,this.auth=new Proxy({},{get:(x,y)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(y)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=m.auth)!==null&&l!==void 0?l:{},this.headers,m.global.fetch),this.fetch=n3t(r,this._getAccessToken.bind(this),m.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},m.realtime)),this.rest=new b4t(new URL("rest/v1",c).href,{headers:this.headers,schema:m.db.schema,fetch:this.fetch}),m.accessToken||this._listenForAuthEvents()}get functions(){return new ZCt(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new K4t(this.storageUrl.href,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,r={},n={}){return this.rest.rpc(t,r,n)}channel(t,r={config:{}}){return this.realtime.channel(t,r)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,r;return e5t(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(t=n.session)===null||t===void 0?void 0:t.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,h){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new J3t({url:this.authUrl.href,headers:Object.assign(Object.assign({},m),d),storageKey:i,autoRefreshToken:t,persistSession:r,detectSessionInUrl:n,storage:a,flowType:l,lock:o,debug:c,fetch:h,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new P4t(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((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(t,r,n){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:t==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const s5t=(s,t,r)=>new t5t(s,t,r),r5t="https://relzejiswnotikjgvjhz.supabase.co",n5t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",V=s5t(r5t,n5t,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),eXe=k.createContext(void 0),a5t=({children:s})=>{const[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[y,v]=k.useState(!1),[w,b]=k.useState(null),[N,S]=k.useState([]),[T,A]=k.useState(null),I=k.useRef(null),D=k.useRef(!1),R=k.useRef(!1),$=br(),F=()=>{h(!1),x(!1),v(!1),b(null),S([]),A(null),I.current=null,D.current=!1},z=async Z=>{if(!(D.current&&I.current===Z)&&!R.current){R.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",Z);const[{data:re,error:le},{data:oe,error:ne},{data:ie,error:ye}]=await Promise.all([V.rpc("has_role",{_user_id:Z,_role:"admin"}),V.rpc("has_role",{_user_id:Z,_role:"brokerage_manager"}),V.rpc("has_role",{_user_id:Z,_role:"coach"})]);if(le||ne)console.error("Role RPC errors:",{isAdminError:le,isBrokerError:ne,isCoachError:ye}),h(!1),x(!1),v(!1);else{const be=!!re,Ue=!!oe,Be=!!ie;console.log("RPC roles result:",{adminValue:be,brokerValue:Ue,coachValue:Be}),h(be),x(Ue),v(Be)}const{data:ce,error:ve}=await V.from("profiles").select("brokerage_id").eq("id",Z).single();if(b(!ve&&ce?ce.brokerage_id:null),oe){console.log("Fetching managed brokerages for user:",Z);const{data:be,error:Ue}=await V.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",Z);if(console.log("Managed brokerage assignments result:",{assignments:be,assignmentsError:Ue}),Ue||!be){console.error("Error fetching managed brokerage assignments:",Ue),S([]);return}const Be=Array.from(new Set(be.map(Le=>Le.brokerage_id).filter(Boolean)));if(Be.length===0){S([]);return}const{data:De,error:Ae}=await V.from("brokerages").select("id, name").in("id",Be);if(console.log("Managed brokerages details result:",{brokeragesData:De,brokeragesError:Ae}),Ae||!De){console.error("Error fetching managed brokerages details:",Ae),S([]);return}const He=De.map(Le=>({id:Le.id,name:Le.name})).sort((Le,Ie)=>Be.indexOf(Le.id)-Be.indexOf(Ie.id));console.log("Parsed managed brokerages:",He),S(He),He.length>0&&A(Le=>Le??He[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),S([]);I.current=Z,D.current=!0}catch(re){console.error("Unexpected error in checkRoles:",re),F()}finally{R.current=!1,c(!1)}}};k.useEffect(()=>{let Z=!0,re=!1;const le=()=>{!Z||re||(re=!0,l(!1))},{data:{subscription:oe}}=V.auth.onAuthStateChange((ye,ce)=>{console.log("Auth event:",ye),Z&&(a(ce),r((ce==null?void 0:ce.user)??null),le(),ye==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{$("/profile?reset=true")},100)),ce!=null&&ce.user?(!D.current||I.current!==ce.user.id)&&setTimeout(()=>{z(ce.user.id)},0):(F(),c(!1)))}),ne=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),le()},4e3);return(async()=>{try{const{data:{session:ye}}=await V.auth.getSession();if(!Z)return;a(ye),r((ye==null?void 0:ye.user)??null),ye!=null&&ye.user?await z(ye.user.id):F()}catch(ye){console.error("Error restoring auth session:",ye),Z&&(a(null),r(null),F())}finally{le()}})(),()=>{Z=!1,window.clearTimeout(ne),oe.unsubscribe()}},[]);const Q=async(Z,re)=>{const{error:le}=await V.auth.signInWithPassword({email:Z,password:re});if(le)throw ue.error(le.message),le;ue.success("Welcome back!");const oe=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";sessionStorage.removeItem("redirectAfterLogin"),$(oe)},K=async(Z,re,le)=>{var ce;const oe=`${window.location.origin}/dashboard`,ne=localStorage.getItem("levelup_referral_code")||null,{data:ie,error:ye}=await V.auth.signUp({email:Z,password:re,options:{emailRedirectTo:oe,data:{name:le,referred_by_code:ne}}});if(ye)throw ue.error(ye.message),ye;if(ne&&((ce=ie.user)!=null&&ce.id))try{await V.from("profiles").update({referred_by_code:ne}).eq("id",ie.user.id),localStorage.removeItem("levelup_referral_code")}catch(ve){console.warn("Failed to attach referral code to profile",ve)}ue.success("Account created! Welcome to LevelUp."),$("/dashboard")},X=async()=>{try{const{data:{session:Z}}=await V.auth.getSession();if(Z){const{error:re}=await V.auth.signOut();re?re.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",re.message):(console.error("Sign out error:",re),ue.error(re.message)):ue.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),a(null),h(!1),x(!1),b(null),S([]),A(null),$("/auth")}catch(Z){console.error("Unexpected sign out error:",Z),$("/auth")}};return e.jsx(eXe.Provider,{value:{user:t,session:n,loading:i,rolesLoading:o,signIn:Q,signUp:K,signOut:X,isAdmin:d,isBrokerageManager:m,isCoach:y,brokerageId:w,managedBrokerages:N,selectedBrokerageId:T,setSelectedBrokerageId:A},children:s})},js=()=>{const s=k.useContext(eXe);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},tXe=k.createContext({onlineUsers:[],totalOnline:0}),i5t=async s=>{try{const{data:t}=await V.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:r}=V.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return r.publicUrl}}catch{}},o5t=({children:s})=>{const{user:t,brokerageId:r,isAdmin:n}=js(),[a,i]=k.useState([]),[l,o]=k.useState(null);k.useEffect(()=>{if(!t)return;let d=!1;V.auth.getSession().then(({data:m})=>{var y;const x=(y=m.session)==null?void 0:y.access_token;if(x)try{V.realtime.setAuth(x)}catch{}});const h=V.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return h.on("presence",{event:"sync"},()=>{const m=h.presenceState(),x=[];Object.entries(m).forEach(([y,v])=>{if(v&&v.length>0){const w=v[0];x.push({id:y,name:w.name||"Unknown",avatarUrl:w.avatarUrl,brokerageId:w.brokerageId,onlineSince:w.onlineSince})}}),console.log("[Presence] sync, users:",x.length,x),i(x)}).on("presence",{event:"join"},({key:m,newPresences:x})=>{console.log("[Presence] join",m,x)}).on("presence",{event:"leave"},({key:m})=>{console.log("[Presence] leave",m)}).subscribe(async(m,x)=>{var y;if(console.log("[Presence] subscribe status:",m,x),m==="SUBSCRIBED"&&!d){const{data:v}=await V.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),w=await i5t(t.id),b=await h.track({name:(v==null?void 0:v.name)||((y=t.email)==null?void 0:y.split("@")[0])||"User",avatarUrl:w,brokerageId:v==null?void 0:v.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",b)}}),o(h),()=>{d=!0;try{h.untrack()}catch{}V.removeChannel(h)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(n||r&&d.brokerageId===r||!r&&!d.brokerageId));return e.jsx(tXe.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},sXe=()=>k.useContext(tXe),rXe=k.createContext(void 0),bN="levelup_admin_session",D_="levelup_impersonation",nve="levelup_impersonation_return",l5t=({children:s})=>{const[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(!1);k.useEffect(()=>{const d=sessionStorage.getItem(D_);if(d)try{const h=JSON.parse(d);r(!0),a(h)}catch{sessionStorage.removeItem(D_)}},[]);const o=async(d,h)=>{l(!0);try{const{data:{session:m}}=await V.auth.getSession();if(!m)return ue.error("No active session found"),!1;const x={access_token:m.access_token,refresh_token:m.refresh_token};sessionStorage.setItem(bN,JSON.stringify(x)),h&&sessionStorage.setItem(nve,h);const y=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m.access_token}`},body:JSON.stringify({targetUserId:d})}),v=await y.json();if(!y.ok)throw new Error(v.error||"Failed to impersonate user");const w={id:v.targetUser.id,name:v.targetUser.name,email:v.targetUser.email};if(sessionStorage.setItem(D_,JSON.stringify(w)),v.method==="session"){const{error:b}=await V.auth.setSession({access_token:v.access_token,refresh_token:v.refresh_token});if(b)throw console.error("Set session error:",b),sessionStorage.removeItem(bN),sessionStorage.removeItem(D_),new Error("Failed to establish impersonation session")}else{const b=v.type||"recovery",{error:N}=await V.auth.verifyOtp({token_hash:v.token_hash,type:b});if(N)throw console.error("Verify OTP error:",N),sessionStorage.removeItem(bN),sessionStorage.removeItem(D_),new Error("Failed to establish impersonation session")}return r(!0),a(w),ue.success(`Now viewing as ${w.name}`),window.location.href="/dashboard",!0}catch(m){return console.error("Impersonation error:",m),ue.error(m.message||"Failed to impersonate user"),sessionStorage.removeItem(bN),sessionStorage.removeItem(D_),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(bN);if(!d){await V.auth.signOut(),window.location.href="/auth";return}const h=JSON.parse(d);await V.auth.signOut();const{error:m}=await V.auth.setSession({access_token:h.access_token,refresh_token:h.refresh_token});if(sessionStorage.removeItem(bN),sessionStorage.removeItem(D_),m){console.error("Failed to restore admin session:",m),ue.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),a(null),ue.success("Returned to your account");const x=sessionStorage.getItem(nve)||"/admin/members";sessionStorage.removeItem(nve),window.location.href=x}catch(d){console.error("Stop impersonation error:",d),ue.error("Failed to restore admin session"),sessionStorage.removeItem(bN),sessionStorage.removeItem(D_),window.location.href="/auth"}finally{l(!1)}};return e.jsx(rXe.Provider,{value:{isImpersonating:t,impersonatedUser:n,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},Yme=()=>{const s=k.useContext(rXe);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},jM=r5("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"}}),G=k.forwardRef(({className:s,variant:t,size:r,asChild:n=!1,...a},i)=>{const l=n?sCe:"button";return e.jsx(l,{className:It(jM({variant:t,size:r,className:s})),ref:i,...a})});G.displayName="Button";const c5t=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:r,isLoading:n}=Yme();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(id,{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(G,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(vr,{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"})]})})]})})},nXe=k.createContext(void 0),VT="levelup_acting_as",B9="levelup_acting_as_self",d5t=({children:s})=>{const{user:t}=js(),[r,n]=k.useState(!1),[a,i]=k.useState([]),[l,o]=k.useState(null),[c,d]=k.useState({}),[h,m]=k.useState(!0),[x,y]=k.useState(()=>sessionStorage.getItem(B9)==="true");k.useEffect(()=>{if(!(t!=null&&t.id)){n(!1),i([]),o(null),d({}),m(!1);return}(async()=>{m(!0);try{const{data:T}=await V.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!T){n(!1),i([]),o(null),d({}),m(!1);return}n(!0);const{data:A,error:I}=await V.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(I||!A||A.length===0){i([]),m(!1);return}const D=A.map(F=>F.agent_id),{data:R}=await V.from("profiles").select("id, name, email, avatar_url").in("id",D),$=(R||[]).map(F=>({id:F.id,name:F.name||F.email||"Unknown",email:F.email||"",avatar_url:F.avatar_url}));if(i($),sessionStorage.getItem(B9)==="true")y(!0),o(null),d({});else{const F=sessionStorage.getItem(VT);if(F){const z=$.find(Q=>Q.id===F);if(z){o(z);const Q=A.find(K=>K.agent_id===F);d((Q==null?void 0:Q.permissions)||{})}else if($.length>0){o($[0]);const Q=A.find(K=>K.agent_id===$[0].id);d((Q==null?void 0:Q.permissions)||{}),sessionStorage.setItem(VT,$[0].id)}}else if($.length>0){o($[0]);const z=A.find(Q=>Q.agent_id===$[0].id);d((z==null?void 0:z.permissions)||{}),sessionStorage.setItem(VT,$[0].id)}}}catch(T){console.error("Error loading assistant data:",T)}finally{m(!1)}})()},[t==null?void 0:t.id]);const v=S=>{o(S),y(!1),sessionStorage.removeItem(B9),S?(sessionStorage.setItem(VT,S.id),V.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",S.id).single().then(({data:T})=>{d((T==null?void 0:T.permissions)||{})})):(sessionStorage.removeItem(VT),d({}))},w=()=>{y(!0),o(null),d({}),sessionStorage.setItem(B9,"true"),sessionStorage.removeItem(VT)},b=S=>!r||x?!0:c[S]===!0,N=r&&l&&!x?l.id:(t==null?void 0:t.id)||null;return e.jsx(nXe.Provider,{value:{isAssistant:r,assignedAgents:a,actingAsAgent:l,setActingAsAgent:v,effectiveUserId:N,permissions:c,hasPermission:b,isLoading:h,isActingAsSelf:x,setActingAsSelf:w},children:s})},MCe=()=>{const s=k.useContext(nXe);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},sa=()=>{const{effectiveUserId:s}=MCe();return s};var aXe={exports:{}},iXe={};/** * @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 NM=k;function u5t(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var h5t=typeof Object.is=="function"?Object.is:u5t,m5t=NM.useState,f5t=NM.useEffect,p5t=NM.useLayoutEffect,x5t=NM.useDebugValue;function g5t(s,t){var r=t(),n=m5t({inst:{value:r,getSnapshot:t}}),a=n[0].inst,i=n[1];return p5t(function(){a.value=r,a.getSnapshot=t,ave(a)&&i({inst:a})},[s,r,t]),f5t(function(){return ave(a)&&i({inst:a}),s(function(){ave(a)&&i({inst:a})})},[s]),x5t(r),r}function ave(s){var t=s.getSnapshot;s=s.value;try{var r=t();return!h5t(s,r)}catch{return!0}}function y5t(s,t){return t()}var v5t=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?y5t:g5t;iXe.useSyncExternalStore=NM.useSyncExternalStore!==void 0?NM.useSyncExternalStore:v5t;aXe.exports=iXe;var b5t=aXe.exports;function _5t(){return b5t.useSyncExternalStore(w5t,()=>!0,()=>!1)}function w5t(){return()=>{}}var ICe="Avatar",[j5t,bUs]=pd(ICe),[N5t,oXe]=j5t(ICe),lXe=k.forwardRef((s,t)=>{const{__scopeAvatar:r,...n}=s,[a,i]=k.useState("idle");return e.jsx(N5t,{scope:r,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(wn.span,{...n,ref:t})})});lXe.displayName=ICe;var cXe="AvatarImage",dXe=k.forwardRef((s,t)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:a=()=>{},...i}=s,l=oXe(cXe,r),o=k5t(n,i),c=Ed(d=>{a(d),l.onImageLoadingStatusChange(d)});return Dd(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(wn.img,{...i,ref:t,src:n}):null});dXe.displayName=cXe;var uXe="AvatarFallback",hXe=k.forwardRef((s,t)=>{const{__scopeAvatar:r,delayMs:n,...a}=s,i=oXe(uXe,r),[l,o]=k.useState(n===void 0);return k.useEffect(()=>{if(n!==void 0){const c=window.setTimeout(()=>o(!0),n);return()=>window.clearTimeout(c)}},[n]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(wn.span,{...a,ref:t}):null});hXe.displayName=uXe;function QDe(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function k5t(s,{referrerPolicy:t,crossOrigin:r}){const n=_5t(),a=k.useRef(null),i=n?(a.current||(a.current=new window.Image),a.current):null,[l,o]=k.useState(()=>QDe(i,s));return Dd(()=>{o(QDe(i,s))},[i,s]),Dd(()=>{const c=m=>()=>{o(m)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof r=="string"&&(i.crossOrigin=r),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,r,t]),l}var mXe=lXe,fXe=dXe,pXe=hXe;const Nn=k.forwardRef(({className:s,...t},r)=>e.jsx(mXe,{ref:r,className:It("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Nn.displayName=mXe.displayName;const ya=k.forwardRef(({className:s,...t},r)=>e.jsx(fXe,{ref:r,className:It("aspect-square h-full w-full",s),...t}));ya.displayName=fXe.displayName;const kn=k.forwardRef(({className:s,...t},r)=>e.jsx(pXe,{ref:r,className:It("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));kn.displayName=pXe.displayName;const S5t=r5("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 Ge({className:s,variant:t,...r}){return e.jsx("div",{className:It(S5t({variant:t}),s),...r})}var C5t=k.createContext(void 0);function Kj(s){const t=k.useContext(C5t);return s||t||"ltr"}var ive=0;function Zme(){k.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??JDe()),document.body.insertAdjacentElement("beforeend",s[1]??JDe()),ive++,()=>{ive===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),ive--}},[])}function JDe(){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 ove="focusScope.autoFocusOnMount",lve="focusScope.autoFocusOnUnmount",eRe={bubbles:!1,cancelable:!0},T5t="FocusScope",KF=k.forwardRef((s,t)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=k.useState(null),d=Ed(a),h=Ed(i),m=k.useRef(null),x=Ga(t,w=>c(w)),y=k.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;k.useEffect(()=>{if(n){let w=function(T){if(y.paused||!o)return;const A=T.target;o.contains(A)?m.current=A:K_(m.current,{select:!0})},b=function(T){if(y.paused||!o)return;const A=T.relatedTarget;A!==null&&(o.contains(A)||K_(m.current,{select:!0}))},N=function(T){if(document.activeElement===document.body)for(const I of T)I.removedNodes.length>0&&K_(o)};document.addEventListener("focusin",w),document.addEventListener("focusout",b);const S=new MutationObserver(N);return o&&S.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",w),document.removeEventListener("focusout",b),S.disconnect()}}},[n,o,y.paused]),k.useEffect(()=>{if(o){sRe.add(y);const w=document.activeElement;if(!o.contains(w)){const N=new CustomEvent(ove,eRe);o.addEventListener(ove,d),o.dispatchEvent(N),N.defaultPrevented||(E5t(P5t(xXe(o)),{select:!0}),document.activeElement===w&&K_(o))}return()=>{o.removeEventListener(ove,d),setTimeout(()=>{const N=new CustomEvent(lve,eRe);o.addEventListener(lve,h),o.dispatchEvent(N),N.defaultPrevented||K_(w??document.body,{select:!0}),o.removeEventListener(lve,h),sRe.remove(y)},0)}}},[o,d,h,y]);const v=k.useCallback(w=>{if(!r&&!n||y.paused)return;const b=w.key==="Tab"&&!w.altKey&&!w.ctrlKey&&!w.metaKey,N=document.activeElement;if(b&&N){const S=w.currentTarget,[T,A]=A5t(S);T&&A?!w.shiftKey&&N===A?(w.preventDefault(),r&&K_(T,{select:!0})):w.shiftKey&&N===T&&(w.preventDefault(),r&&K_(A,{select:!0})):N===S&&w.preventDefault()}},[r,n,y.paused]);return e.jsx(wn.div,{tabIndex:-1,...l,ref:x,onKeyDown:v})});KF.displayName=T5t;function E5t(s,{select:t=!1}={}){const r=document.activeElement;for(const n of s)if(K_(n,{select:t}),document.activeElement!==r)return}function A5t(s){const t=xXe(s),r=tRe(t,s),n=tRe(t.reverse(),s);return[r,n]}function xXe(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{const a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function tRe(s,t){for(const r of s)if(!M5t(r,{upTo:t}))return r}function M5t(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 I5t(s){return s instanceof HTMLInputElement&&"select"in s}function K_(s,{select:t=!1}={}){if(s&&s.focus){const r=document.activeElement;s.focus({preventScroll:!0}),s!==r&&I5t(s)&&t&&s.select()}}var sRe=L5t();function L5t(){let s=[];return{add(t){const r=s[0];t!==r&&(r==null||r.pause()),s=rRe(s,t),s.unshift(t)},remove(t){var r;s=rRe(s,t),(r=s[0])==null||r.resume()}}}function rRe(s,t){const r=[...s],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function P5t(s){return s.filter(t=>t.tagName!=="A")}var cve="rovingFocusGroup.onEntryFocus",D5t={bubbles:!1,cancelable:!0},YF="RovingFocusGroup",[Gwe,gXe,R5t]=BF(YF),[O5t,Yj]=pd(YF,[R5t]),[F5t,B5t]=O5t(YF),yXe=k.forwardRef((s,t)=>e.jsx(Gwe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Gwe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(z5t,{...s,ref:t})})}));yXe.displayName=YF;var z5t=k.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:h=!1,...m}=s,x=k.useRef(null),y=Ga(t,x),v=Kj(i),[w,b]=Sh({prop:l,defaultProp:o??null,onChange:c,caller:YF}),[N,S]=k.useState(!1),T=Ed(d),A=gXe(r),I=k.useRef(!1),[D,R]=k.useState(0);return k.useEffect(()=>{const $=x.current;if($)return $.addEventListener(cve,T),()=>$.removeEventListener(cve,T)},[T]),e.jsx(F5t,{scope:r,orientation:n,dir:v,loop:a,currentTabStopId:w,onItemFocus:k.useCallback($=>b($),[b]),onItemShiftTab:k.useCallback(()=>S(!0),[]),onFocusableItemAdd:k.useCallback(()=>R($=>$+1),[]),onFocusableItemRemove:k.useCallback(()=>R($=>$-1),[]),children:e.jsx(wn.div,{tabIndex:N||D===0?-1:0,"data-orientation":n,...m,ref:y,style:{outline:"none",...s.style},onMouseDown:Vr(s.onMouseDown,()=>{I.current=!0}),onFocus:Vr(s.onFocus,$=>{const F=!I.current;if($.target===$.currentTarget&&F&&!N){const z=new CustomEvent(cve,D5t);if($.currentTarget.dispatchEvent(z),!z.defaultPrevented){const Q=A().filter(le=>le.focusable),K=Q.find(le=>le.active),X=Q.find(le=>le.id===w),re=[K,X,...Q].filter(Boolean).map(le=>le.ref.current);_Xe(re,h)}}I.current=!1}),onBlur:Vr(s.onBlur,()=>S(!1))})})}),vXe="RovingFocusGroupItem",bXe=k.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=Yu(),d=i||c,h=B5t(vXe,r),m=h.currentTabStopId===d,x=gXe(r),{onFocusableItemAdd:y,onFocusableItemRemove:v,currentTabStopId:w}=h;return k.useEffect(()=>{if(n)return y(),()=>v()},[n,y,v]),e.jsx(Gwe.ItemSlot,{scope:r,id:d,focusable:n,active:a,children:e.jsx(wn.span,{tabIndex:m?0:-1,"data-orientation":h.orientation,...o,ref:t,onMouseDown:Vr(s.onMouseDown,b=>{n?h.onItemFocus(d):b.preventDefault()}),onFocus:Vr(s.onFocus,()=>h.onItemFocus(d)),onKeyDown:Vr(s.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){h.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const N=q5t(b,h.orientation,h.dir);if(N!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let T=x().filter(A=>A.focusable).map(A=>A.ref.current);if(N==="last")T.reverse();else if(N==="prev"||N==="next"){N==="prev"&&T.reverse();const A=T.indexOf(b.currentTarget);T=h.loop?V5t(T,A+1):T.slice(A+1)}setTimeout(()=>_Xe(T))}}),children:typeof l=="function"?l({isCurrentTabStop:m,hasTabStop:w!=null}):l})})});bXe.displayName=vXe;var $5t={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function U5t(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function q5t(s,t,r){const n=U5t(s.key,r);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return $5t[n]}function _Xe(s,t=!1){const r=document.activeElement;for(const n of s)if(n===r||(n.focus({preventScroll:t}),document.activeElement!==r))return}function V5t(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var Xme=yXe,Qme=bXe,H5t=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},HT=new WeakMap,z9=new WeakMap,$9={},dve=0,wXe=function(s){return s&&(s.host||wXe(s.parentNode))},G5t=function(s,t){return t.map(function(r){if(s.contains(r))return r;var n=wXe(r);return n&&s.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",s,". Doing nothing"),null)}).filter(function(r){return!!r})},W5t=function(s,t,r,n){var a=G5t(t,Array.isArray(s)?s:[s]);$9[r]||($9[r]=new WeakMap);var i=$9[r],l=[],o=new Set,c=new Set(a),d=function(m){!m||o.has(m)||(o.add(m),d(m.parentNode))};a.forEach(d);var h=function(m){!m||c.has(m)||Array.prototype.forEach.call(m.children,function(x){if(o.has(x))h(x);else try{var y=x.getAttribute(n),v=y!==null&&y!=="false",w=(HT.get(x)||0)+1,b=(i.get(x)||0)+1;HT.set(x,w),i.set(x,b),l.push(x),w===1&&v&&z9.set(x,!0),b===1&&x.setAttribute(r,"true"),v||x.setAttribute(n,"true")}catch(N){console.error("aria-hidden: cannot operate on ",x,N)}})};return h(t),o.clear(),dve++,function(){l.forEach(function(m){var x=HT.get(m)-1,y=i.get(m)-1;HT.set(m,x),i.set(m,y),x||(z9.has(m)||m.removeAttribute(n),z9.delete(m)),y||m.removeAttribute(r)}),dve--,dve||(HT=new WeakMap,HT=new WeakMap,z9=new WeakMap,$9={})}},Jme=function(s,t,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(s)?s:[s]),a=H5t(s);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live]"))),W5t(n,a,r,"aria-hidden")):function(){return null}},z0=function(){return z0=Object.assign||function(t){for(var r,n=1,a=arguments.length;n"u")return dTt;var t=uTt(s),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}},mTt=SXe(),DA="data-scroll-locked",fTt=function(s,t,r,n){var a=s.left,i=s.top,l=s.right,o=s.gap;return r===void 0&&(r="margin"),` .`.concat(Y5t,` { overflow: hidden `).concat(n,`; padding-right: `).concat(o,"px ").concat(n,`; } body[`).concat(DA,`] { overflow: hidden `).concat(n,`; overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(n,";"),r==="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(n,`; `),r==="padding"&&"padding-right: ".concat(o,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(tce,` { right: `).concat(o,"px ").concat(n,`; } .`).concat(sce,` { margin-right: `).concat(o,"px ").concat(n,`; } .`).concat(tce," .").concat(tce,` { right: 0 `).concat(n,`; } .`).concat(sce," .").concat(sce,` { margin-right: 0 `).concat(n,`; } body[`).concat(DA,`] { `).concat(Z5t,": ").concat(o,`px; } `)},aRe=function(){var s=parseInt(document.body.getAttribute(DA)||"0",10);return isFinite(s)?s:0},pTt=function(){k.useEffect(function(){return document.body.setAttribute(DA,(aRe()+1).toString()),function(){var s=aRe()-1;s<=0?document.body.removeAttribute(DA):document.body.setAttribute(DA,s.toString())}},[])},xTt=function(s){var t=s.noRelative,r=s.noImportant,n=s.gapMode,a=n===void 0?"margin":n;pTt();var i=k.useMemo(function(){return hTt(a)},[a]);return k.createElement(mTt,{styles:fTt(i,!t,a,r?"":"!important")})},Wwe=!1;if(typeof window<"u")try{var U9=Object.defineProperty({},"passive",{get:function(){return Wwe=!0,!0}});window.addEventListener("test",U9,U9),window.removeEventListener("test",U9,U9)}catch{Wwe=!1}var GT=Wwe?{passive:!1}:!1,gTt=function(s){return s.tagName==="TEXTAREA"},CXe=function(s,t){if(!(s instanceof Element))return!1;var r=window.getComputedStyle(s);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!gTt(s)&&r[t]==="visible")},yTt=function(s){return CXe(s,"overflowY")},vTt=function(s){return CXe(s,"overflowX")},iRe=function(s,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=TXe(s,n);if(a){var i=EXe(s,n),l=i[1],o=i[2];if(l>o)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},bTt=function(s){var t=s.scrollTop,r=s.scrollHeight,n=s.clientHeight;return[t,r,n]},_Tt=function(s){var t=s.scrollLeft,r=s.scrollWidth,n=s.clientWidth;return[t,r,n]},TXe=function(s,t){return s==="v"?yTt(t):vTt(t)},EXe=function(s,t){return s==="v"?bTt(t):_Tt(t)},wTt=function(s,t){return s==="h"&&t==="rtl"?-1:1},jTt=function(s,t,r,n,a){var i=wTt(s,window.getComputedStyle(t).direction),l=i*n,o=r.target,c=t.contains(o),d=!1,h=l>0,m=0,x=0;do{if(!o)break;var y=EXe(s,o),v=y[0],w=y[1],b=y[2],N=w-b-i*v;(v||N)&&TXe(s,o)&&(m+=N,x+=v);var S=o.parentNode;o=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(h&&(Math.abs(m)<1||!a)||!h&&(Math.abs(x)<1||!a))&&(d=!0),d},q9=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},oRe=function(s){return[s.deltaX,s.deltaY]},lRe=function(s){return s&&"current"in s?s.current:s},NTt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},kTt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},STt=0,WT=[];function CTt(s){var t=k.useRef([]),r=k.useRef([0,0]),n=k.useRef(),a=k.useState(STt++)[0],i=k.useState(SXe)[0],l=k.useRef(s);k.useEffect(function(){l.current=s},[s]),k.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var w=K5t([s.lockRef.current],(s.shards||[]).map(lRe),!0).filter(Boolean);return w.forEach(function(b){return b.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),w.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=k.useCallback(function(w,b){if("touches"in w&&w.touches.length===2||w.type==="wheel"&&w.ctrlKey)return!l.current.allowPinchZoom;var N=q9(w),S=r.current,T="deltaX"in w?w.deltaX:S[0]-N[0],A="deltaY"in w?w.deltaY:S[1]-N[1],I,D=w.target,R=Math.abs(T)>Math.abs(A)?"h":"v";if("touches"in w&&R==="h"&&D.type==="range")return!1;var $=iRe(R,D);if(!$)return!0;if($?I=R:(I=R==="v"?"h":"v",$=iRe(R,D)),!$)return!1;if(!n.current&&"changedTouches"in w&&(T||A)&&(n.current=I),!I)return!0;var F=n.current||I;return jTt(F,b,w,F==="h"?T:A,!0)},[]),c=k.useCallback(function(w){var b=w;if(!(!WT.length||WT[WT.length-1]!==i)){var N="deltaY"in b?oRe(b):q9(b),S=t.current.filter(function(I){return I.name===b.type&&(I.target===b.target||b.target===I.shadowParent)&&NTt(I.delta,N)})[0];if(S&&S.should){b.cancelable&&b.preventDefault();return}if(!S){var T=(l.current.shards||[]).map(lRe).filter(Boolean).filter(function(I){return I.contains(b.target)}),A=T.length>0?o(b,T[0]):!l.current.noIsolation;A&&b.cancelable&&b.preventDefault()}}},[]),d=k.useCallback(function(w,b,N,S){var T={name:w,delta:b,target:N,should:S,shadowParent:TTt(N)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(A){return A!==T})},1)},[]),h=k.useCallback(function(w){r.current=q9(w),n.current=void 0},[]),m=k.useCallback(function(w){d(w.type,oRe(w),w.target,o(w,s.lockRef.current))},[]),x=k.useCallback(function(w){d(w.type,q9(w),w.target,o(w,s.lockRef.current))},[]);k.useEffect(function(){return WT.push(i),s.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:x}),document.addEventListener("wheel",c,GT),document.addEventListener("touchmove",c,GT),document.addEventListener("touchstart",h,GT),function(){WT=WT.filter(function(w){return w!==i}),document.removeEventListener("wheel",c,GT),document.removeEventListener("touchmove",c,GT),document.removeEventListener("touchstart",h,GT)}},[]);var y=s.removeScrollBar,v=s.inert;return k.createElement(k.Fragment,null,v?k.createElement(i,{styles:kTt(a)}):null,y?k.createElement(xTt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function TTt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const ETt=rTt(kXe,CTt);var ZF=k.forwardRef(function(s,t){return k.createElement(efe,z0({},s,{ref:t,sideCar:ETt}))});ZF.classNames=efe.classNames;var Kwe=["Enter"," "],ATt=["ArrowDown","PageUp","Home"],AXe=["ArrowUp","PageDown","End"],MTt=[...ATt,...AXe],ITt={ltr:[...Kwe,"ArrowRight"],rtl:[...Kwe,"ArrowLeft"]},LTt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},XF="Menu",[u8,PTt,DTt]=BF(XF),[a5,MXe]=pd(XF,[DTt,Pv,Yj]),tfe=Pv(),IXe=Yj(),[RTt,i5]=a5(XF),[OTt,QF]=a5(XF),LXe=s=>{const{__scopeMenu:t,open:r=!1,children:n,dir:a,onOpenChange:i,modal:l=!0}=s,o=tfe(t),[c,d]=k.useState(null),h=k.useRef(!1),m=Ed(i),x=Kj(a);return k.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",v,{capture:!0,once:!0}),document.addEventListener("pointermove",v,{capture:!0,once:!0})},v=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",v,{capture:!0}),document.removeEventListener("pointermove",v,{capture:!0})}},[]),e.jsx(qF,{...o,children:e.jsx(RTt,{scope:t,open:r,onOpenChange:m,content:c,onContentChange:d,children:e.jsx(OTt,{scope:t,onClose:k.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:x,modal:l,children:n})})})};LXe.displayName=XF;var FTt="MenuAnchor",LCe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=tfe(r);return e.jsx(PI,{...a,...n,ref:t})});LCe.displayName=FTt;var PCe="MenuPortal",[BTt,PXe]=a5(PCe,{forceMount:void 0}),DXe=s=>{const{__scopeMenu:t,forceMount:r,children:n,container:a}=s,i=i5(PCe,t);return e.jsx(BTt,{scope:t,forceMount:r,children:e.jsx(ru,{present:r||i.open,children:e.jsx(AI,{asChild:!0,container:a,children:n})})})};DXe.displayName=PCe;var lg="MenuContent",[zTt,DCe]=a5(lg),RXe=k.forwardRef((s,t)=>{const r=PXe(lg,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=i5(lg,s.__scopeMenu),l=QF(lg,s.__scopeMenu);return e.jsx(u8.Provider,{scope:s.__scopeMenu,children:e.jsx(ru,{present:n||i.open,children:e.jsx(u8.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx($Tt,{...a,ref:t}):e.jsx(UTt,{...a,ref:t})})})})}),$Tt=k.forwardRef((s,t)=>{const r=i5(lg,s.__scopeMenu),n=k.useRef(null),a=Ga(t,n);return k.useEffect(()=>{const i=n.current;if(i)return Jme(i)},[]),e.jsx(RCe,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Vr(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),UTt=k.forwardRef((s,t)=>{const r=i5(lg,s.__scopeMenu);return e.jsx(RCe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),qTt=kj("MenuContent.ScrollLock"),RCe=k.forwardRef((s,t)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:x,onDismiss:y,disableOutsideScroll:v,...w}=s,b=i5(lg,r),N=QF(lg,r),S=tfe(r),T=IXe(r),A=PTt(r),[I,D]=k.useState(null),R=k.useRef(null),$=Ga(t,R,b.onContentChange),F=k.useRef(0),z=k.useRef(""),Q=k.useRef(0),K=k.useRef(null),X=k.useRef("right"),Z=k.useRef(0),re=v?ZF:k.Fragment,le=v?{as:qTt,allowPinchZoom:!0}:void 0,oe=ie=>{var Ae,He;const ye=z.current+ie,ce=A().filter(Le=>!Le.disabled),ve=document.activeElement,be=(Ae=ce.find(Le=>Le.ref.current===ve))==null?void 0:Ae.textValue,Ue=ce.map(Le=>Le.textValue),Be=tEt(Ue,ye,be),De=(He=ce.find(Le=>Le.textValue===Be))==null?void 0:He.ref.current;(function Le(Ie){z.current=Ie,window.clearTimeout(F.current),Ie!==""&&(F.current=window.setTimeout(()=>Le(""),1e3))})(ye),De&&setTimeout(()=>De.focus())};k.useEffect(()=>()=>window.clearTimeout(F.current),[]),Zme();const ne=k.useCallback(ie=>{var ce,ve;return X.current===((ce=K.current)==null?void 0:ce.side)&&rEt(ie,(ve=K.current)==null?void 0:ve.area)},[]);return e.jsx(zTt,{scope:r,searchRef:z,onItemEnter:k.useCallback(ie=>{ne(ie)&&ie.preventDefault()},[ne]),onItemLeave:k.useCallback(ie=>{var ye;ne(ie)||((ye=R.current)==null||ye.focus(),D(null))},[ne]),onTriggerLeave:k.useCallback(ie=>{ne(ie)&&ie.preventDefault()},[ne]),pointerGraceTimerRef:Q,onPointerGraceIntentChange:k.useCallback(ie=>{K.current=ie},[]),children:e.jsx(re,{...le,children:e.jsx(KF,{asChild:!0,trapped:a,onMountAutoFocus:Vr(i,ie=>{var ye;ie.preventDefault(),(ye=R.current)==null||ye.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(Hj,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:x,onDismiss:y,children:e.jsx(Xme,{asChild:!0,...T,dir:N.dir,orientation:"vertical",loop:n,currentTabStopId:I,onCurrentTabStopIdChange:D,onEntryFocus:Vr(c,ie=>{N.isUsingKeyboardRef.current||ie.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(VF,{role:"menu","aria-orientation":"vertical","data-state":QXe(b.open),"data-radix-menu-content":"",dir:N.dir,...S,...w,ref:$,style:{outline:"none",...w.style},onKeyDown:Vr(w.onKeyDown,ie=>{const ce=ie.target.closest("[data-radix-menu-content]")===ie.currentTarget,ve=ie.ctrlKey||ie.altKey||ie.metaKey,be=ie.key.length===1;ce&&(ie.key==="Tab"&&ie.preventDefault(),!ve&&be&&oe(ie.key));const Ue=R.current;if(ie.target!==Ue||!MTt.includes(ie.key))return;ie.preventDefault();const De=A().filter(Ae=>!Ae.disabled).map(Ae=>Ae.ref.current);AXe.includes(ie.key)&&De.reverse(),JTt(De)}),onBlur:Vr(s.onBlur,ie=>{ie.currentTarget.contains(ie.target)||(window.clearTimeout(F.current),z.current="")}),onPointerMove:Vr(s.onPointerMove,h8(ie=>{const ye=ie.target,ce=Z.current!==ie.clientX;if(ie.currentTarget.contains(ye)&&ce){const ve=ie.clientX>Z.current?"right":"left";X.current=ve,Z.current=ie.clientX}}))})})})})})})});RXe.displayName=lg;var VTt="MenuGroup",OCe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(wn.div,{role:"group",...n,ref:t})});OCe.displayName=VTt;var HTt="MenuLabel",OXe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(wn.div,{...n,ref:t})});OXe.displayName=HTt;var yde="MenuItem",cRe="menu.itemSelect",sfe=k.forwardRef((s,t)=>{const{disabled:r=!1,onSelect:n,...a}=s,i=k.useRef(null),l=QF(yde,s.__scopeMenu),o=DCe(yde,s.__scopeMenu),c=Ga(t,i),d=k.useRef(!1),h=()=>{const m=i.current;if(!r&&m){const x=new CustomEvent(cRe,{bubbles:!0,cancelable:!0});m.addEventListener(cRe,y=>n==null?void 0:n(y),{once:!0}),rCe(m,x),x.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(FXe,{...a,ref:c,disabled:r,onClick:Vr(s.onClick,h),onPointerDown:m=>{var x;(x=s.onPointerDown)==null||x.call(s,m),d.current=!0},onPointerUp:Vr(s.onPointerUp,m=>{var x;d.current||(x=m.currentTarget)==null||x.click()}),onKeyDown:Vr(s.onKeyDown,m=>{const x=o.searchRef.current!=="";r||x&&m.key===" "||Kwe.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})});sfe.displayName=yde;var FXe=k.forwardRef((s,t)=>{const{__scopeMenu:r,disabled:n=!1,textValue:a,...i}=s,l=DCe(yde,r),o=IXe(r),c=k.useRef(null),d=Ga(t,c),[h,m]=k.useState(!1),[x,y]=k.useState("");return k.useEffect(()=>{const v=c.current;v&&y((v.textContent??"").trim())},[i.children]),e.jsx(u8.ItemSlot,{scope:r,disabled:n,textValue:a??x,children:e.jsx(Qme,{asChild:!0,...o,focusable:!n,children:e.jsx(wn.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...i,ref:d,onPointerMove:Vr(s.onPointerMove,h8(v=>{n?l.onItemLeave(v):(l.onItemEnter(v),v.defaultPrevented||v.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Vr(s.onPointerLeave,h8(v=>l.onItemLeave(v))),onFocus:Vr(s.onFocus,()=>m(!0)),onBlur:Vr(s.onBlur,()=>m(!1))})})})}),GTt="MenuCheckboxItem",BXe=k.forwardRef((s,t)=>{const{checked:r=!1,onCheckedChange:n,...a}=s;return e.jsx(VXe,{scope:s.__scopeMenu,checked:r,children:e.jsx(sfe,{role:"menuitemcheckbox","aria-checked":vde(r)?"mixed":r,...a,ref:t,"data-state":BCe(r),onSelect:Vr(a.onSelect,()=>n==null?void 0:n(vde(r)?!0:!r),{checkForDefaultPrevented:!1})})})});BXe.displayName=GTt;var zXe="MenuRadioGroup",[WTt,KTt]=a5(zXe,{value:void 0,onValueChange:()=>{}}),$Xe=k.forwardRef((s,t)=>{const{value:r,onValueChange:n,...a}=s,i=Ed(n);return e.jsx(WTt,{scope:s.__scopeMenu,value:r,onValueChange:i,children:e.jsx(OCe,{...a,ref:t})})});$Xe.displayName=zXe;var UXe="MenuRadioItem",qXe=k.forwardRef((s,t)=>{const{value:r,...n}=s,a=KTt(UXe,s.__scopeMenu),i=r===a.value;return e.jsx(VXe,{scope:s.__scopeMenu,checked:i,children:e.jsx(sfe,{role:"menuitemradio","aria-checked":i,...n,ref:t,"data-state":BCe(i),onSelect:Vr(n.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,r)},{checkForDefaultPrevented:!1})})})});qXe.displayName=UXe;var FCe="MenuItemIndicator",[VXe,YTt]=a5(FCe,{checked:!1}),HXe=k.forwardRef((s,t)=>{const{__scopeMenu:r,forceMount:n,...a}=s,i=YTt(FCe,r);return e.jsx(ru,{present:n||vde(i.checked)||i.checked===!0,children:e.jsx(wn.span,{...a,ref:t,"data-state":BCe(i.checked)})})});HXe.displayName=FCe;var ZTt="MenuSeparator",GXe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s;return e.jsx(wn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:t})});GXe.displayName=ZTt;var XTt="MenuArrow",WXe=k.forwardRef((s,t)=>{const{__scopeMenu:r,...n}=s,a=tfe(r);return e.jsx(HF,{...a,...n,ref:t})});WXe.displayName=XTt;var QTt="MenuSub",[_Us,KXe]=a5(QTt),AD="MenuSubTrigger",YXe=k.forwardRef((s,t)=>{const r=i5(AD,s.__scopeMenu),n=QF(AD,s.__scopeMenu),a=KXe(AD,s.__scopeMenu),i=DCe(AD,s.__scopeMenu),l=k.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},h=k.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return k.useEffect(()=>h,[h]),k.useEffect(()=>{const m=o.current;return()=>{window.clearTimeout(m),c(null)}},[o,c]),e.jsx(LCe,{asChild:!0,...d,children:e.jsx(FXe,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":a.contentId,"data-state":QXe(r.open),...s,ref:Eb(t,a.onTriggerChange),onClick:m=>{var x;(x=s.onClick)==null||x.call(s,m),!(s.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Vr(s.onPointerMove,h8(m=>{i.onItemEnter(m),!m.defaultPrevented&&!s.disabled&&!r.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{r.onOpenChange(!0),h()},100))})),onPointerLeave:Vr(s.onPointerLeave,h8(m=>{var y,v;h();const x=(y=r.content)==null?void 0:y.getBoundingClientRect();if(x){const w=(v=r.content)==null?void 0:v.dataset.side,b=w==="right",N=b?-5:5,S=x[b?"left":"right"],T=x[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+N,y:m.clientY},{x:S,y:x.top},{x:T,y:x.top},{x:T,y:x.bottom},{x:S,y:x.bottom}],side:w}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Vr(s.onKeyDown,m=>{var y;const x=i.searchRef.current!=="";s.disabled||x&&m.key===" "||ITt[n.dir].includes(m.key)&&(r.onOpenChange(!0),(y=r.content)==null||y.focus(),m.preventDefault())})})})});YXe.displayName=AD;var ZXe="MenuSubContent",XXe=k.forwardRef((s,t)=>{const r=PXe(lg,s.__scopeMenu),{forceMount:n=r.forceMount,...a}=s,i=i5(lg,s.__scopeMenu),l=QF(lg,s.__scopeMenu),o=KXe(ZXe,s.__scopeMenu),c=k.useRef(null),d=Ga(t,c);return e.jsx(u8.Provider,{scope:s.__scopeMenu,children:e.jsx(ru,{present:n||i.open,children:e.jsx(u8.Slot,{scope:s.__scopeMenu,children:e.jsx(RCe,{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:h=>{var m;l.isUsingKeyboardRef.current&&((m=c.current)==null||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:Vr(s.onFocusOutside,h=>{h.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Vr(s.onEscapeKeyDown,h=>{l.onClose(),h.preventDefault()}),onKeyDown:Vr(s.onKeyDown,h=>{var y;const m=h.currentTarget.contains(h.target),x=LTt[l.dir].includes(h.key);m&&x&&(i.onOpenChange(!1),(y=o.trigger)==null||y.focus(),h.preventDefault())})})})})})});XXe.displayName=ZXe;function QXe(s){return s?"open":"closed"}function vde(s){return s==="indeterminate"}function BCe(s){return vde(s)?"indeterminate":s?"checked":"unchecked"}function JTt(s){const t=document.activeElement;for(const r of s)if(r===t||(r.focus(),document.activeElement!==t))return}function eEt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}function tEt(s,t,r){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=r?s.indexOf(r):-1;let l=eEt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==r));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==r?c:void 0}function sEt(s,t){const{x:r,y:n}=s;let a=!1;for(let i=0,l=t.length-1;in!=x>n&&r<(m-d)*(n-h)/(x-h)+d&&(a=!a)}return a}function rEt(s,t){if(!t)return!1;const r={x:s.clientX,y:s.clientY};return sEt(r,t)}function h8(s){return t=>t.pointerType==="mouse"?s(t):void 0}var nEt=LXe,aEt=LCe,iEt=DXe,oEt=RXe,lEt=OCe,cEt=OXe,dEt=sfe,uEt=BXe,hEt=$Xe,mEt=qXe,fEt=HXe,pEt=GXe,xEt=WXe,gEt=YXe,yEt=XXe,rfe="DropdownMenu",[vEt,wUs]=pd(rfe,[MXe]),jf=MXe(),[bEt,JXe]=vEt(rfe),eQe=s=>{const{__scopeDropdownMenu:t,children:r,dir:n,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=jf(t),d=k.useRef(null),[h,m]=Sh({prop:a,defaultProp:i??!1,onChange:l,caller:rfe});return e.jsx(bEt,{scope:t,triggerId:Yu(),triggerRef:d,contentId:Yu(),open:h,onOpenChange:m,onOpenToggle:k.useCallback(()=>m(x=>!x),[m]),modal:o,children:e.jsx(nEt,{...c,open:h,onOpenChange:m,dir:n,modal:o,children:r})})};eQe.displayName=rfe;var tQe="DropdownMenuTrigger",sQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...a}=s,i=JXe(tQe,r),l=jf(r);return e.jsx(aEt,{asChild:!0,...l,children:e.jsx(wn.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":n?"":void 0,disabled:n,...a,ref:Eb(t,i.triggerRef),onPointerDown:Vr(s.onPointerDown,o=>{!n&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:Vr(s.onKeyDown,o=>{n||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});sQe.displayName=tQe;var _Et="DropdownMenuPortal",rQe=s=>{const{__scopeDropdownMenu:t,...r}=s,n=jf(t);return e.jsx(iEt,{...n,...r})};rQe.displayName=_Et;var nQe="DropdownMenuContent",aQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=JXe(nQe,r),i=jf(r),l=k.useRef(!1);return e.jsx(oEt,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...n,ref:t,onCloseAutoFocus:Vr(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:Vr(s.onInteractOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,h=c.button===2||d;(!a.modal||h)&&(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)"}})});aQe.displayName=nQe;var wEt="DropdownMenuGroup",jEt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(lEt,{...a,...n,ref:t})});jEt.displayName=wEt;var NEt="DropdownMenuLabel",iQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(cEt,{...a,...n,ref:t})});iQe.displayName=NEt;var kEt="DropdownMenuItem",oQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(dEt,{...a,...n,ref:t})});oQe.displayName=kEt;var SEt="DropdownMenuCheckboxItem",lQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(uEt,{...a,...n,ref:t})});lQe.displayName=SEt;var CEt="DropdownMenuRadioGroup",TEt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(hEt,{...a,...n,ref:t})});TEt.displayName=CEt;var EEt="DropdownMenuRadioItem",cQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(mEt,{...a,...n,ref:t})});cQe.displayName=EEt;var AEt="DropdownMenuItemIndicator",dQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(fEt,{...a,...n,ref:t})});dQe.displayName=AEt;var MEt="DropdownMenuSeparator",uQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(pEt,{...a,...n,ref:t})});uQe.displayName=MEt;var IEt="DropdownMenuArrow",LEt=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(xEt,{...a,...n,ref:t})});LEt.displayName=IEt;var PEt="DropdownMenuSubTrigger",hQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(gEt,{...a,...n,ref:t})});hQe.displayName=PEt;var DEt="DropdownMenuSubContent",mQe=k.forwardRef((s,t)=>{const{__scopeDropdownMenu:r,...n}=s,a=jf(r);return e.jsx(yEt,{...a,...n,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)"}})});mQe.displayName=DEt;var REt=eQe,OEt=sQe,FEt=rQe,fQe=aQe,pQe=iQe,xQe=oQe,gQe=lQe,yQe=cQe,vQe=dQe,bQe=uQe,_Qe=hQe,wQe=mQe;const Fd=REt,Bd=OEt,BEt=k.forwardRef(({className:s,inset:t,children:r,...n},a)=>e.jsxs(_Qe,{ref:a,className:It("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),...n,children:[r,e.jsx(va,{className:"ml-auto h-4 w-4"})]}));BEt.displayName=_Qe.displayName;const zEt=k.forwardRef(({className:s,...t},r)=>e.jsx(wQe,{ref:r,className:It("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}));zEt.displayName=wQe.displayName;const xd=k.forwardRef(({className:s,sideOffset:t=4,...r},n)=>e.jsx(FEt,{children:e.jsx(fQe,{ref:n,sideOffset:t,className:It("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),...r})}));xd.displayName=fQe.displayName;const Pa=k.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(xQe,{ref:n,className:It("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),...r}));Pa.displayName=xQe.displayName;const $Et=k.forwardRef(({className:s,children:t,checked:r,...n},a)=>e.jsxs(gQe,{ref:a,className:It("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:r,...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(vQe,{children:e.jsx(Kn,{className:"h-4 w-4"})})}),t]}));$Et.displayName=gQe.displayName;const UEt=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(yQe,{ref:n,className:It("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),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(vQe,{children:e.jsx(Ld,{className:"h-2 w-2 fill-current"})})}),t]}));UEt.displayName=yQe.displayName;const m8=k.forwardRef(({className:s,inset:t,...r},n)=>e.jsx(pQe,{ref:n,className:It("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...r}));m8.displayName=pQe.displayName;const _v=k.forwardRef(({className:s,...t},r)=>e.jsx(bQe,{ref:r,className:It("-mx-1 my-1 h-px bg-muted",s),...t}));_v.displayName=bQe.displayName;const qEt=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:a,setActingAsSelf:i}=MCe();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(Di,{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(pr,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{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(Di,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Nn,{className:"h-5 w-5",children:[e.jsx(ya,{src:t.avatar_url||void 0}),e.jsx(kn,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Wi,{className:"h-3 w-3"})]})}),e.jsxs(xd,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Pa,{onClick:i,className:"gap-2",children:[e.jsx(Di,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Ge,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(_v,{}),r.map(o=>e.jsxs(Pa,{onClick:()=>n(o),className:"gap-2",children:[e.jsxs(Nn,{className:"h-6 w-6",children:[e.jsx(ya,{src:o.avatar_url||void 0}),e.jsx(kn,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Ge,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Ge,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},Xs=({children:s,requireAdmin:t=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=js(),c=ec();if(a||(t||r)&&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(!n){const d=c.pathname+c.search+c.hash;return d&&d!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",d),e.jsx(K0e,{to:"/auth",replace:!0})}return t&&!l?e.jsx(K0e,{to:"/dashboard",replace:!0}):r&&!o&&!l?e.jsx(K0e,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var zCe={};(function s(t,r,n,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 ye=new OffscreenCanvas(1,1),ce=ye.getContext("2d");ce.fillRect(0,0,1,1);var ve=ye.transferToImageBitmap();ce.createPattern(ve,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ye){var ce=r.exports.Promise,ve=ce!==void 0?ce:t.Promise;return typeof ve=="function"?new ve(ye):(ye(c,c),null)}var h=function(ye,ce){return{transform:function(ve){if(ye)return ve;if(ce.has(ve))return ce.get(ve);var be=new OffscreenCanvas(ve.width,ve.height),Ue=be.getContext("2d");return Ue.drawImage(ve,0,0),ce.set(ve,be),be},clear:function(){ce.clear()}}}(o,new Map),m=function(){var ye=Math.floor(16.666666666666668),ce,ve,be={},Ue=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ce=function(Be){var De=Math.random();return be[De]=requestAnimationFrame(function Ae(He){Ue===He||Ue+ye-1{const{data:t,error:r}=await V.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function HEt(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function GEt(){const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{error:n}=await V.from("celebration_queue").insert({user_id:r.user_id,celebration_type:r.celebration_type,title:r.title,message:r.message||null,points_amount:r.points_amount||null,created_by:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}var nfe="Dialog",[jQe,NQe]=pd(nfe),[WEt,zy]=jQe(nfe),kQe=s=>{const{__scopeDialog:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=k.useRef(null),c=k.useRef(null),[d,h]=Sh({prop:n,defaultProp:a??!1,onChange:i,caller:nfe});return e.jsx(WEt,{scope:t,triggerRef:o,contentRef:c,contentId:Yu(),titleId:Yu(),descriptionId:Yu(),open:d,onOpenChange:h,onOpenToggle:k.useCallback(()=>h(m=>!m),[h]),modal:l,children:r})};kQe.displayName=nfe;var SQe="DialogTrigger",CQe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=zy(SQe,r),i=Ga(t,a.triggerRef);return e.jsx(wn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":qCe(a.open),...n,ref:i,onClick:Vr(s.onClick,a.onOpenToggle)})});CQe.displayName=SQe;var $Ce="DialogPortal",[KEt,TQe]=jQe($Ce,{forceMount:void 0}),EQe=s=>{const{__scopeDialog:t,forceMount:r,children:n,container:a}=s,i=zy($Ce,t);return e.jsx(KEt,{scope:t,forceMount:r,children:k.Children.map(n,l=>e.jsx(ru,{present:r||i.open,children:e.jsx(AI,{asChild:!0,container:a,children:l})}))})};EQe.displayName=$Ce;var bde="DialogOverlay",AQe=k.forwardRef((s,t)=>{const r=TQe(bde,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=zy(bde,s.__scopeDialog);return i.modal?e.jsx(ru,{present:n||i.open,children:e.jsx(ZEt,{...a,ref:t})}):null});AQe.displayName=bde;var YEt=kj("DialogOverlay.RemoveScroll"),ZEt=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=zy(bde,r);return e.jsx(ZF,{as:YEt,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(wn.div,{"data-state":qCe(a.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),T3="DialogContent",MQe=k.forwardRef((s,t)=>{const r=TQe(T3,s.__scopeDialog),{forceMount:n=r.forceMount,...a}=s,i=zy(T3,s.__scopeDialog);return e.jsx(ru,{present:n||i.open,children:i.modal?e.jsx(XEt,{...a,ref:t}):e.jsx(QEt,{...a,ref:t})})});MQe.displayName=T3;var XEt=k.forwardRef((s,t)=>{const r=zy(T3,s.__scopeDialog),n=k.useRef(null),a=Ga(t,r.contentRef,n);return k.useEffect(()=>{const i=n.current;if(i)return Jme(i)},[]),e.jsx(IQe,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Vr(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=r.triggerRef.current)==null||l.focus()}),onPointerDownOutside:Vr(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:Vr(s.onFocusOutside,i=>i.preventDefault())})}),QEt=k.forwardRef((s,t)=>{const r=zy(T3,s.__scopeDialog),n=k.useRef(!1),a=k.useRef(!1);return e.jsx(IQe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(n.current||(o=r.triggerRef.current)==null||o.focus(),i.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),IQe=k.forwardRef((s,t)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=zy(T3,r),c=k.useRef(null),d=Ga(t,c);return Zme(),e.jsxs(e.Fragment,{children:[e.jsx(KF,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(Hj,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":qCe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(eAt,{titleId:o.titleId}),e.jsx(sAt,{contentRef:c,descriptionId:o.descriptionId})]})]})}),UCe="DialogTitle",LQe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=zy(UCe,r);return e.jsx(wn.h2,{id:a.titleId,...n,ref:t})});LQe.displayName=UCe;var PQe="DialogDescription",DQe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=zy(PQe,r);return e.jsx(wn.p,{id:a.descriptionId,...n,ref:t})});DQe.displayName=PQe;var RQe="DialogClose",OQe=k.forwardRef((s,t)=>{const{__scopeDialog:r,...n}=s,a=zy(RQe,r);return e.jsx(wn.button,{type:"button",...n,ref:t,onClick:Vr(s.onClick,()=>a.onOpenChange(!1))})});OQe.displayName=RQe;function qCe(s){return s?"open":"closed"}var FQe="DialogTitleWarning",[JEt,BQe]=njt(FQe,{contentName:T3,titleName:UCe,docsSlug:"dialog"}),eAt=({titleId:s})=>{const t=BQe(FQe),r=`\`${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 k.useEffect(()=>{s&&(document.getElementById(s)||console.error(r))},[r,s]),null},tAt="DialogDescriptionWarning",sAt=({contentRef:s,descriptionId:t})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${BQe(tAt).contentName}}.`;return k.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(n))},[n,s,t]),null},afe=kQe,VCe=CQe,ife=EQe,zI=AQe,$I=MQe,JF=LQe,eB=DQe,tB=OQe;const fs=afe,vi=VCe,rAt=ife,jUs=tB,zQe=k.forwardRef(({className:s,...t},r)=>e.jsx(zI,{ref:r,className:It("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}));zQe.displayName=zI.displayName;const ms=k.forwardRef(({className:s,children:t,overlayClassName:r,...n},a)=>e.jsxs(rAt,{children:[e.jsx(zQe,{className:r}),e.jsxs($I,{ref:a,className:It("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),...n,children:[t,e.jsxs(tB,{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(vr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ms.displayName=$I.displayName;const ys=({className:s,...t})=>e.jsx("div",{className:It("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});ys.displayName="DialogHeader";const an=({className:s,...t})=>e.jsx("div",{className:It("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});an.displayName="DialogFooter";const gs=k.forwardRef(({className:s,...t},r)=>e.jsx(JF,{ref:r,className:It("text-lg font-semibold leading-none tracking-tight",s),...t}));gs.displayName=JF.displayName;const Hr=k.forwardRef(({className:s,...t},r)=>e.jsx(eB,{ref:r,className:It("text-sm text-muted-foreground",s),...t}));Hr.displayName=eB.displayName;const nAt={points_earned:Gi,listing_created:En,deal_closed:wl,custom:Xn},uRe={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"},hRe=()=>{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 aAt(){const{user:s}=js(),t=Xt(),{data:r}=VEt(),n=HEt(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=k.useCallback(()=>{const y=Date.now()+3e3,v={startVelocity:30,spread:360,ticks:60,zIndex:9999},w=(N,S)=>Math.random()*(S-N)+N,b=setInterval(()=>{const N=y-Date.now();if(N<=0){clearInterval(b);return}const S=50*(N/3e3);dRe({...v,particleCount:S,origin:{x:w(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),dRe({...v,particleCount:S,origin:{x:w(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);k.useEffect(()=>{hRe()||r&&r.length>0&&!a&&(i(r[0]),o(!0),setTimeout(c,100))},[r,a,c]);const d=async()=>{if(a){const x=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],y=>(y==null?void 0:y.filter(v=>v.id!==x))??[]),await n.mutateAsync(x)}};if(hRe()||!a)return null;const h=nAt[a.celebration_type]||Xn,m=uRe[a.celebration_type]||uRe.custom;return e.jsx(fs,{open:l,onOpenChange:x=>!x&&d(),children:e.jsxs(ms,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${m} 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 ${m} flex items-center justify-center animate-bounce`,children:e.jsx(h,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(jr,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(jr,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(jr,{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(G,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}const HCe="/assets/levelup-logo-horizontal-DEFNc0ms.png",GCe="/assets/levelup-logo-white-C2RAgAoG.png",iAt="/assets/listings-hero-BI9Ki9Dq.jpg",Ne=k.forwardRef(({className:s,type:t,...r},n)=>e.jsx("input",{type:t,className:It("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:n,...r}));Ne.displayName="Input";var $Qe={exports:{}};(function(s,t){(function(r,n){s.exports=n()})(Zd,function(){let r,n,a;function i(o,c){if(!r)r=c;else if(!n)n=c;else{const d={};r(d),a=c(d);const h="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 = {}; ("+r+")(sharedChunk); ("+n+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([h],{type:"text/javascript"})))}}i(["exports"],function(o){var c=1e-6,d=typeof Float32Array<"u"?Float32Array:Array;function h(g,u){var f=u[0],_=u[1],C=u[2],M=u[3],P=f*M-C*_;return P?(g[0]=M*(P=1/P),g[1]=-_*P,g[2]=-C*P,g[3]=f*P,g):null}function m(){var g=new d(9);return d!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function x(g,u){var f=u[0],_=u[1],C=u[2],M=u[3],P=u[4],B=u[5],U=u[6],W=u[7],ee=u[8];return g[0]=P*ee-B*W,g[1]=C*W-_*ee,g[2]=_*B-C*P,g[3]=B*U-M*ee,g[4]=f*ee-C*U,g[5]=C*M-f*B,g[6]=M*W-P*U,g[7]=_*U-f*W,g[8]=f*P-_*M,g}function y(g,u,f){var _=u[0],C=u[1],M=u[2],P=u[3],B=u[4],U=u[5],W=u[6],ee=u[7],se=u[8],ae=f[0],me=f[1],ge=f[2],we=f[3],Ee=f[4],Fe=f[5],Qe=f[6],Ve=f[7],at=f[8];return g[0]=ae*_+me*P+ge*W,g[1]=ae*C+me*B+ge*ee,g[2]=ae*M+me*U+ge*se,g[3]=we*_+Ee*P+Fe*W,g[4]=we*C+Ee*B+Fe*ee,g[5]=we*M+Ee*U+Fe*se,g[6]=Qe*_+Ve*P+at*W,g[7]=Qe*C+Ve*B+at*ee,g[8]=Qe*M+Ve*U+at*se,g}function v(){var g=new d(16);return d!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function w(g){var u=new d(16);return u[0]=g[0],u[1]=g[1],u[2]=g[2],u[3]=g[3],u[4]=g[4],u[5]=g[5],u[6]=g[6],u[7]=g[7],u[8]=g[8],u[9]=g[9],u[10]=g[10],u[11]=g[11],u[12]=g[12],u[13]=g[13],u[14]=g[14],u[15]=g[15],u}function b(g){return g[0]=1,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=1,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=1,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function N(g,u){var f=u[0],_=u[1],C=u[2],M=u[3],P=u[4],B=u[5],U=u[6],W=u[7],ee=u[8],se=u[9],ae=u[10],me=u[11],ge=u[12],we=u[13],Ee=u[14],Fe=u[15],Qe=f*B-_*P,Ve=f*U-C*P,at=f*W-M*P,ut=_*U-C*B,ft=_*W-M*B,Bt=C*W-M*U,Et=ee*we-se*ge,Ot=ee*Ee-ae*ge,Lt=ee*Fe-me*ge,Pt=se*Ee-ae*we,hs=se*Fe-me*we,bs=ae*Fe-me*Ee,Ts=Qe*bs-Ve*hs+at*Pt+ut*Lt-ft*Ot+Bt*Et;return Ts?(g[0]=(B*bs-U*hs+W*Pt)*(Ts=1/Ts),g[1]=(C*hs-_*bs-M*Pt)*Ts,g[2]=(we*Bt-Ee*ft+Fe*ut)*Ts,g[3]=(ae*ft-se*Bt-me*ut)*Ts,g[4]=(U*Lt-P*bs-W*Ot)*Ts,g[5]=(f*bs-C*Lt+M*Ot)*Ts,g[6]=(Ee*at-ge*Bt-Fe*Ve)*Ts,g[7]=(ee*Bt-ae*at+me*Ve)*Ts,g[8]=(P*hs-B*Lt+W*Et)*Ts,g[9]=(_*Lt-f*hs-M*Et)*Ts,g[10]=(ge*ft-we*at+Fe*Qe)*Ts,g[11]=(se*at-ee*ft-me*Qe)*Ts,g[12]=(B*Ot-P*Pt-U*Et)*Ts,g[13]=(f*Pt-_*Ot+C*Et)*Ts,g[14]=(we*Ve-ge*ut-Ee*Qe)*Ts,g[15]=(ee*ut-se*Ve+ae*Qe)*Ts,g):null}function S(g,u,f){var _=u[0],C=u[1],M=u[2],P=u[3],B=u[4],U=u[5],W=u[6],ee=u[7],se=u[8],ae=u[9],me=u[10],ge=u[11],we=u[12],Ee=u[13],Fe=u[14],Qe=u[15],Ve=f[0],at=f[1],ut=f[2],ft=f[3];return g[0]=Ve*_+at*B+ut*se+ft*we,g[1]=Ve*C+at*U+ut*ae+ft*Ee,g[2]=Ve*M+at*W+ut*me+ft*Fe,g[3]=Ve*P+at*ee+ut*ge+ft*Qe,g[4]=(Ve=f[4])*_+(at=f[5])*B+(ut=f[6])*se+(ft=f[7])*we,g[5]=Ve*C+at*U+ut*ae+ft*Ee,g[6]=Ve*M+at*W+ut*me+ft*Fe,g[7]=Ve*P+at*ee+ut*ge+ft*Qe,g[8]=(Ve=f[8])*_+(at=f[9])*B+(ut=f[10])*se+(ft=f[11])*we,g[9]=Ve*C+at*U+ut*ae+ft*Ee,g[10]=Ve*M+at*W+ut*me+ft*Fe,g[11]=Ve*P+at*ee+ut*ge+ft*Qe,g[12]=(Ve=f[12])*_+(at=f[13])*B+(ut=f[14])*se+(ft=f[15])*we,g[13]=Ve*C+at*U+ut*ae+ft*Ee,g[14]=Ve*M+at*W+ut*me+ft*Fe,g[15]=Ve*P+at*ee+ut*ge+ft*Qe,g}function T(g,u,f){var _,C,M,P,B,U,W,ee,se,ae,me,ge,we=f[0],Ee=f[1],Fe=f[2];return u===g?(g[12]=u[0]*we+u[4]*Ee+u[8]*Fe+u[12],g[13]=u[1]*we+u[5]*Ee+u[9]*Fe+u[13],g[14]=u[2]*we+u[6]*Ee+u[10]*Fe+u[14],g[15]=u[3]*we+u[7]*Ee+u[11]*Fe+u[15]):(C=u[1],M=u[2],P=u[3],B=u[4],U=u[5],W=u[6],ee=u[7],se=u[8],ae=u[9],me=u[10],ge=u[11],g[0]=_=u[0],g[1]=C,g[2]=M,g[3]=P,g[4]=B,g[5]=U,g[6]=W,g[7]=ee,g[8]=se,g[9]=ae,g[10]=me,g[11]=ge,g[12]=_*we+B*Ee+se*Fe+u[12],g[13]=C*we+U*Ee+ae*Fe+u[13],g[14]=M*we+W*Ee+me*Fe+u[14],g[15]=P*we+ee*Ee+ge*Fe+u[15]),g}function A(g,u,f){var _=f[0],C=f[1],M=f[2];return g[0]=u[0]*_,g[1]=u[1]*_,g[2]=u[2]*_,g[3]=u[3]*_,g[4]=u[4]*C,g[5]=u[5]*C,g[6]=u[6]*C,g[7]=u[7]*C,g[8]=u[8]*M,g[9]=u[9]*M,g[10]=u[10]*M,g[11]=u[11]*M,g[12]=u[12],g[13]=u[13],g[14]=u[14],g[15]=u[15],g}function I(g,u,f){var _=Math.sin(f),C=Math.cos(f),M=u[4],P=u[5],B=u[6],U=u[7],W=u[8],ee=u[9],se=u[10],ae=u[11];return u!==g&&(g[0]=u[0],g[1]=u[1],g[2]=u[2],g[3]=u[3],g[12]=u[12],g[13]=u[13],g[14]=u[14],g[15]=u[15]),g[4]=M*C+W*_,g[5]=P*C+ee*_,g[6]=B*C+se*_,g[7]=U*C+ae*_,g[8]=W*C-M*_,g[9]=ee*C-P*_,g[10]=se*C-B*_,g[11]=ae*C-U*_,g}function D(g,u,f){var _=Math.sin(f),C=Math.cos(f),M=u[0],P=u[1],B=u[2],U=u[3],W=u[8],ee=u[9],se=u[10],ae=u[11];return u!==g&&(g[4]=u[4],g[5]=u[5],g[6]=u[6],g[7]=u[7],g[12]=u[12],g[13]=u[13],g[14]=u[14],g[15]=u[15]),g[0]=M*C-W*_,g[1]=P*C-ee*_,g[2]=B*C-se*_,g[3]=U*C-ae*_,g[8]=M*_+W*C,g[9]=P*_+ee*C,g[10]=B*_+se*C,g[11]=U*_+ae*C,g}function R(g,u,f){var _=Math.sin(f),C=Math.cos(f),M=u[0],P=u[1],B=u[2],U=u[3],W=u[4],ee=u[5],se=u[6],ae=u[7];return u!==g&&(g[8]=u[8],g[9]=u[9],g[10]=u[10],g[11]=u[11],g[12]=u[12],g[13]=u[13],g[14]=u[14],g[15]=u[15]),g[0]=M*C+W*_,g[1]=P*C+ee*_,g[2]=B*C+se*_,g[3]=U*C+ae*_,g[4]=W*C-M*_,g[5]=ee*C-P*_,g[6]=se*C-B*_,g[7]=ae*C-U*_,g}function $(g,u){return g[0]=u[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=u[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=u[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function F(g,u,f){var _,C,M,P=f[0],B=f[1],U=f[2],W=Math.sqrt(P*P+B*B+U*U);return W0&&(M=1/Math.sqrt(M)),g[0]=u[0]*M,g[1]=u[1]*M,g[2]=u[2]*M,g}function Ie(g,u){return g[0]*u[0]+g[1]*u[1]+g[2]*u[2]}function Te(g,u,f){var _=u[0],C=u[1],M=u[2],P=f[0],B=f[1],U=f[2];return g[0]=C*U-M*B,g[1]=M*P-_*U,g[2]=_*B-C*P,g}function xe(g,u,f,_){var C=u[0],M=u[1],P=u[2];return g[0]=C+_*(f[0]-C),g[1]=M+_*(f[1]-M),g[2]=P+_*(f[2]-P),g}function et(g,u,f){var _=u[0],C=u[1],M=u[2],P=f[3]*_+f[7]*C+f[11]*M+f[15];return g[0]=(f[0]*_+f[4]*C+f[8]*M+f[12])/(P=P||1),g[1]=(f[1]*_+f[5]*C+f[9]*M+f[13])/P,g[2]=(f[2]*_+f[6]*C+f[10]*M+f[14])/P,g}function fe(g,u,f){var _=u[0],C=u[1],M=u[2];return g[0]=_*f[0]+C*f[3]+M*f[6],g[1]=_*f[1]+C*f[4]+M*f[7],g[2]=_*f[2]+C*f[5]+M*f[8],g}function it(g,u,f){var _=f[0],C=f[1],M=f[2],P=f[3],B=u[0],U=u[1],W=u[2],ee=C*W-M*U,se=M*B-_*W,ae=_*U-C*B;return g[0]=B+P*(ee+=ee)+C*(ae+=ae)-M*(se+=se),g[1]=U+P*se+M*ee-_*ae,g[2]=W+P*ae+_*se-C*ee,g}function Oe(g){return g[0]=0,g[1]=0,g[2]=0,g}function Ye(g,u){return g[0]===u[0]&&g[1]===u[1]&&g[2]===u[2]}var We=ie,_e=ye,Re=re;function tt(){var g=new d(4);return d!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Ke(g,u,f){return g[0]=u[0]*f,g[1]=u[1]*f,g[2]=u[2]*f,g[3]=u[3]*f,g}function Ze(g,u){var f=u[0],_=u[1],C=u[2],M=u[3],P=f*f+_*_+C*C+M*M;return P>0&&(P=1/Math.sqrt(P)),g[0]=f*P,g[1]=_*P,g[2]=C*P,g[3]=M*P,g}function lt(g,u){return g[0]*u[0]+g[1]*u[1]+g[2]*u[2]+g[3]*u[3]}function xt(g,u,f){var _=u[0],C=u[1],M=u[2],P=u[3];return g[0]=f[0]*_+f[4]*C+f[8]*M+f[12]*P,g[1]=f[1]*_+f[5]*C+f[9]*M+f[13]*P,g[2]=f[2]*_+f[6]*C+f[10]*M+f[14]*P,g[3]=f[3]*_+f[7]*C+f[11]*M+f[15]*P,g}function Xe(){var g=new d(4);return d!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function Je(g){return g[0]=0,g[1]=0,g[2]=0,g[3]=1,g}function jt(g,u,f){f*=.5;var _=u[0],C=u[1],M=u[2],P=u[3],B=Math.sin(f),U=Math.cos(f);return g[0]=_*U+P*B,g[1]=C*U+M*B,g[2]=M*U-C*B,g[3]=P*U-_*B,g}function ns(g,u,f){f*=.5;var _=u[0],C=u[1],M=u[2],P=u[3],B=Math.sin(f),U=Math.cos(f);return g[0]=_*U-M*B,g[1]=C*U+P*B,g[2]=M*U+_*B,g[3]=P*U-C*B,g}X(),tt();var Ns,Ys,rs,bt=Ze,cs=(Ns=X(),Ys=le(1,0,0),rs=le(0,1,0),function(g,u,f){var _=Ie(u,f);return _<-.999999?(Te(Ns,Ys,u),Re(Ns)<1e-6&&Te(Ns,rs,u),Le(Ns,Ns),function(C,M,P){P*=.5;var B=Math.sin(P);C[0]=B*M[0],C[1]=B*M[1],C[2]=B*M[2],C[3]=Math.cos(P)}(g,Ns,Math.PI),g):_>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(Te(Ns,u,f),g[0]=Ns[0],g[1]=Ns[1],g[2]=Ns[2],g[3]=1+_,bt(g,g))});function yt(){var g=new d(2);return d!=Float32Array&&(g[0]=0,g[1]=0),g}function is(g,u){var f=new d(2);return f[0]=g,f[1]=u,f}function Bs(g,u,f){return g[0]=u,g[1]=f,g}function ps(g,u,f){return g[0]=u[0]+f[0],g[1]=u[1]+f[1],g}function lr(g,u,f){return g[0]=u[0]-f[0],g[1]=u[1]-f[1],g}function kr(g,u,f){return g[0]=u[0]*f,g[1]=u[1]*f,g}function Lr(g){var u=g[0],f=g[1];return Math.sqrt(u*u+f*f)}function qr(g,u){var f=u[0],_=u[1],C=f*f+_*_;return C>0&&(C=1/Math.sqrt(C)),g[0]=u[0]*C,g[1]=u[1]*C,g}function Ur(g,u){return g[0]*u[0]+g[1]*u[1]}Xe(),Xe(),m();var Mr,Cr,Xr=lr;function Ln(g){return g&&g.__esModule&&Object.prototype.hasOwnProperty.call(g,"default")?g.default:g}yt();var Zs=function(){if(Cr)return Mr;function g(u,f,_,C){this.cx=3*u,this.bx=3*(_-u)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*f,this.by=3*(C-f)-this.cy,this.ay=1-this.cy-this.by,this.p1x=u,this.p1y=f,this.p2x=_,this.p2y=C}return Cr=1,Mr=g,g.prototype={sampleCurveX:function(u){return((this.ax*u+this.bx)*u+this.cx)*u},sampleCurveY:function(u){return((this.ay*u+this.by)*u+this.cy)*u},sampleCurveDerivativeX:function(u){return(3*this.ax*u+2*this.bx)*u+this.cx},solveCurveX:function(u,f){if(f===void 0&&(f=1e-6),u<0)return 0;if(u>1)return 1;for(var _=u,C=0;C<8;C++){var M=this.sampleCurveX(_)-u;if(Math.abs(M)M?B=_:U=_,_=.5*(U-B)+B;return _},solve:function(u,f){return this.sampleCurveY(this.solveCurveX(u,f))}},Mr}(),Yr=Ln(Zs);function ss(g,u){this.x=g,this.y=u}function ta(g,u){if(Array.isArray(g)){if(!Array.isArray(u)||g.length!==u.length)return!1;for(let f=0;f=1)return 1;const u=g*g,f=u*g;return 4*(g<.5?f:3*(g-u)+f-.75)}function zt(g,u,f,_){const C=new Yr(g,u,f,_);return function(M){return C.solve(M)}}const Se=zt(.25,.1,.25,1);function ze(g,u,f){return Math.min(f,Math.max(u,g))}function st(g,u,f){return(f=ze((f-g)/(u-g),0,1))*f*(3-2*f)}function gt(g,u,f){const _=f-u,C=((g-u)%_+_)%_+u;return C===u?f:C}function At(g,u,f){if(!g.length)return f(null,[]);let _=g.length;const C=new Array(g.length);let M=null;g.forEach((P,B)=>{u(P,(U,W)=>{U&&(M=U),C[B]=W,--_===0&&f(M,C)})})}let Ft=1;function Wt(){return Ft++}function Vt(g){return g<=1?1:Math.pow(2,Math.ceil(Math.log2(g)))}function Jt(g,u){g.forEach(f=>{u[f]&&(u[f]=u[f].bind(u))})}function qs(g,u,f){const _={};for(const C in g)_[C]=u.call(this,g[C],C,g);return _}function Cs(g,u,f){const _={};for(const C in g)u.call(this,g[C],C,g)&&(_[C]=g[C]);return _}function xr(g){return Array.isArray(g)?g.map(xr):typeof g=="object"&&g?qs(g,xr):g}function Wr(g,u){for(let f=0;f=0)return!0;return!1}const tn={};function Rr(g){tn[g]||(typeof console<"u"&&console.warn(g),tn[g]=!0)}function sn(g,u,f){return(f.y-g.y)*(u.x-g.x)>(u.y-g.y)*(f.x-g.x)}function rn(g){let u=0;for(let f,_,C=0,M=g.length,P=M-1;C@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(f,_,C,M)=>{const P=C||M;return u[_]=!P||P.toLowerCase(),""}),u["max-age"]){const f=parseInt(u["max-age"],10);isNaN(f)?delete u["max-age"]:u["max-age"]=f}return u}let wo,co=null;function ia(g,u){return[g[4*u],g[4*u+1],g[4*u+2],g[4*u+3]]}function Ji(g,u,f,_){for(;u>1;g[C]<_?u=C+1:f=C}return u}function il(g,u,f,_){for(;u>1;g[C]<=_?u=C+1:f=C}return u}function bi(g){return g>0?1/(1.001-g):1+g}function eo(g){return g>0?1-1/(1.001-g):-g}function no(g,u,f){return(g-u.min)*(f.max-f.min)/(u.max-u.min)+f.min}const ba={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(!ba.API_URL)return null;try{const g=new URL(ba.API_URL);return g.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":g.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 ir(){return new URL(ba.DRACO_URL,ba.API_URL).href}function ra(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(wo===void 0){if(typeof WebAssembly!="object")return!1;const g=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]);wo=WebAssembly.validate(g)}return wo}()?ba.MESHOPT_SIMD_URL:ba.MESHOPT_URL,ba.API_URL).href}function Ci(){return new URL(ba.BUILDING_GEN_URL,ba.API_URL).href}function qo(g){return ba.API_URL_REGEX.test(g)}function Xo(g){return ba.API_SPRITE_REGEX.test(g)}let ol,Kc,nu,Nf,Ah,kf;function am(){return ol==null&&(ol=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),ol}const ju={now:()=>Nf!==void 0?Nf:performance.now(),setNow(g){Nf=g},restoreNow(){Nf=void 0},frame(g){const u=requestAnimationFrame(g);return{cancel:()=>cancelAnimationFrame(u)}},getImageData(g,u=0){const{width:f,height:_}=g;Ah||(Ah=document.createElement("canvas"));const C=Ah.getContext("2d",{willReadFrequently:!0});if(!C)throw new Error("failed to create canvas 2d context");return(f>Ah.width||_>Ah.height)&&(Ah.width=f,Ah.height=_),C.clearRect(-u,-u,f+2*u,_+2*u),C.drawImage(g,0,0,f,_),C.getImageData(-u,-u,f+2*u,_+2*u)},resolveURL:g=>(Kc||(Kc=document.createElement("a")),Kc.href=g,Kc.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(nu==null&&(nu=window.matchMedia("(prefers-reduced-motion: reduce)")),nu.matches)},hasCanvasFingerprintNoise(){if(kf!==void 0)return kf;if(!am())return kf=!1,!1;const g=new OffscreenCanvas(85,1),u=g.getContext("2d",{willReadFrequently:!0});let f=0;for(let C=0;C0?`?${M}`:""}`}const Im="mapbox-tiles";let Kv=500,Zb=50;const Wy=["language","worldview","jobid"];let Nu;function Cg(){try{return caches}catch{}}function lp(){const g=Cg();g&&Nu==null&&(Nu=g.open(Im))}let f2=1/0;const Lm={supported:!1,testSupport:function(g){!au&&cp&&(ku?zd(g):Mh=g)}};let Mh,cp,au=!1,ku=!1;const Yv=typeof self<"u"?self:{};function zd(g){const u=g.createTexture();g.bindTexture(g.TEXTURE_2D,u);try{if(g.texImage2D(g.TEXTURE_2D,0,g.RGBA,g.RGBA,g.UNSIGNED_BYTE,cp),g.isContextLost())return;Lm.supported=!0}catch{}g.deleteTexture(u),au=!0}Yv.document&&(cp=Yv.document.createElement("img"),cp.onload=function(){Mh&&zd(Mh),Mh=null,ku=!0},cp.onerror=function(){au=!0,Mh=null},cp.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const Zv={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(Zv);class p2 extends Error{constructor(u,f,_){f===401&&qo(_)&&(u+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(u),this.status=f,this.url=_}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Tg(g){return typeof g=="object"&&g!==null&&"status"in g&&g.status===404}const qa=fa()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Ky=function(g,u){return/^file:/.test(f=g.url)||/^file:/.test(qa())&&!/^\w+:/.test(f)?function(_,C){const M=new XMLHttpRequest;M.open(_.method||"GET",_.url,!0),_.type==="arrayBuffer"&&(M.responseType="arraybuffer");for(const P in _.headers)M.setRequestHeader(P,_.headers[P]);return _.type==="json"&&(M.responseType="text",M.setRequestHeader("Accept","application/json")),M.withCredentials=_.credentials==="include",M.onerror=()=>{C(new Error(M.statusText))},M.onload=()=>{if((M.status>=200&&M.status<300||M.status===0)&&M.response!==null){let P=M.response;if(_.type==="json")try{P=JSON.parse(M.response)}catch(U){return C(U)}const B=new Headers;M.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(U=>{const W=U.split(": "),ee=W.shift(),se=W.join(": ");B.append(ee,se)}),C(null,P,B)}else C(new p2(M.statusText,M.status,_.url))},M.send(_.body),{cancel:()=>M.abort()}}(g,u):function(_,C){const M=new AbortController,P=new Request(_.url,{method:_.method||"GET",body:_.body,credentials:_.credentials,headers:_.headers,referrer:qa(),referrerPolicy:_.referrerPolicy,signal:M.signal});let B=!1,U=!1;const W=(ee=P.url).indexOf("sku=")>0&&qo(ee);var ee;_.type==="json"&&P.headers.set("Accept","application/json");const se=(me,ge,we)=>{if(U)return;if(me&&me.message!=="SecurityError"&&Rr(me.toString()),ge&&we)return ae(ge);const Ee=Date.now();fetch(P).then(Fe=>{if(Fe.ok){const Qe=W?Fe.clone():null;return ae(Fe,Qe,Ee)}return C(new p2(Fe.statusText,Fe.status,_.url))}).catch(Fe=>{Fe.name!=="AbortError"&&C(new Error(`${Fe.message} ${_.url}`))})},ae=(me,ge,we)=>{(_.type==="arrayBuffer"?me.arrayBuffer():_.type==="json"?me.json():me.text()).then(Ee=>{U||(ge&&we&&function(Fe,Qe,Ve){if(lp(),Nu==null)return;const at=go(Qe.headers.get("cache-control")||"");if(at["no-store"])return;const ut={status:Qe.status,statusText:Qe.statusText,headers:new Headers};Qe.headers.forEach((Lt,Pt)=>ut.headers.set(Pt,Lt)),at["max-age"]&&ut.headers.set("Expires",new Date(Ve+1e3*at["max-age"]).toUTCString());const ft=ut.headers.get("expires");if(!ft||new Date(ft).getTime()-Ve<42e4)return;let Bt=m2(Fe.url,{persistentParams:Wy});if(Qe.status===206){const Lt=Fe.headers.get("Range");if(!Lt)return;ut.status=200,Bt=Wv(Bt,{range:Lt})}const Et=new Response((Ot=Qe.status)!==200&&Ot!==404&&[101,103,204,205,304].includes(Ot)?null:Qe.body,ut);var Ot;lp(),Nu!=null&&Nu.then(Lt=>Lt.put(Bt,Et)).catch(Lt=>Rr(Lt.message))}(P,ge,we),B=!0,C(null,Ee,me.headers))}).catch(Ee=>{U||C(new Error(Ee.message))})};return W?function(me,ge){if(lp(),Nu==null)return ge(null);Nu.then(we=>{let Ee=m2(me.url,{persistentParams:Wy});const Fe=me.headers.get("Range");Fe&&(Ee=Wv(Ee,{range:Fe})),we.match(Ee).then(Qe=>{const Ve=function(at){if(!at)return!1;const ut=new Date(at.headers.get("expires")||0),ft=go(at.headers.get("cache-control")||"");return Number(ut)>Date.now()&&!ft["no-cache"]}(Qe);we.delete(Ee).catch(ge),Ve&&we.put(Ee,Qe.clone()).catch(ge),ge(null,Qe,Ve)}).catch(ge)}).catch(ge)}(P,se):se(null,null),{cancel:()=>{U=!0,B||M.abort()}}}(g,u);var f},Yy=function(g,u){return Ky(Object.assign(g,{type:"arrayBuffer"}),u)};function g5(g){const u=document.createElement("a");return u.href=g,u.protocol===location.protocol&&u.host===location.host}let Xb,gx;Xb=[],gx=0;const Eg=function(g,u){if(Lm.supported&&(g.headers||(g.headers={}),g.headers.accept="image/webp,*/*"),gx>=ba.MAX_PARALLEL_IMAGE_REQUESTS){const M={requestParameters:g,callback:u,cancelled:!1,cancel(){this.cancelled=!0}};return Xb.push(M),M}gx++;let f=!1;const _=()=>{if(!f)for(f=!0,gx--;Xb.length&&gx{_(),M?u(M):P&&function(U,W){const ee=new Blob([new Uint8Array(U)],{type:"image/png"});createImageBitmap(ee).then(se=>{W(null,se)}).catch(se=>{W(new Error(`Could not load image because of ${se.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(P,(U,W)=>u(U,W,B))});return{cancel:()=>{C.cancel(),_()}}};var Ag,Qb,y5,Mg={exports:{}},Xv={exports:{}},x2={exports:{}},PL=function(){if(y5)return Mg.exports;y5=1;var g=(Ag||(Ag=1,Xv.exports=function(f,_){var C,M,P,B,U,W,ee,se;for(M=f.length-(C=3&f.length),P=_,U=3432918353,W=461845907,se=0;se>>16)*U&65535)<<16)&4294967295)<<15|ee>>>17))*W+(((ee>>>16)*W&65535)<<16)&4294967295)<<13|P>>>19))+((5*(P>>>16)&65535)<<16)&4294967295))+(((B>>>16)+58964&65535)<<16);switch(ee=0,C){case 3:ee^=(255&f.charCodeAt(se+2))<<16;case 2:ee^=(255&f.charCodeAt(se+1))<<8;case 1:P^=ee=(65535&(ee=(ee=(65535&(ee^=255&f.charCodeAt(se)))*U+(((ee>>>16)*U&65535)<<16)&4294967295)<<15|ee>>>17))*W+(((ee>>>16)*W&65535)<<16)&4294967295}return P^=f.length,P=2246822507*(65535&(P^=P>>>16))+((2246822507*(P>>>16)&65535)<<16)&4294967295,P=3266489909*(65535&(P^=P>>>13))+((3266489909*(P>>>16)&65535)<<16)&4294967295,(P^=P>>>16)>>>0}),Xv.exports),u=(Qb||(Qb=1,x2.exports=function(f,_){for(var C,M=f.length,P=_^M,B=0;M>=4;)C=1540483477*(65535&(C=255&f.charCodeAt(B)|(255&f.charCodeAt(++B))<<8|(255&f.charCodeAt(++B))<<16|(255&f.charCodeAt(++B))<<24))+((1540483477*(C>>>16)&65535)<<16),P=1540483477*(65535&P)+((1540483477*(P>>>16)&65535)<<16)^(C=1540483477*(65535&(C^=C>>>24))+((1540483477*(C>>>16)&65535)<<16)),M-=4,++B;switch(M){case 3:P^=(255&f.charCodeAt(B+2))<<16;case 2:P^=(255&f.charCodeAt(B+1))<<8;case 1:P=1540483477*(65535&(P^=255&f.charCodeAt(B)))+((1540483477*(P>>>16)&65535)<<16)}return P=1540483477*(65535&(P^=P>>>13))+((1540483477*(P>>>16)&65535)<<16),(P^=P>>>15)>>>0}),x2.exports);return Mg.exports=g,Mg.exports.murmur3=g,Mg.exports.murmur2=u,Mg.exports}(),yx=Ln(PL);class Pm{constructor(u,...f){Object.assign(this,f[0]||{}),this.type=u}}class Zy extends Pm{constructor(u,f={}){super("error",Object.assign({error:u},f))}}function Ih(g,u,f){f[g]&&f[g].indexOf(u)!==-1||(f[g]=f[g]||[],f[g].push(u))}function Jb(g,u,f){if(f&&f[g]){const _=f[g].indexOf(u);_!==-1&&f[g].splice(_,1)}}class Qv{on(u,f){return this._listeners=this._listeners||{},Ih(u,f,this._listeners),this}off(u,f){return Jb(u,f,this._listeners),Jb(u,f,this._oneTimeListeners),this}once(u,f){return f?(this._oneTimeListeners=this._oneTimeListeners||{},Ih(u,f,this._oneTimeListeners),this):new Promise(_=>{this.once(u,_)})}fire(u,f){const _=typeof u=="string"?new Pm(u,f):u,C=_.type;if(this.listens(C)){_.target=this;const M=this._listeners&&this._listeners[C]?this._listeners[C].slice():[];for(const U of M)U.call(this,_);const P=this._oneTimeListeners&&this._oneTimeListeners[C]?this._oneTimeListeners[C].slice():[];for(const U of P)Jb(C,U,this._oneTimeListeners),U.call(this,_);const B=this._eventedParent;if(B){const U=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(_,U),B.fire(_)}}else _ instanceof Zy&&console.error(_.error);return this}listens(u){return!!(this._listeners&&this._listeners[u]&&this._listeners[u].length>0||this._oneTimeListeners&&this._oneTimeListeners[u]&&this._oneTimeListeners[u].length>0||this._eventedParent&&this._eventedParent.listens(u))}setEventedParent(u,f){return this._eventedParent=u,this._eventedParentData=f,this}}class kt{constructor(u){typeof u=="string"?this.name=u:(this.name=u.name,this.iconsetId=u.iconsetId)}static from(u){return new kt(u)}static toString(u){return u.iconsetId?`${u.name}${u.iconsetId}`:u.name}static parse(u){const[f,_]=u.split("");return new kt({name:f,iconsetId:_})}static isEqual(u,f){return u.name===f.name&&u.iconsetId===f.iconsetId}toString(){return kt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var Gs,mr={},An=function(){if(Gs)return mr;Gs=1;var g={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 u(M){return(M=Math.round(M))<0?0:M>255?255:M}function f(M){return u(M[M.length-1]==="%"?parseFloat(M)/100*255:parseInt(M))}function _(M){return(P=M[M.length-1]==="%"?parseFloat(M)/100:parseFloat(M))<0?0:P>1?1:P;var P}function C(M,P,B){return B<0?B+=1:B>1&&(B-=1),6*B<1?M+(P-M)*B*6:2*B<1?P:3*B<2?M+(P-M)*(2/3-B)*6:M}try{mr.parseCSSColor=function(M){var P,B=M.replace(/ /g,"").toLowerCase();if(B in g)return g[B].slice();if(B[0]==="#")return B.length===4?(P=parseInt(B.substr(1),16))>=0&&P<=4095?[(3840&P)>>4|(3840&P)>>8,240&P|(240&P)>>4,15&P|(15&P)<<4,1]:null:B.length===7&&(P=parseInt(B.substr(1),16))>=0&&P<=16777215?[(16711680&P)>>16,(65280&P)>>8,255&P,1]:null;var U=B.indexOf("("),W=B.indexOf(")");if(U!==-1&&W+1===B.length){var ee=B.substr(0,U),se=B.substr(U+1,W-(U+1)).split(","),ae=1;switch(ee){case"rgba":if(se.length!==4)return null;ae=_(se.pop());case"rgb":return se.length!==3?null:[f(se[0]),f(se[1]),f(se[2]),ae];case"hsla":if(se.length!==4)return null;ae=_(se.pop());case"hsl":if(se.length!==3)return null;var me=(parseFloat(se[0])%360+360)%360/360,ge=_(se[1]),we=_(se[2]),Ee=we<=.5?we*(ge+1):we+ge-we*ge,Fe=2*we-Ee;return[u(255*C(Fe,Ee,me+1/3)),u(255*C(Fe,Ee,me)),u(255*C(Fe,Ee,me-1/3)),ae];default:return null}}return null}}catch{}return mr}();class wr{constructor(u,f,_,C=1){this.r=u,this.g=f,this.b=_,this.a=C}static parse(u){if(!u)return;if(u instanceof wr)return u;if(typeof u!="string")return;const f=An.parseCSSColor(u);return f?new wr(f[0]/255,f[1]/255,f[2]/255,f[3]):void 0}toString(){const[u,f,_,C]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*u)},${Math.round(255*f)},${Math.round(255*_)},${C})`}toNonPremultipliedRenderColor(u){const{r:f,g:_,b:C,a:M}=this;return new Ia(u,f,_,C,M)}toPremultipliedRenderColor(u){const{r:f,g:_,b:C,a:M}=this;return new si(u,f*M,_*M,C*M,M)}clone(){return new wr(this.r,this.g,this.b,this.a)}}class Oa{constructor(u,f,_,C,M,P=!1){if(this.premultiplied=!1,this.premultiplied=P,u){const B=u.image.height,U=B*B;this.premultiplied?(f=M===0?0:f/M*(B-1),_=M===0?0:_/M*(B-1),C=M===0?0:C/M*(B-1)):(f*=B-1,_*=B-1,C*=B-1),f=Math.max(0,Math.min(B-1,f)),_=Math.max(0,Math.min(B-1,_)),C=Math.max(0,Math.min(B-1,C));const W=Math.floor(f),ee=Math.floor(_),se=Math.floor(C),ae=Math.ceil(f),me=Math.ceil(_),ge=Math.ceil(C),we=f-W,Ee=_-ee,Fe=C-se,Qe=u.image.data,Ve=4*(W+ee*U+se*B),at=4*(W+ee*U+ge*B),ut=4*(W+me*U+se*B),ft=4*(W+me*U+ge*B),Bt=4*(ae+ee*U+se*B),Et=4*(ae+ee*U+ge*B),Ot=4*(ae+me*U+se*B),Lt=4*(ae+me*U+ge*B);this.r=hn(hn(hn(Qe[Ve],Qe[at],Fe),hn(Qe[ut],Qe[ft],Fe),Ee),hn(hn(Qe[Bt],Qe[Et],Fe),hn(Qe[Ot],Qe[Lt],Fe),Ee),we)/255*(this.premultiplied?M:1),this.g=hn(hn(hn(Qe[Ve+1],Qe[at+1],Fe),hn(Qe[ut+1],Qe[ft+1],Fe),Ee),hn(hn(Qe[Bt+1],Qe[Et+1],Fe),hn(Qe[Ot+1],Qe[Lt+1],Fe),Ee),we)/255*(this.premultiplied?M:1),this.b=hn(hn(hn(Qe[Ve+2],Qe[at+2],Fe),hn(Qe[ut+2],Qe[ft+2],Fe),Ee),hn(hn(Qe[Bt+2],Qe[Et+2],Fe),hn(Qe[Ot+2],Qe[Lt+2],Fe),Ee),we)/255*(this.premultiplied?M:1),this.a=M}else this.r=f,this.g=_,this.b=C,this.a=M}toArray(){const{r:u,g:f,b:_,a:C}=this;return[255*u,255*f,255*_,C]}toHslaArray(){let{r:u,g:f,b:_,a:C}=this;if(this.premultiplied){if(C===0)return[0,0,0,0];const ge=1/C;u*=ge,f*=ge,_*=ge}const M=Math.min(Math.max(u,0),1),P=Math.min(Math.max(f,0),1),B=Math.min(Math.max(_,0),1),U=Math.min(M,P,B),W=Math.max(M,P,B),ee=W-U,se=.5*(U+W);if(ee===0)return[0,0,100*se,C];const ae=se>.5?ee/(2-W-U):ee/(W+U);let me;switch(W){case M:me=60*((P-B)/ee+(Phn(_,u[C],f))}wr.black=new wr(0,0,0,1),wr.white=new wr(1,1,1,1),wr.transparent=new wr(0,0,0,0),wr.red=new wr(1,0,0,1),wr.blue=new wr(0,0,1,1);var Dm=Object.freeze({__proto__:null,array:gd,color:function(g,u,f){return new wr(hn(g.r,u.r,f),hn(g.g,u.g,f),hn(g.b,u.b,f),hn(g.a,u.a,f))},number:hn});class sh extends Error{constructor(u,f){super(f),this.message=f,this.key=u}}class Ig{constructor(u,f=[]){this.parent=u,this.bindings={};for(const[_,C]of f)this.bindings[_]=C}concat(u){return new Ig(this,u)}get(u){if(this.bindings[u])return this.bindings[u];if(this.parent)return this.parent.get(u);throw new Error(`${u} not found in scope.`)}has(u){return!!this.bindings[u]||!!this.parent&&this.parent.has(u)}}const Lg={kind:"null"},Zr={kind:"number"},gi={kind:"string"},_i={kind:"boolean"},rh={kind:"color"},Xy={kind:"object"},wi={kind:"value"},Jv={kind:"collator"},g2={kind:"formatted"},y2={kind:"resolvedImage"};function Su(g,u){return{kind:"array",itemType:g,N:u}}function tc(g){if(g.kind==="array"){const u=tc(g.itemType);return typeof g.N=="number"?`array<${u}, ${g.N}>`:g.itemType.kind==="value"?"array":`array<${u}>`}return g.kind}const tge=[Lg,Zr,gi,_i,rh,g2,Xy,Su(wi),y2];function v2(g,u){if(u.kind==="error")return null;if(g.kind==="array"){if(u.kind==="array"&&(u.N===0&&u.itemType.kind==="value"||!v2(g.itemType,u.itemType))&&(typeof g.N!="number"||g.N===u.N))return null}else{if(g.kind===u.kind)return null;if(g.kind==="value"){for(const f of tge)if(!v2(f,u))return null}}return`Expected ${tc(g)} but found ${tc(u)} instead.`}function DL(g,u){return u.some(f=>f.kind===g.kind)}function e_(g,u){return u.some(f=>f==="null"?g===null:f==="array"?Array.isArray(g):f==="object"?g&&!Array.isArray(g)&&typeof g=="object":f===typeof g)}function Pg(g,u){return g.kind==="array"&&u.kind==="array"?g.N===u.N&&Pg(g.itemType,u.itemType):g.kind===u.kind}class RL{constructor(u,f,_){this.sensitivity=u?f?"variant":"case":f?"accent":"base",this.locale=_,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(u,f){return this.collator.compare(u,f)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class b2{constructor(u,f,_,C,M){this.text=u.normalize?u.normalize():u,this.image=f,this.scale=_,this.fontStack=C,this.textColor=M}}class iu{constructor(u){this.sections=u}static fromString(u){return new iu([new b2(u,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(u=>u.text.length!==0||!!u.image&&u.image.hasPrimary())}static factory(u){return u instanceof iu?u:iu.fromString(u)}toString(){return this.sections.length===0?"":this.sections.map(u=>u.text).join("")}serialize(){const u=["format"];for(const f of this.sections){if(f.image){const C=f.image.getPrimary().id.toString();u.push(["image",C]);continue}u.push(f.text);const _={};f.fontStack&&(_["text-font"]=["literal",f.fontStack.split(",")]),f.scale&&(_["font-scale"]=f.scale),f.textColor&&(_["text-color"]=["rgba"].concat(f.textColor.toNonPremultipliedRenderColor(null).toArray())),u.push(_)}return u}}class Sf{constructor(u,f={}){this.id=kt.from(u),this.params=f.params,this.sx=f.sx||1,this.sy=f.sy||1}toString(){return JSON.stringify(this)}static parse(u){let f,_,C,M;try{({id:f,params:_,sx:C,sy:M}=JSON.parse(u)||{})}catch{return null}return f?new Sf(f,{params:_,sx:C,sy:M}):null}scaleSelf(u,f=u){return this.sx*=u,this.sy*=f,this}}class Lh{constructor(u,f,_,C,M=!1){this.primaryId=kt.from(u),this.primaryOptions=f,_&&(this.secondaryId=kt.from(_)),this.secondaryOptions=C,this.available=M}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Sf(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Sf(this.secondaryId,this.secondaryOptions):null}static from(u){return typeof u=="string"?Lh.build({name:u}):u}static build(u,f,_,C){return!u||typeof u=="object"&&!("name"in u)?null:new Lh(u,_,f,C)}}function KB(g,u,f,_){return typeof g=="number"&&g>=0&&g<=255&&typeof u=="number"&&u>=0&&u<=255&&typeof f=="number"&&f>=0&&f<=255?_===void 0||typeof _=="number"&&_>=0&&_<=1?null:`Invalid rgba value [${[g,u,f,_].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof _=="number"?[g,u,f,_]:[g,u,f]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function t_(g){if(g===null||typeof g=="string"||typeof g=="boolean"||typeof g=="number"||g instanceof wr||g instanceof RL||g instanceof iu||g instanceof Lh)return!0;if(Array.isArray(g)){for(const u of g)if(!t_(u))return!1;return!0}if(typeof g=="object"){for(const u in g)if(!t_(g[u]))return!1;return!0}return!1}function xl(g){if(g===null)return Lg;if(typeof g=="string")return gi;if(typeof g=="boolean")return _i;if(typeof g=="number")return Zr;if(g instanceof wr)return rh;if(g instanceof RL)return Jv;if(g instanceof iu)return g2;if(g instanceof Lh)return y2;if(Array.isArray(g)){const u=g.length;let f;for(const _ of g){const C=xl(_);if(f){if(f===C)continue;f=wi;break}f=C}return Su(f||wi,u)}return Xy}function Tn(g){const u=typeof g;return g===null?"":u==="string"||u==="number"||u==="boolean"?String(g):g instanceof iu||g instanceof Lh||g instanceof wr?g.toString():JSON.stringify(g)}class $r{constructor(u,f){this.type=u,this.value=f}static parse(u,f){if(u.length!==2)return f.error(`'literal' expression requires exactly one argument, but found ${u.length-1} instead.`);if(!t_(u[1]))return f.error("invalid value");const _=u[1];let C=xl(_);const M=f.expectedType;return C.kind!=="array"||C.N!==0||!M||M.kind!=="array"||typeof M.N=="number"&&M.N!==0||(C=M),new $r(C,_)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof wr?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof iu?this.value.serialize():this.value}}class $l{constructor(u){this.name="ExpressionEvaluationError",this.message=u}toJSON(){return this.message}}const Mn={string:gi,number:Zr,boolean:_i,object:Xy};class Rm{constructor(u,f){this.type=u,this.args=f}static parse(u,f){if(u.length<2)return f.error("Expected at least one argument.");let _,C=1;const M=u[0];if(M==="array"){let B,U;if(u.length>2){const W=u[1];if(typeof W!="string"||!(W in Mn)||W==="object")return f.error('The item type argument of "array" must be one of string, number, boolean',1);B=Mn[W],C++}else B=wi;if(u.length>3){if(u[2]!==null&&(typeof u[2]!="number"||u[2]<0||u[2]!==Math.floor(u[2])))return f.error('The length argument to "array" must be a positive integer literal',2);U=u[2],C++}_=Su(B,U)}else _=Mn[M];const P=[];for(;Cu.outputDefined())}serialize(){const u=this.type,f=[u.kind];if(u.kind==="array"){const _=u.itemType;if(_.kind==="string"||_.kind==="number"||_.kind==="boolean"){f.push(_.kind);const C=u.N;(typeof C=="number"||this.args.length>1)&&f.push(C)}}return f.concat(this.args.map(_=>_.serialize()))}}class e1{constructor(u){this.type=g2,this.sections=u}static parse(u,f){if(u.length<2)return f.error("Expected at least one argument.");const _=u[1];if(!Array.isArray(_)&&typeof _=="object")return f.error("First argument must be an image or text section.");const C=[];let M=!1;for(let P=1;P<=u.length-1;++P){const B=u[P];if(M&&typeof B=="object"&&!Array.isArray(B)){M=!1;let U=null;if(B["font-scale"]&&(U=f.parseObjectValue(B["font-scale"],P,"font-scale",Zr),!U))return null;let W=null;if(B["text-font"]&&(W=f.parseObjectValue(B["text-font"],P,"text-font",Su(gi)),!W))return null;let ee=null;if(B["text-color"]&&(ee=f.parseObjectValue(B["text-color"],P,"text-color",rh),!ee))return null;const se=C[C.length-1];se.scale=U,se.font=W,se.textColor=ee}else{const U=f.parse(u[P],P,wi);if(!U)return null;const W=U.type.kind;if(W!=="string"&&W!=="value"&&W!=="null"&&W!=="resolvedImage")return f.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");M=!0,C.push({content:U,scale:null,font:null,textColor:null})}}return new e1(C)}evaluate(u){return new iu(this.sections.map(f=>{const _=f.content.evaluate(u);return Pg(xl(_),y2)?new b2("",_,null,null,null):new b2(Tn(_),null,f.scale?f.scale.evaluate(u):null,f.font?f.font.evaluate(u).join(","):null,f.textColor?f.textColor.evaluate(u):null)}))}eachChild(u){for(const f of this.sections)u(f.content),f.scale&&u(f.scale),f.font&&u(f.font),f.textColor&&u(f.textColor)}outputDefined(){return!1}serialize(){const u=["format"];for(const f of this.sections){u.push(f.content.serialize());const _={};f.scale&&(_["font-scale"]=f.scale.serialize()),f.font&&(_["text-font"]=f.font.serialize()),f.textColor&&(_["text-color"]=f.textColor.serialize()),u.push(_)}return u}}class vn{constructor(u,f,_,C){this._imageWarnHistory={},this.type=y2,this.namePrimary=u,this.nameSecondary=f,_&&(this.paramsPrimary=_.params,this.iconsetIdPrimary=_.iconset?_.iconset.id:void 0),C&&(this.paramsSecondary=C.params,this.iconsetIdSecondary=C.iconset?C.iconset.id:void 0)}static parse(u,f){if(u.length<2)return f.error("Expected two or more arguments.");let _=1;const C=[];function M(){if(_kt.isEqual(P,M)),C.available){const P=C.getSecondary()?C.getSecondary().id:null;P&&(C.available=u.availableImages.some(B=>kt.isEqual(B,P)))}}return C}eachChild(u){if(u(this.namePrimary),this.paramsPrimary)for(const f in this.paramsPrimary)this.paramsPrimary[f]&&u(this.paramsPrimary[f]);if(this.nameSecondary&&(u(this.nameSecondary),this.paramsSecondary))for(const f in this.paramsSecondary)this.paramsSecondary[f]&&u(this.paramsSecondary[f])}outputDefined(){return!1}serializeOptions(u,f){const _={};if(f&&(_.iconset={id:f}),u){_.params={};for(const C in u)u[C]&&(_.params[C]=u[C].serialize())}return Object.keys(_).length>0?_:void 0}serialize(){const u=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const f=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);f&&u.push(f)}if(this.nameSecondary&&(u.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const f=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);f&&u.push(f)}return u}}function _2(g){return b5(g)?"string":w2(g)?"number":j2(g)?"boolean":Array.isArray(g)?"array":g===null?"null":v5(g)?"object":typeof g}function v5(g){return g!=null&&!Array.isArray(g)&&typeof g!="function"&&!(g instanceof String||g instanceof Number||g instanceof Boolean)&&typeof g=="object"}function b5(g){return typeof g=="string"||g instanceof String}function w2(g){return typeof g=="number"||g instanceof Number}function j2(g){return typeof g=="boolean"||g instanceof Boolean}const sge={"to-boolean":_i,"to-color":rh,"to-number":Zr,"to-string":gi};class dp{constructor(u,f){this.type=u,this.args=f}static parse(u,f){if(u.length<2)return f.error("Expected at least one argument.");const _=u[0],C=[];let M=Lg;if(_==="to-array"){if(!Array.isArray(u[1]))return null;const P=u[1].length;if(f.expectedType){if(f.expectedType.kind!=="array")return f.error(`Expected ${f.expectedType.kind} but found array.`);M=Su(f.expectedType.itemType,P)}else{if(!(P>0&&t_(u[1][0])))return null;M=Su(xl(u[1][0]),P)}for(let B=0;B4?`Invalid rbga value ${JSON.stringify(f)}: expected an array containing either three or four numeric values.`:KB(f[0],f[1],f[2],f[3]),!_))return new wr(f[0]/255,f[1]/255,f[2]/255,f[3])}throw new $l(_||`Could not parse color from value '${typeof f=="string"?f:String(JSON.stringify(f))}'`)}if(this.type.kind==="number"){let f=null;for(const _ of this.args){if(f=_.evaluate(u),f===null)return 0;const C=Number(f);if(!isNaN(C))return C}throw new $l(`Could not convert ${JSON.stringify(f)} to number.`)}return this.type.kind==="formatted"?iu.fromString(Tn(this.args[0].evaluate(u))):this.type.kind==="resolvedImage"?Lh.build(Tn(this.args[0].evaluate(u))):this.type.kind==="array"?this.args.map(f=>f.evaluate(u)):Tn(this.args[0].evaluate(u))}eachChild(u){this.args.forEach(u)}outputDefined(){return this.args.every(u=>u.outputDefined())}serialize(){if(this.type.kind==="formatted")return new e1([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new vn(this.args[0]).serialize();const u=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(f=>{u.push(f.serialize())}),u}}const t1=["Unknown","Point","LineString","Polygon"];class N2{constructor(u,f,_){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=u,this.options=f,this.iconImageUseTheme=_}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?t1[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(u){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const u=this.featureDistanceData.center,f=this.featureDistanceData.scale,{x:_,y:C}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(_*f-u[0])+this.featureDistanceData.bearing[1]*(C*f-u[1])}return 0}parseColor(u){let f=this._parseColorCache[u];return f||(f=this._parseColorCache[u]=wr.parse(u)),f}getConfig(u){return this.options?this.options.get(u):null}}class Mc{constructor(u,f,_,C,M){this.name=u,this.type=f,this._evaluate=_,this.args=C,this._overloadIndex=M}evaluate(u){if(!this._evaluate){const f=Mc.definitions[this.name];this._evaluate=Array.isArray(f)?f[2]:f.overloads[this._overloadIndex][1]}return this._evaluate(u,this.args)}eachChild(u){this.args.forEach(u)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(u=>u.serialize()))}static parse(u,f){const _=u[0],C=Mc.definitions[_];if(!C)return f.error(`Unknown expression "${_}". If you wanted a literal array, use ["literal", [...]].`,0);const M=Array.isArray(C)?C[0]:C.type,P=Array.isArray(C)?[[C[1],C[2]]]:C.overloads,B=[];let U=null,W=-1;for(const[ee,se]of P){if(Array.isArray(ee)&&ee.length!==u.length-1)continue;B.push(ee),W++,U=new T5(f.registry,f.path,null,f.scope,void 0,f._scope,f.options,f.iconImageUseTheme);const ae=[];let me=!1;for(let ge=1;geae)).map(Qy).join(" | "),se=[];for(let ae=1;aef;){if(_-f>600){const U=_-f+1,W=u-f+1,ee=Math.log(U),se=.5*Math.exp(2*ee/3),ae=.5*Math.sqrt(ee*se*(U-se)/U)*(W-U/2<0?-1:1);YB(g,u,Math.max(f,Math.floor(u-W*se/U+ae)),Math.min(_,Math.floor(u+(U-W)*se/U+ae)),C)}const M=g[u];let P=f,B=_;for(k2(g,f,u),C(g[_],M)>0&&k2(g,f,_);P0;)B--}C(g[f],M)===0?k2(g,f,B):(B++,k2(g,B,_)),B<=u&&(f=B+1),u<=B&&(_=B-1)}}function k2(g,u,f){const _=g[u];g[u]=g[f],g[f]=_}function w5(g,u){return gu?1:0}function ZB(g){let u=0;for(let f,_,C=0,M=g.length,P=M-1;C=u[2]||g[1]<=u[1]||g[3]>=u[3])}function rge(g,u,f){const _=g[0]-u[0],C=g[1]-u[1],M=g[0]-f[0],P=g[1]-f[1];return _*P-M*C===0&&_*M<=0&&C*P<=0}function OL(g,u,f){return u[1]>g[1]!=f[1]>g[1]&&g[0]<(f[0]-u[0])*(g[1]-u[1])/(f[1]-u[1])+u[0]}function s_(g,u,f=!1){let _=!1;for(let C=0,M=u.length;C0&&B<0||P<0&&B>0}function C2(g,u,f,_){return(C=[_[0]-f[0],_[1]-f[1]])[0]*(M=[u[0]-g[0],u[1]-g[1]])[1]-C[1]*M[0]!==0&&!(!XB(g,u,f,_)||!XB(f,_,g,u));var C,M}function FL(g){const u=new ss(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),f=new ss(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const _ of g[0])u.x>_.x&&(u.x=_.x),u.y>_.y&&(u.y=_.y),f.x<_.x&&(f.x=_.x),f.y<_.y&&(f.y=_.y);return{min:u,max:f}}const Jy=8192;function nge(g,u){const f=(180+g[0])/360,_=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+g[1]*Math.PI/360)))/360,C=Math.pow(2,u.z);return[Math.round(f*C*Jy),Math.round(_*C*Jy)]}function s1(g,u){for(let f=0;ff[2]){const C=.5*_;let M=g[0]-f[0]>C?-_:f[0]-g[0]>C?_:0;M===0&&(M=g[0]-f[2]>C?-_:f[2]-g[0]>C?_:0),g[0]+=M}up(u,g)}function $L(g,u,f,_){const C=Math.pow(2,_.z)*Jy,M=[_.x*Jy,_.y*Jy],P=[];if(!g)return P;for(const B of g)for(const U of B){const W=[U.x+M[0],U.y+M[1]];Cf(W,u,f,C),P.push(W)}return P}function UL(g,u,f,_){const C=Math.pow(2,_.z)*Jy,M=[_.x*Jy,_.y*Jy],P=[];if(!g)return P;for(const U of g){const W=[];for(const ee of U){const se=[ee.x+M[0],ee.y+M[1]];up(u,se),W.push(se)}P.push(W)}if(u[2]-u[0]<=C/2){(B=u)[0]=B[1]=1/0,B[2]=B[3]=-1/0;for(const U of P)for(const W of U)Cf(W,u,f,C)}var B;return P}class e0{constructor(u,f){this.type=_i,this.geojson=u,this.geometries=f}static parse(u,f){if(u.length!==2)return f.error(`'within' expression requires exactly one argument, but found ${u.length-1} instead.`);if(t_(u[1])){const _=u[1];if(_.type==="FeatureCollection")for(let C=0;C<_.features.length;++C){const M=_.features[C].geometry.type;if(M==="Polygon"||M==="MultiPolygon")return new e0(_,_.features[C].geometry)}else if(_.type==="Feature"){const C=_.geometry.type;if(C==="Polygon"||C==="MultiPolygon")return new e0(_,_.geometry)}else if(_.type==="Polygon"||_.type==="MultiPolygon")return new e0(_,_)}return f.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(u){if(u.geometry()!=null&&u.canonicalID()!=null){if(u.geometryType()==="Point")return function(f,_){const C=[1/0,1/0,-1/0,-1/0],M=[1/0,1/0,-1/0,-1/0],P=f.canonicalID();if(!P)return!1;if(_.type==="Polygon"){const B=j5(_.coordinates,M,P),U=$L(f.geometry(),C,M,P);if(!S2(C,M))return!1;for(const W of U)if(!s_(W,B))return!1}if(_.type==="MultiPolygon"){const B=zL(_.coordinates,M,P),U=$L(f.geometry(),C,M,P);if(!S2(C,M))return!1;for(const W of U)if(!s1(W,B))return!1}return!0}(u,this.geometries);if(u.geometryType()==="LineString")return function(f,_){const C=[1/0,1/0,-1/0,-1/0],M=[1/0,1/0,-1/0,-1/0],P=f.canonicalID();if(!P)return!1;if(_.type==="Polygon"){const B=j5(_.coordinates,M,P),U=UL(f.geometry(),C,M,P);if(!S2(C,M))return!1;for(const W of U)if(!QB(W,B))return!1}if(_.type==="MultiPolygon"){const B=zL(_.coordinates,M,P),U=UL(f.geometry(),C,M,P);if(!S2(C,M))return!1;for(const W of U)if(!BL(W,B))return!1}return!0}(u,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}serialize(){return["within",this.geojson]}}const T2={kilometers:1,miles:1e3/1609.344,nauticalmiles:1e3/1852,meters:1e3,metres:1e3,yards:1e3/.9144,feet:1e3/.3048,inches:1e3/.0254},qL=1/298.257223563,VL=qL*(2-qL),r_=Math.PI/180;class n_{static fromTile(u,f,_){const C=Math.PI*(1-2*(u+.5)/Math.pow(2,f)),M=Math.atan(.5*(Math.exp(C)-Math.exp(-C)))/r_;return new n_(M,_)}static get units(){return T2}constructor(u,f){if(u===void 0)throw new Error("No latitude given.");if(f&&!T2[f])throw new Error(`Unknown unit ${f}. Use one of: ${Object.keys(T2).join(", ")}`);const _=6378.137*r_*(f?T2[f]:1),C=Math.cos(u*r_),M=1/(1-VL*(1-C*C)),P=Math.sqrt(M);this.kx=_*P*C,this.ky=_*P*M*(1-VL)}distance(u,f){const _=Om(u[0]-f[0])*this.kx,C=(u[1]-f[1])*this.ky;return Math.sqrt(_*_+C*C)}bearing(u,f){const _=Om(f[0]-u[0])*this.kx;return Math.atan2(_,(f[1]-u[1])*this.ky)/r_}destination(u,f,_){const C=_*r_;return this.offset(u,Math.sin(C)*f,Math.cos(C)*f)}offset(u,f,_){return[u[0]+f/this.kx,u[1]+_/this.ky]}lineDistance(u){let f=0;for(let _=0;_f)return N5(M,P,(f-(_-B))/B)}return u[u.length-1]}pointToSegmentDistance(u,f,_){let[C,M]=f,P=Om(_[0]-C)*this.kx,B=(_[1]-M)*this.ky;if(P!==0||B!==0){const U=(Om(u[0]-C)*this.kx*P+(u[1]-M)*this.ky*B)/(P*P+B*B);U>1?(C=_[0],M=_[1]):U>0&&(C+=P/this.kx*U,M+=B/this.ky*U)}return P=Om(u[0]-C)*this.kx,B=(u[1]-M)*this.ky,Math.sqrt(P*P+B*B)}pointOnLine(u,f){let _=1/0,C=u[0][0],M=u[0][1],P=0,B=0;for(let U=0;U1?(W=u[U+1][0],ee=u[U+1][1]):me>0&&(W+=se/this.kx*me,ee+=ae/this.ky*me)),se=Om(f[0]-W)*this.kx,ae=(f[1]-ee)*this.ky;const ge=se*se+ae*ae;ge<_&&(_=ge,C=W,M=ee,P=U,B=me)}return{point:[C,M],index:P,t:Math.max(0,Math.min(1,B))}}lineSlice(u,f,_){let C=this.pointOnLine(_,u),M=this.pointOnLine(_,f);if(C.index>M.index||C.index===M.index&&C.t>M.t){const W=C;C=M,M=W}const P=[C.point],B=C.index+1,U=M.index;!HL(_[B],P[0])&&B<=U&&P.push(_[B]);for(let W=B+1;W<=U;W++)P.push(_[W]);return HL(_[U],M.point)||P.push(M.point),P}lineSliceAlong(u,f,_){let C=0;const M=[];for(let P=0;P<_.length-1;P++){const B=_[P],U=_[P+1],W=this.distance(B,U);if(C+=W,C>u&&M.length===0&&M.push(N5(B,U,(u-(C-W))/W)),C>=f)return M.push(N5(B,U,(f-(C-W))/W)),M;C>u&&M.push(U)}return M}bufferPoint(u,f){const _=f/this.ky,C=f/this.kx;return[u[0]-C,u[1]-_,u[0]+C,u[1]+_]}bufferBBox(u,f){const _=f/this.ky,C=f/this.kx;return[u[0]-C,u[1]-_,u[2]+C,u[3]+_]}insideBBox(u,f){return Om(u[0]-f[0])>=0&&Om(u[0]-f[2])<=0&&u[1]>=f[1]&&u[1]<=f[3]}}function HL(g,u){return g[0]===u[0]&&g[1]===u[1]}function N5(g,u,f){const _=Om(u[0]-g[0]);return[g[0]+_*f,g[1]+(u[1]-g[1])*f]}function Om(g){for(;g<-180;)g+=360;for(;g>180;)g-=360;return g}class E2{constructor(u=[],f=(_,C)=>_C?1:0){if(this.data=u,this.length=this.data.length,this.compare=f,this.length>0)for(let _=(this.length>>1)-1;_>=0;_--)this._down(_)}push(u){this.data.push(u),this._up(this.length++)}pop(){if(this.length===0)return;const u=this.data[0],f=this.data.pop();return--this.length>0&&(this.data[0]=f,this._down(0)),u}peek(){return this.data[0]}_up(u){const{data:f,compare:_}=this,C=f[u];for(;u>0;){const M=u-1>>1,P=f[M];if(_(C,P)>=0)break;f[u]=P,u=M}f[u]=C}_down(u){const{data:f,compare:_}=this,C=this.length>>1,M=f[u];for(;u=0)break;f[u]=f[P],u=P}f[u]=M}}var fr=8192;function JB(g,u){return u.dist-g.dist}function ez(g){const u=[1/0,1/0,-1/0,-1/0];if(u.length!==g.length)return!1;for(let f=0;f=g[0]&&g[1]g[1])return[null,null];const f=r1(g);if(u){if(f===2)return[g,null];const _=Math.floor(f/2);return[[g[0],g[0]+_],[g[0]+_,g[1]]]}{if(f===1)return[g,null];const _=Math.floor(f/2)-1;return[[g[0],g[0]+_],[g[0]+_+1,g[1]]]}}function t0(g,u){const f=[1/0,1/0,-1/0,-1/0];if(!hp(u,g.length))return f;for(let _=u[0];_<=u[1];++_)up(f,g[_]);return f}function A2(g){const u=[1/0,1/0,-1/0,-1/0];for(let f=0;fu[2]&&(_=g[0]-u[2]),g[1]>u[3]&&(C=g[1]-u[3]),g[3]=_)return _;if(S2(C,M)){if(az(g,u))return 0}else if(az(u,g))return 0;let P=_;for(const B of g)for(let U=0,W=B.length,ee=W-1;U=M)continue;const ee=W.range1;if(r1(ee)<=B){if(!hp(ee,g.length))return NaN;if(u){const se=Mo(g,ee,f,_);if((M=Math.min(M,se))===0)return M}else for(let se=ee[0];se<=ee[1];++se){const ae=lge(g[se],f,_);if((M=Math.min(M,ae))===0)return M}}else{const se=a_(ee,u);if(se[0]!==null){const ae=i_(t0(g,se[0]),U,_);ae=P)continue;const se=ee.range1,ae=ee.range2;if(r1(se)<=U&&r1(ae)<=W){if(!hp(se,g.length)||!hp(ae,f.length))return NaN;if(u&&_?P=Math.min(P,oge(g,se,f,ae,C)):u||_?u&&!_?P=Math.min(P,rz(f,ae,g,se,C)):!u&&_&&(P=Math.min(P,rz(g,se,f,ae,C))):P=Math.min(P,nz(g,se,f,ae,C)),P===0)return P}else{const me=a_(se,u),ge=a_(ae,_);k5(B,P,C,g,f,me[0],ge[0]),k5(B,P,C,g,f,me[0],ge[1]),k5(B,P,C,g,f,me[1],ge[0]),k5(B,P,C,g,f,me[1],ge[1])}}return P}function WL(g,u,f,_,C=1/0){let M=C;const P=t0(g,[0,g.length-1]);for(const B of f)if(!(M!==1/0&&i_(P,t0(B,[0,B.length-1]),_)>=M)&&(M=Math.min(M,iz(g,u,B,!0,_,M)),M===0))return M;return M}function S5(g,u,f,_,C=1/0){let M=C;const P=t0(g,[0,g.length-1]);for(const B of f){if(M!==1/0&&i_(P,A2(B),_)>=M)continue;const U=dge(g,u,B,_,M);if(isNaN(U))return U;if((M=Math.min(M,U))===0)return M}return M}function KL(g){return g==="Point"||g==="MultiPoint"||g==="LineString"||g==="MultiLineString"||g==="Polygon"||g==="MultiPolygon"}class n1{constructor(u,f){this.type=Zr,this.geojson=u,this.geometries=f}static parse(u,f){if(u.length!==2)return f.error(`'distance' expression requires either one argument, but found ' ${u.length-1} instead.`);if(t_(u[1])){const _=u[1];if(_.type==="FeatureCollection"){for(let C=0;C<_.features.length;++C)if(KL(_.features[C].geometry.type))return new n1(_,_.features[C].geometry)}else if(_.type==="Feature"){if(KL(_.geometry.type))return new n1(_,_.geometry)}else if(KL(_.type))return new n1(_,_)}return f.error("'distance' expression needs to be an array with format ['Distance', GeoJSONObj].")}evaluate(u){const f=u.geometry(),_=u.canonicalID();if(f!=null&&_!=null){if(u.geometryType()==="Point")return function(C,M,P){const B=[];for(const W of C)for(const ee of W)B.push(Dg(ee,M));const U=new n_(B[0][1],"meters");return P.type==="Point"||P.type==="MultiPoint"||P.type==="LineString"?iz(B,!1,P.type==="Point"?[P.coordinates]:P.coordinates,P.type==="LineString",U):P.type==="MultiLineString"?WL(B,!1,P.coordinates,U):P.type==="Polygon"||P.type==="MultiPolygon"?S5(B,!1,P.type==="Polygon"?[P.coordinates]:P.coordinates,U):null}(f,_,this.geometries);if(u.geometryType()==="LineString")return function(C,M,P){const B=[];for(const W of C){const ee=[];for(const se of W)ee.push(Dg(se,M));B.push(ee)}const U=new n_(B[0][0][1],"meters");if(P.type==="Point"||P.type==="MultiPoint"||P.type==="LineString")return WL(P.type==="Point"?[P.coordinates]:P.coordinates,P.type==="LineString",B,U);if(P.type==="MultiLineString"){let W=1/0;for(let ee=0;ee{u&&!a1(f)&&(u=!1)}),u}function o_(g){if(g instanceof Mc&&g.name==="feature-state")return!1;let u=!0;return g.eachChild(f=>{u&&!o_(f)&&(u=!1)}),u}function vx(g,u){if(g instanceof Mc&&u.indexOf(g.name)>=0)return!1;let f=!0;return g.eachChild(_=>{f&&!vx(_,u)&&(f=!1)}),f}function oz(g,u,f){return[g,u,f].filter(Boolean).join("")}function YL(g,u){switch(g){case"string":return Tn(u);case"number":return+u;case"boolean":return!!u;case"color":return wr.parse(u);case"formatted":return iu.fromString(Tn(u));case"resolvedImage":return Lh.build(Tn(u))}return u}function lz(g,u,f,_){return _!==void 0&&(g=_*Math.round(g/_)),u!==void 0&&gf&&(g=f),g}class l_{constructor(u,f,_,C=!1){this.type=u,this.key=f,this.scope=_,this.featureConstant=C}static parse(u,f){let _=f.expectedType;if(_==null&&(_=wi),u.length<2||u.length>3)return f.error("Invalid number of arguments for 'config' expression.");const C=f.parse(u[1],1);if(!(C instanceof $r))return f.error("Key name of 'config' expression must be a string literal.");let M,P=!0;const B=Tn(C.value);if(u.length>=3){const U=f.parse(u[2],2);if(!(U instanceof $r))return f.error("Scope of 'config' expression must be a string literal.");M=Tn(U.value)}if(f.options){const U=oz(B,M,f._scope),W=f.options.get(U);W&&(P=a1(W.value||W.default))}return new l_(_,B,M,P)}evaluate(u){const f=oz(this.key,this.scope,u.scope),_=u.getConfig(f);if(!_)return null;const{type:C,value:M,values:P,minValue:B,maxValue:U,stepValue:W}=_,ee=_.default.evaluate(u);let se=ee;if(M){const ae=u.scope;u.scope=(ae||"").split("").slice(1).join(""),se=M.evaluate(u),u.scope=ae}return C&&(se=YL(C,se)),se===void 0||B===void 0&&U===void 0&&W===void 0||(typeof se=="number"?se=lz(se,B,U,W):Array.isArray(se)&&(se=se.map(ae=>typeof ae=="number"?lz(ae,B,U,W):ae))),M!==void 0&&se!==void 0&&P&&!P.includes(se)&&(se=ee,C&&(se=YL(C,se))),(C&&C!==this.type||se!==void 0&&!Pg(xl(se),this.type))&&(se=YL(this.type.kind,se)),se}eachChild(){}outputDefined(){return!1}serialize(){const u=["config",this.key];return this.scope&&u.concat(this.scope),u}}class C5{constructor(u,f){this.type=f.type,this.name=u,this.boundExpression=f}static parse(u,f){if(u.length!==2||typeof u[1]!="string")return f.error("'var' expression requires exactly one string literal argument.");const _=u[1];return f.scope.has(_)?new C5(_,f.scope.get(_)):f.error(`Unknown variable "${_}". Make sure "${_}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(u){return this.boundExpression.evaluate(u)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class T5{constructor(u,f=[],_,C=new Ig,M=[],P,B,U){this.registry=u,this.path=f,this.key=f.map(W=>typeof W=="string"?`['${W}']`:`[${W}]`).join(""),this.scope=C,this.errors=M,this.expectedType=_,this._scope=P,this.options=B,this.iconImageUseTheme=U}parse(u,f,_,C,M={}){return f||_?this.concat(f,null,_,C)._parse(u,M):this._parse(u,M)}parseObjectValue(u,f,_,C,M,P={}){return this.concat(f,_,C,M)._parse(u,P)}_parse(u,f){function _(C,M,P){return P==="assert"?new Rm(M,[C]):P==="coerce"?new dp(M,[C]):C}if(u!==null&&typeof u!="string"&&typeof u!="boolean"&&typeof u!="number"||(u=["literal",u]),Array.isArray(u)){if(u.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const C=typeof u[0]=="string"?this.registry[u[0]]:void 0;if(C){let M=C.parse(u,this);if(!M)return null;if(this.expectedType){const P=this.expectedType,B=M.type;if(P.kind!=="string"&&P.kind!=="number"&&P.kind!=="boolean"&&P.kind!=="object"&&P.kind!=="array"||B.kind!=="value")if(P.kind!=="color"&&P.kind!=="formatted"&&P.kind!=="resolvedImage"||B.kind!=="value"&&B.kind!=="string"){if(this.checkSubtype(P,B))return null}else M=_(M,P,f.typeAnnotation||"coerce");else M=_(M,P,f.typeAnnotation||"assert")}if(!(M instanceof $r)&&M.type.kind!=="resolvedImage"&&ZL(M)){const P=new N2(this._scope,this.options,this.iconImageUseTheme);try{M=new $r(M.type,M.evaluate(P))}catch(B){return this.error(B.message),null}}return M}return dp.parse(["to-array",u],this)}return this.error(u===void 0?"'undefined' value invalid. Use null instead.":typeof u=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof u} instead.`)}concat(u,f,_,C){let M=typeof u=="number"?this.path.concat(u):this.path;M=typeof f=="string"?M.concat(f):M;const P=C?this.scope.concat(C):this.scope;return new T5(this.registry,M,_||null,P,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(u,...f){const _=`${this.key}${f.map(C=>`[${C}]`).join("")}`;this.errors.push(new sh(_,u))}checkSubtype(u,f){const _=v2(u,f);return _&&this.error(_),_}}function ZL(g){if(g instanceof C5)return ZL(g.boundExpression);if(g instanceof Mc&&g.name==="error"||g instanceof _5||g instanceof e0||g instanceof n1||g instanceof l_)return!1;const u=g instanceof dp||g instanceof Rm;let f=!0;return g.eachChild(_=>{f=u?f&&ZL(_):f&&_ instanceof $r}),!!f&&a1(g)&&vx(g,["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 E5(g,u){const f=g.length-1;let _,C,M=0,P=f,B=0;for(;M<=P;)if(B=Math.floor((M+P)/2),_=g[B],C=g[B+1],_<=u){if(B===f||uu))throw new $l("Input is not a number.");P=B-1}return 0}class M2{constructor(u,f,_){this.type=u,this.input=f,this.labels=[],this.outputs=[];for(const[C,M]of _)this.labels.push(C),this.outputs.push(M)}static parse(u,f){if(u.length-1<4)return f.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if((u.length-1)%2!=0)return f.error("Expected an even number of arguments.");const _=f.parse(u[1],1,Zr);if(!_)return null;const C=[];let M=null;f.expectedType&&f.expectedType.kind!=="value"&&(M=f.expectedType);for(let P=1;P=B)return f.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',W);const se=f.parse(U,ee,M);if(!se)return null;M=M||se.type,C.push([B,se])}return new M2(M,_,C)}evaluate(u){const f=this.labels,_=this.outputs;if(f.length===1)return _[0].evaluate(u);const C=this.input.evaluate(u);if(C<=f[0])return _[0].evaluate(u);const M=f.length;return C>=f[M-1]?_[M-1].evaluate(u):_[E5(f,C)].evaluate(u)}eachChild(u){u(this.input);for(const f of this.outputs)u(f)}outputDefined(){return this.outputs.every(u=>u.outputDefined())}serialize(){const u=["step",this.input.serialize()];for(let f=0;f0&&u.push(this.labels[f]),u.push(this.outputs[f].serialize());return u}}const cz=.95047,dz=1.08883,uz=4/29,c_=6/29,hz=3*c_*c_,uge=c_*c_*c_,hge=Math.PI/180,mge=180/Math.PI;function XL(g){return g>uge?Math.pow(g,1/3):g/hz+uz}function QL(g){return g>c_?g*g*g:hz*(g-uz)}function I2(g){return 255*(g<=.0031308?12.92*g:1.055*Math.pow(g,1/2.4)-.055)}function d_(g){return(g/=255)<=.04045?g/12.92:Math.pow((g+.055)/1.055,2.4)}function JL(g){const u=d_(g.r),f=d_(g.g),_=d_(g.b),C=XL((.4124564*u+.3575761*f+.1804375*_)/cz),M=XL((.2126729*u+.7151522*f+.072175*_)/1);return{l:116*M-16,a:500*(C-M),b:200*(M-XL((.0193339*u+.119192*f+.9503041*_)/dz)),alpha:g.a}}function mz(g){let u=(g.l+16)/116,f=isNaN(g.a)?u:u+g.a/500,_=isNaN(g.b)?u:u-g.b/200;return u=1*QL(u),f=cz*QL(f),_=dz*QL(_),new wr(I2(3.2404542*f-1.5371385*u-.4985314*_),I2(-.969266*f+1.8760108*u+.041556*_),I2(.0556434*f-.2040259*u+1.0572252*_),g.alpha)}function fge(g,u,f){const _=u-g;return g+f*(_>180||_<-180?_-360*Math.round(_/360):_)}const L2={forward:JL,reverse:mz,interpolate:function(g,u,f){return{l:hn(g.l,u.l,f),a:hn(g.a,u.a,f),b:hn(g.b,u.b,f),alpha:hn(g.alpha,u.alpha,f)}}},u_={forward:function(g){const{l:u,a:f,b:_}=JL(g),C=Math.atan2(_,f)*mge;return{h:C<0?C+360:C,c:Math.sqrt(f*f+_*_),l:u,alpha:g.a}},reverse:function(g){const u=g.h*hge,f=g.c;return mz({l:g.l,a:Math.cos(u)*f,b:Math.sin(u)*f,alpha:g.alpha})},interpolate:function(g,u,f){return{h:fge(g.h,u.h,f),c:hn(g.c,u.c,f),l:hn(g.l,u.l,f),alpha:hn(g.alpha,u.alpha,f)}}};var eP=Object.freeze({__proto__:null,hcl:u_,lab:L2});class ou{constructor(u,f,_,C,M){this.type=u,this.operator=f,this.interpolation=_,this.input=C,this.labels=[],this.outputs=[];for(const[P,B]of M)this.labels.push(P),this.outputs.push(B)}static interpolationFactor(u,f,_,C){let M=0;if(u.name==="exponential")M=A5(f,u.base,_,C);else if(u.name==="linear")M=A5(f,1,_,C);else if(u.name==="cubic-bezier"){const P=u.controlPoints;M=new Yr(P[0],P[1],P[2],P[3]).solve(A5(f,1,_,C))}return M}static parse(u,f){let[_,C,M,...P]=u;if(!Array.isArray(C)||C.length===0)return f.error("Expected an interpolation type expression.",1);if(C[0]==="linear")C={name:"linear"};else if(C[0]==="exponential"){const W=C[1];if(typeof W!="number")return f.error("Exponential interpolation requires a numeric base.",1,1);C={name:"exponential",base:W}}else{if(C[0]!=="cubic-bezier")return f.error(`Unknown interpolation type ${String(C[0])}`,1,0);{const W=C.slice(1);if(W.length!==4||W.some(ee=>typeof ee!="number"||ee<0||ee>1))return f.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);C={name:"cubic-bezier",controlPoints:W}}}if(u.length-1<4)return f.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if(u.length-1>3&&(u.length-1)%2!=0)return f.error("Expected an even number of arguments.");if(M=f.parse(M,2,Zr),!M)return null;const B=[];let U=null;_==="interpolate-hcl"||_==="interpolate-lab"?U=rh:f.expectedType&&f.expectedType.kind!=="value"&&(U=f.expectedType);for(let W=0;W=ee)return f.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',ae);const ge=f.parse(se,me,U);if(!ge)return null;U=U||ge.type,B.push([ee,ge])}return U.kind==="number"||U.kind==="color"||U.kind==="array"&&U.itemType.kind==="number"&&typeof U.N=="number"?new ou(U,_,C,M,B):f.error(`Type ${tc(U)} is not interpolatable.`)}evaluate(u){const f=this.labels,_=this.outputs;if(f.length===1)return _[0].evaluate(u);const C=this.input.evaluate(u);if(C<=f[0])return _[0].evaluate(u);const M=f.length;if(C>=f[M-1])return _[M-1].evaluate(u);const P=E5(f,C),B=ou.interpolationFactor(this.interpolation,C,f[P],f[P+1]),U=_[P].evaluate(u),W=_[P+1].evaluate(u);return this.operator==="interpolate"?Dm[this.type.kind.toLowerCase()](U,W,B):this.operator==="interpolate-hcl"?u_.reverse(u_.interpolate(u_.forward(U),u_.forward(W),B)):L2.reverse(L2.interpolate(L2.forward(U),L2.forward(W),B))}eachChild(u){u(this.input);for(const f of this.outputs)u(f)}outputDefined(){return this.outputs.every(u=>u.outputDefined())}serialize(){let u;u=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const f=[this.operator,u,this.input.serialize()];for(let _=0;_v2(C,B.type));return new P2(P?wi:_,M)}evaluate(u){let f,_=null,C=0;for(const M of this.args){if(C++,_=M.evaluate(u),_&&_ instanceof Lh&&!_.available&&(f||(f=_),_=null,C===this.args.length))return f;if(_!==null)break}return _}eachChild(u){this.args.forEach(u)}outputDefined(){return this.args.every(u=>u.outputDefined())}serialize(){const u=["coalesce"];return this.eachChild(f=>{u.push(f.serialize())}),u}}class M5{constructor(u,f){this.type=f.type,this.bindings=[].concat(u),this.result=f}evaluate(u){return this.result.evaluate(u)}eachChild(u){for(const f of this.bindings)u(f[1]);u(this.result)}static parse(u,f){if(u.length<4)return f.error(`Expected at least 3 arguments, but found ${u.length-1} instead.`);const _=[];for(let M=1;M=_.length)throw new $l("Array index out of bounds: index exceeds array size");if(f!==Math.floor(f))throw new $l("Array index must be an integer. Use at-interpolated for fractional indices");return _[f]}eachChild(u){u(this.index),u(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class R2{constructor(u,f,_){this.type=u,this.index=f,this.input=_}static parse(u,f){if(u.length!==3)return f.error(`Expected 2 arguments, but found ${u.length-1} instead.`);const _=f.parse(u[1],1,Zr),C=f.parse(u[2],2,Su(f.expectedType||wi));return _&&C?new R2(C.type.itemType,_,C):null}evaluate(u){const f=this.index.evaluate(u),_=this.input.evaluate(u);if(f<0)throw new $l(`Array index out of bounds: ${f} < 0.`);if(f>_.length-1)throw new $l(`Array index out of bounds: ${f} > ${_.length-1}.`);if(f===Math.floor(f))return _[f];const C=Math.floor(f),M=Math.ceil(f),P=_[C],B=_[M];if(typeof P!="number"||typeof B!="number")throw new $l(`Cannot interpolate between non-number values at index ${f}.`);const U=f-C;return P*(1-U)+B*U}eachChild(u){u(this.index),u(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class O2{constructor(u,f){this.type=_i,this.needle=u,this.haystack=f}static parse(u,f){if(u.length!==3)return f.error(`Expected 2 arguments, but found ${u.length-1} instead.`),null;const _=f.parse(u[1],1,wi),C=f.parse(u[2],2,wi);return _&&C?DL(_.type,[_i,gi,Zr,Lg,wi])?new O2(_,C):(f.error(`Expected first argument to be of type boolean, string, number or null, but found ${tc(_.type)} instead`),null):null}evaluate(u){const f=this.needle.evaluate(u),_=this.haystack.evaluate(u);if(_==null)return!1;if(!e_(f,["boolean","string","number","null"]))throw new $l(`Expected first argument to be of type boolean, string, number or null, but found ${tc(xl(f))} instead.`);if(!e_(_,["string","array"]))throw new $l(`Expected second argument to be of type array or string, but found ${tc(xl(_))} instead.`);return _.indexOf(f)>=0}eachChild(u){u(this.needle),u(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class I5{constructor(u,f,_){this.type=Zr,this.needle=u,this.haystack=f,this.fromIndex=_}static parse(u,f){if(u.length<=2||u.length>=5)return f.error(`Expected 3 or 4 arguments, but found ${u.length-1} instead.`),null;const _=f.parse(u[1],1,wi),C=f.parse(u[2],2,wi);if(!_||!C)return null;if(!DL(_.type,[_i,gi,Zr,Lg,wi]))return f.error(`Expected first argument to be of type boolean, string, number or null, but found ${tc(_.type)} instead`),null;if(u.length===4){const M=f.parse(u[3],3,Zr);return M?new I5(_,C,M):null}return new I5(_,C)}evaluate(u){const f=this.needle.evaluate(u),_=this.haystack.evaluate(u);if(!e_(f,["boolean","string","number","null"]))throw new $l(`Expected first argument to be of type boolean, string, number or null, but found ${tc(xl(f))} instead.`);if(!e_(_,["string","array"]))throw new $l(`Expected second argument to be of type array or string, but found ${tc(xl(_))} instead.`);if(this.fromIndex){const C=this.fromIndex.evaluate(u);return _.indexOf(f,C)}return _.indexOf(f)}eachChild(u){u(this.needle),u(this.haystack),this.fromIndex&&u(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const u=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),u]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class tP{constructor(u,f,_,C,M,P){this.inputType=u,this.type=f,this.input=_,this.cases=C,this.outputs=M,this.otherwise=P}static parse(u,f){if(u.length<5)return f.error(`Expected at least 4 arguments, but found only ${u.length-1}.`);if(u.length%2!=1)return f.error("Expected an even number of arguments.");let _,C;f.expectedType&&f.expectedType.kind!=="value"&&(C=f.expectedType);const M={},P=[];for(let W=2;WNumber.MAX_SAFE_INTEGER)return ae.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof ge=="number"&&Math.floor(ge)!==ge)return ae.error("Numeric branch labels must be integer values.");if(_){if(ae.checkSubtype(_,xl(ge)))return null}else _=xl(ge);if(M[String(ge)]!==void 0)return ae.error("Branch labels must be unique.");M[String(ge)]=P.length}const me=f.parse(se,W,C);if(!me)return null;C=C||me.type,P.push(me)}const B=f.parse(u[1],1,wi);if(!B)return null;const U=f.parse(u[u.length-1],u.length-1,C);return U?B.type.kind!=="value"&&f.concat(1).checkSubtype(_,B.type)?null:new tP(_,C,B,M,P,U):null}evaluate(u){const f=this.input.evaluate(u);return(Pg(xl(f),this.inputType)&&this.outputs[this.cases[f]]||this.otherwise).evaluate(u)}eachChild(u){u(this.input),this.outputs.forEach(u),u(this.otherwise)}outputDefined(){return this.outputs.every(u=>u.outputDefined())&&this.otherwise.outputDefined()}serialize(){const u=["match",this.input.serialize()],f=Object.keys(this.cases).sort(),_=[],C={};for(const P of f){const B=C[this.cases[P]];B===void 0?(C[this.cases[P]]=_.length,_.push([this.cases[P],[P]])):_[B][1].push(P)}const M=P=>this.inputType.kind==="number"?Number(P):P;for(const[P,B]of _)u.push(B.length===1?M(B[0]):B.map(M)),u.push(this.outputs[P].serialize());return u.push(this.otherwise.serialize()),u}}class L5{constructor(u,f,_){this.type=u,this.branches=f,this.otherwise=_}static parse(u,f){if(u.length<4)return f.error(`Expected at least 3 arguments, but found only ${u.length-1}.`),null;if(u.length%2!=0)return f.error("Expected an odd number of arguments."),null;let _;f.expectedType&&f.expectedType.kind!=="value"&&(_=f.expectedType);const C=[];for(let P=1;Pf.outputDefined())&&this.otherwise.outputDefined()}serialize(){const u=["case"];return this.eachChild(f=>{u.push(f.serialize())}),u}}class F2{constructor(u,f,_,C){this.type=u,this.input=f,this.beginIndex=_,this.endIndex=C}static parse(u,f){if(u.length<=2||u.length>=5)return f.error(`Expected 3 or 4 arguments, but found ${u.length-1} instead.`),null;const _=f.parse(u[1],1,wi),C=f.parse(u[2],2,Zr);if(!_||!C)return null;if(!DL(_.type,[Su(wi),gi,wi]))return f.error(`Expected first argument to be of type array or string, but found ${tc(_.type)} instead`),null;if(u.length===4){const M=f.parse(u[3],3,Zr);return M?new F2(_.type,_,C,M):null}return new F2(_.type,_,C)}evaluate(u){const f=this.input.evaluate(u),_=this.beginIndex.evaluate(u);if(!e_(f,["string","array"]))throw new $l(`Expected first argument to be of type array or string, but found ${tc(xl(f))} instead.`);if(this.endIndex){const C=this.endIndex.evaluate(u);return f.slice(_,C)}return f.slice(_)}eachChild(u){u(this.input),u(this.beginIndex),this.endIndex&&u(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const u=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),u]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class sP{constructor(u,f){this.type=Su(gi),this.str=u,this.delimiter=f}static parse(u,f){if(u.length!==3)return f.error(`Expected 2 arguments, but found ${u.length-1} instead.`);const _=f.parse(u[1],1,gi),C=f.parse(u[2],2,gi);return _&&C?new sP(_,C):void 0}evaluate(u){const f=this.str.evaluate(u),_=this.delimiter.evaluate(u);return f.split(_)}eachChild(u){u(this.str),u(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function fz(g,u){return g==="=="||g==="!="?u.kind==="boolean"||u.kind==="string"||u.kind==="number"||u.kind==="null"||u.kind==="value":u.kind==="string"||u.kind==="number"||u.kind==="value"}function pz(g,u,f,_){return _.compare(u,f)===0}function i1(g,u,f){const _=g!=="=="&&g!=="!=";return class UQe{constructor(M,P,B){this.type=_i,this.lhs=M,this.rhs=P,this.collator=B,this.hasUntypedArgument=M.type.kind==="value"||P.type.kind==="value"}static parse(M,P){if(M.length!==3&&M.length!==4)return P.error("Expected two or three arguments.");const B=M[0];let U=P.parse(M[1],1,wi);if(!U)return null;if(!fz(B,U.type))return P.concat(1).error(`"${B}" comparisons are not supported for type '${tc(U.type)}'.`);let W=P.parse(M[2],2,wi);if(!W)return null;if(!fz(B,W.type))return P.concat(2).error(`"${B}" comparisons are not supported for type '${tc(W.type)}'.`);if(U.type.kind!==W.type.kind&&U.type.kind!=="value"&&W.type.kind!=="value")return P.error(`Cannot compare types '${tc(U.type)}' and '${tc(W.type)}'.`);_&&(U.type.kind==="value"&&W.type.kind!=="value"?U=new Rm(W.type,[U]):U.type.kind!=="value"&&W.type.kind==="value"&&(W=new Rm(U.type,[W])));let ee=null;if(M.length===4){if(U.type.kind!=="string"&&W.type.kind!=="string"&&U.type.kind!=="value"&&W.type.kind!=="value")return P.error("Cannot use collator to compare non-string types.");if(ee=P.parse(M[3],3,Jv),!ee)return null}return new UQe(U,W,ee)}evaluate(M){const P=this.lhs.evaluate(M),B=this.rhs.evaluate(M);if(_&&this.hasUntypedArgument){const U=xl(P),W=xl(B);if(U.kind!==W.kind||U.kind!=="string"&&U.kind!=="number")throw new $l(`Expected arguments for "${g}" to be (string, string) or (number, number), but found (${U.kind}, ${W.kind}) instead.`)}if(this.collator&&!_&&this.hasUntypedArgument){const U=xl(P),W=xl(B);if(U.kind!=="string"||W.kind!=="string")return u(M,P,B)}return this.collator?f(M,P,B,this.collator.evaluate(M)):u(M,P,B)}eachChild(M){M(this.lhs),M(this.rhs),this.collator&&M(this.collator)}outputDefined(){return!0}serialize(){const M=[g];return this.eachChild(P=>{M.push(P.serialize())}),M}}}const xz=i1("==",function(g,u,f){return u===f},pz),P5=i1("!=",function(g,u,f){return u!==f},function(g,u,f,_){return!pz(0,u,f,_)}),pge=i1("<",function(g,u,f){return u",function(g,u,f){return u>f},function(g,u,f,_){return _.compare(u,f)>0}),xge=i1("<=",function(g,u,f){return u<=f},function(g,u,f,_){return _.compare(u,f)<=0}),gge=i1(">=",function(g,u,f){return u>=f},function(g,u,f,_){return _.compare(u,f)>=0});class D5{constructor(u,f,_,C,M,P){this.type=gi,this.number=u,this.locale=f,this.currency=_,this.unit=C,this.minFractionDigits=M,this.maxFractionDigits=P}static parse(u,f){if(u.length!==3)return f.error("Expected two arguments.");const _=f.parse(u[1],1,Zr);if(!_)return null;const C=u[2];if(typeof C!="object"||Array.isArray(C))return f.error("NumberFormat options argument must be an object.");let M=null;if(C.locale&&(M=f.parseObjectValue(C.locale,2,"locale",gi),!M))return null;let P=null;if(C.currency&&(P=f.parseObjectValue(C.currency,2,"currency",gi),!P))return null;let B=null;if(C.unit&&(B=f.parseObjectValue(C.unit,2,"unit",gi),!B))return null;let U=null;if(C["min-fraction-digits"]&&(U=f.parseObjectValue(C["min-fraction-digits"],2,"min-fraction-digits",Zr),!U))return null;let W=null;return C["max-fraction-digits"]&&(W=f.parseObjectValue(C["max-fraction-digits"],2,"max-fraction-digits",Zr),!W)?null:new D5(_,M,P,B,U,W)}evaluate(u){return new Intl.NumberFormat(this.locale?this.locale.evaluate(u):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(u):void 0,unit:this.unit?this.unit.evaluate(u):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(u):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(u):void 0}).format(this.number.evaluate(u))}eachChild(u){u(this.number),this.locale&&u(this.locale),this.currency&&u(this.currency),this.unit&&u(this.unit),this.minFractionDigits&&u(this.minFractionDigits),this.maxFractionDigits&&u(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const u={};return this.locale&&(u.locale=this.locale.serialize()),this.currency&&(u.currency=this.currency.serialize()),this.unit&&(u.unit=this.unit.serialize()),this.minFractionDigits&&(u["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(u["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),u]}}class R5{constructor(u){this.type=Zr,this.input=u}static parse(u,f){if(u.length!==2)return f.error(`Expected 1 argument, but found ${u.length-1} instead.`),null;const _=f.parse(u[1],1);return _?_.type.kind!=="array"&&_.type.kind!=="string"&&_.type.kind!=="value"?(f.error(`Expected argument of type string or array, but found ${tc(_.type)} instead.`),null):new R5(_):null}evaluate(u){const f=this.input.evaluate(u);if(typeof f=="string"||Array.isArray(f))return f.length;throw new $l(`Expected value to be of type string or array, but found ${tc(xl(f))} instead.`)}eachChild(u){u(this.input)}outputDefined(){return!1}serialize(){const u=["length"];return this.eachChild(f=>{u.push(f.serialize())}),u}}function yz(g){return function(){g=1831565813+(g|=0)|0;let u=Math.imul(g^g>>>15,1|g);return u=u+Math.imul(u^u>>>7,61|u)^u,((u^u>>>14)>>>0)/4294967296}}const h_={"==":xz,"!=":P5,">":gz,"<":pge,">=":gge,"<=":xge,array:Rm,at:D2,"at-interpolated":R2,boolean:Rm,case:L5,coalesce:P2,collator:_5,format:e1,image:vn,in:O2,"index-of":I5,interpolate:ou,"interpolate-hcl":ou,"interpolate-lab":ou,length:R5,let:M5,literal:$r,match:tP,number:Rm,"number-format":D5,object:Rm,slice:F2,step:M2,string:Rm,"to-boolean":dp,"to-color":dp,"to-number":dp,"to-string":dp,var:C5,within:e0,distance:n1,config:l_,split:sP};function vz(g,[u,f,_,C]){u=u.evaluate(g),f=f.evaluate(g),_=_.evaluate(g);const M=C?C.evaluate(g):1,P=KB(u,f,_,M);if(P)throw new $l(P);return new wr(u/255,f/255,_/255,M)}function bz(g,[u,f,_,C]){u=u.evaluate(g),f=f.evaluate(g),_=_.evaluate(g);const M=C?C.evaluate(g):1,P=function(W,ee,se,ae){return typeof W=="number"&&W>=0&&W<=360?typeof ee=="number"&&ee>=0&&ee<=100&&typeof se=="number"&&se>=0&&se<=100?ae===void 0||typeof ae=="number"&&ae>=0&&ae<=1?null:`Invalid hsla value [${[W,ee,se,ae].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof ae=="number"?[W,ee,se,ae]:[W,ee,se]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof ae=="number"?[W,ee,se,ae]:[W,ee,se]).join(", ")}]: 'h' must be between 0 and 360.`}(u,f,_,M);if(P)throw new $l(P);const B=`hsla(${u}, ${f}%, ${_}%, ${M})`,U=wr.parse(B);if(!U)throw new $l(`Failed to parse HSLA color: ${B}`);return U}function B2(g,u){return g in u}function O5(g,u){const f=u[g];return f===void 0?null:f}function s0(g){return{type:g}}function F5(g){if(g instanceof l_)return new Set([g.key]);let u=new Set;return g.eachChild(f=>{u=new Set([...u,...F5(f)])}),u}function B5(g){if(g instanceof Mc&&g.name==="is-active-floor")return!0;let u=!1;return g.eachChild(f=>{!u&&B5(f)&&(u=!0)}),u}function _z(g){return{result:"success",value:g}}function r0(g){return{result:"error",value:g}}function z2(g,u){return!!g&&!!g.parameters&&g.parameters.indexOf(u)>-1}function z5(g){return g["property-type"]==="data-driven"}function wz(g){return z2(g.expression,"measure-light")}function rP(g){return z2(g.expression,"zoom")}function $5(g){return!!g.expression&&g.expression.interpolated}function nP(g){return typeof g=="object"&&g!==null&&!Array.isArray(g)}function jz(g){return g}function Nz(g,u){const f=u.type==="color",_=g.stops&&typeof g.stops[0][0]=="object",C=_||!(_||g.property!==void 0),M=g.type||($5(u)?"exponential":"interval");if(f&&((g=Object.assign({},g)).stops&&(g.stops=g.stops.map(W=>[W[0],wr.parse(W[1])])),g.default=wr.parse(g.default?g.default:u.default)),g.colorSpace&&g.colorSpace!=="rgb"&&!eP[g.colorSpace])throw new Error(`Unknown color space: ${g.colorSpace}`);let P,B,U;if(M==="exponential")P=kz;else if(M==="interval")P=vge;else if(M==="categorical"){P=yge,B=Object.create(null);for(const W of g.stops)B[W[0]]=W[1];U=typeof g.stops[0][0]}else{if(M!=="identity")throw new Error(`Unknown function type "${M}"`);P=Sz}if(_){const W={},ee=[];for(let me=0;meme[0]),evaluate:({zoom:me},ge)=>kz({stops:se,base:g.base},u,me).evaluate(me,ge)}}if(C){const W=M==="exponential"?{name:"exponential",base:g.base!==void 0?g.base:1}:null;return{kind:"camera",interpolationType:W,interpolationFactor:ou.interpolationFactor.bind(void 0,W),zoomStops:g.stops.map(ee=>ee[0]),evaluate:({zoom:ee})=>P(g,u,ee,B,U)}}return{kind:"source",evaluate(W,ee){const se=ee&&ee.properties?ee.properties[g.property]:void 0;return se===void 0?bx(g.default,u.default):P(g,u,se,B,U)}}}function bx(g,u,f){return g!==void 0?g:u!==void 0?u:f!==void 0?f:void 0}function yge(g,u,f,_,C){return bx(typeof f===C?_[f]:void 0,g.default,u.default)}function vge(g,u,f){if(!w2(f))return bx(g.default,u.default);const _=g.stops.length;if(_===1||f<=g.stops[0][0])return g.stops[0][1];if(f>=g.stops[_-1][0])return g.stops[_-1][1];const C=E5(g.stops.map(M=>M[0]),f);return g.stops[C][1]}function kz(g,u,f){const _=g.base!==void 0?g.base:1;if(!w2(f))return bx(g.default,u.default);const C=g.stops.length;if(C===1||f<=g.stops[0][0])return g.stops[0][1];if(f>=g.stops[C-1][0])return g.stops[C-1][1];const M=E5(g.stops.map(ee=>ee[0]),f),P=function(ee,se,ae,me){const ge=me-ae,we=ee-ae;return ge===0?0:se===1?we/ge:(Math.pow(se,we)-1)/(Math.pow(se,ge)-1)}(f,_,g.stops[M][0],g.stops[M+1][0]),B=g.stops[M][1],U=g.stops[M+1][1];let W=Dm[u.type]||jz;if(g.colorSpace&&g.colorSpace!=="rgb"){const ee=eP[g.colorSpace];W=(se,ae)=>ee.reverse(ee.interpolate(ee.forward(se),ee.forward(ae),P))}return typeof B.evaluate=="function"?{evaluate(...ee){const se=B.evaluate.apply(void 0,ee),ae=U.evaluate.apply(void 0,ee);if(se!==void 0&&ae!==void 0)return W(se,ae,P)}}:W(B,U,P)}function Sz(g,u,f){return u.type==="color"?f=wr.parse(f):u.type==="formatted"?f=iu.fromString(f.toString()):u.type==="resolvedImage"?f=Lh.build(f.toString()):_2(f)===u.type||u.type==="enum"&&u.values[f]||(f=void 0),bx(f,g.default,u.default)}Mc.register(h_,{error:[{kind:"error"},[gi],(g,[u])=>{throw new $l(u.evaluate(g))}],typeof:[gi,[wi],(g,[u])=>tc(xl(u.evaluate(g)))],"to-rgba":[Su(Zr,4),[rh],(g,[u])=>u.evaluate(g).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Su(Zr,4),[rh],(g,[u])=>u.evaluate(g).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[rh,[Zr,Zr,Zr],vz],rgba:[rh,[Zr,Zr,Zr,Zr],vz],hsl:[rh,[Zr,Zr,Zr],bz],hsla:[rh,[Zr,Zr,Zr,Zr],bz],has:{type:_i,overloads:[[[gi],(g,[u])=>B2(u.evaluate(g),g.properties())],[[gi,Xy],(g,[u,f])=>B2(u.evaluate(g),f.evaluate(g))]]},get:{type:wi,overloads:[[[gi],(g,[u])=>O5(u.evaluate(g),g.properties())],[[gi,Xy],(g,[u,f])=>O5(u.evaluate(g),f.evaluate(g))]]},"feature-state":[wi,[gi],(g,[u])=>O5(u.evaluate(g),g.featureState||{})],properties:[Xy,[],g=>g.properties()],"geometry-type":[gi,[],g=>g.geometryType()],worldview:[gi,[],g=>g.globals.worldview||""],"is-active-floor":[_i,s0(gi),(g,u)=>{if(!(g.globals&&g.globals.activeFloors&&g.globals.activeFloors.size>0))return!1;if(u.length===0)return!0;const f=g.globals.activeFloors;return u.some(_=>{const C=_.evaluate(g);return f.has(C)})}],id:[wi,[],g=>g.id()],zoom:[Zr,[],g=>g.globals.zoom],pitch:[Zr,[],g=>g.globals.pitch||0],"distance-from-center":[Zr,[],g=>g.distanceFromCenter()],"measure-light":[Zr,[gi],(g,[u])=>g.measureLight(u.evaluate(g))],"heatmap-density":[Zr,[],g=>g.globals.heatmapDensity||0],"line-progress":[Zr,[],g=>g.globals.lineProgress||0],"raster-value":[Zr,[],g=>g.globals.rasterValue||0],"raster-particle-speed":[Zr,[],g=>g.globals.rasterParticleSpeed||0],"sky-radial-progress":[Zr,[],g=>g.globals.skyRadialProgress||0],accumulated:[wi,[],g=>g.globals.accumulated===void 0?null:g.globals.accumulated],"+":[Zr,s0(Zr),(g,u)=>{let f=0;for(const _ of u)f+=_.evaluate(g);return f}],"*":[Zr,s0(Zr),(g,u)=>{let f=1;for(const _ of u)f*=_.evaluate(g);return f}],"-":{type:Zr,overloads:[[[Zr,Zr],(g,[u,f])=>u.evaluate(g)-f.evaluate(g)],[[Zr],(g,[u])=>-u.evaluate(g)]]},"/":[Zr,[Zr,Zr],(g,[u,f])=>u.evaluate(g)/f.evaluate(g)],"%":[Zr,[Zr,Zr],(g,[u,f])=>u.evaluate(g)%f.evaluate(g)],ln2:[Zr,[],()=>Math.LN2],pi:[Zr,[],()=>Math.PI],e:[Zr,[],()=>Math.E],"^":[Zr,[Zr,Zr],(g,[u,f])=>Math.pow(u.evaluate(g),f.evaluate(g))],sqrt:[Zr,[Zr],(g,[u])=>Math.sqrt(u.evaluate(g))],log10:[Zr,[Zr],(g,[u])=>Math.log(u.evaluate(g))/Math.LN10],ln:[Zr,[Zr],(g,[u])=>Math.log(u.evaluate(g))],log2:[Zr,[Zr],(g,[u])=>Math.log2(u.evaluate(g))],sin:[Zr,[Zr],(g,[u])=>Math.sin(u.evaluate(g))],cos:[Zr,[Zr],(g,[u])=>Math.cos(u.evaluate(g))],tan:[Zr,[Zr],(g,[u])=>Math.tan(u.evaluate(g))],asin:[Zr,[Zr],(g,[u])=>Math.asin(u.evaluate(g))],acos:[Zr,[Zr],(g,[u])=>Math.acos(u.evaluate(g))],atan:[Zr,[Zr],(g,[u])=>Math.atan(u.evaluate(g))],min:[Zr,s0(Zr),(g,u)=>Math.min(...u.map(f=>f.evaluate(g)))],max:[Zr,s0(Zr),(g,u)=>Math.max(...u.map(f=>f.evaluate(g)))],abs:[Zr,[Zr],(g,[u])=>Math.abs(u.evaluate(g))],round:[Zr,[Zr],(g,[u])=>{const f=u.evaluate(g);return f<0?-Math.round(-f):Math.round(f)}],floor:[Zr,[Zr],(g,[u])=>Math.floor(u.evaluate(g))],ceil:[Zr,[Zr],(g,[u])=>Math.ceil(u.evaluate(g))],"filter-==":[_i,[gi,wi],(g,[u,f])=>g.properties()[u.value]===f.value],"filter-id-==":[_i,[wi],(g,[u])=>g.id()===u.value],"filter-type-==":[_i,[gi],(g,[u])=>g.geometryType()===u.value],"filter-<":[_i,[gi,wi],(g,[u,f])=>{const _=g.properties()[u.value],C=f.value;return typeof _==typeof C&&_{const f=g.id(),_=u.value;return typeof f==typeof _&&f<_}],"filter->":[_i,[gi,wi],(g,[u,f])=>{const _=g.properties()[u.value],C=f.value;return typeof _==typeof C&&_>C}],"filter-id->":[_i,[wi],(g,[u])=>{const f=g.id(),_=u.value;return typeof f==typeof _&&f>_}],"filter-<=":[_i,[gi,wi],(g,[u,f])=>{const _=g.properties()[u.value],C=f.value;return typeof _==typeof C&&_<=C}],"filter-id-<=":[_i,[wi],(g,[u])=>{const f=g.id(),_=u.value;return typeof f==typeof _&&f<=_}],"filter->=":[_i,[gi,wi],(g,[u,f])=>{const _=g.properties()[u.value],C=f.value;return typeof _==typeof C&&_>=C}],"filter-id->=":[_i,[wi],(g,[u])=>{const f=g.id(),_=u.value;return typeof f==typeof _&&f>=_}],"filter-has":[_i,[wi],(g,[u])=>u.value in g.properties()],"filter-has-id":[_i,[],g=>g.id()!==null&&g.id()!==void 0],"filter-type-in":[_i,[Su(gi)],(g,[u])=>u.value.indexOf(g.geometryType())>=0],"filter-id-in":[_i,[Su(wi)],(g,[u])=>u.value.indexOf(g.id())>=0],"filter-in-small":[_i,[gi,Su(wi)],(g,[u,f])=>f.value.indexOf(g.properties()[u.value])>=0],"filter-in-large":[_i,[gi,Su(wi)],(g,[u,f])=>function(_,C,M,P){for(;M<=P;){const B=M+P>>1;if(C[B]===_)return!0;C[B]>_?P=B-1:M=B+1}return!1}(g.properties()[u.value],f.value,0,f.value.length-1)],all:{type:_i,overloads:[[[_i,_i],(g,[u,f])=>u.evaluate(g)&&f.evaluate(g)],[s0(_i),(g,u)=>{for(const f of u)if(!f.evaluate(g))return!1;return!0}]]},any:{type:_i,overloads:[[[_i,_i],(g,[u,f])=>u.evaluate(g)||f.evaluate(g)],[s0(_i),(g,u)=>{for(const f of u)if(f.evaluate(g))return!0;return!1}]]},"!":[_i,[_i],(g,[u])=>!u.evaluate(g)],"is-supported-script":[_i,[gi],(g,[u])=>{const f=g.globals&&g.globals.isSupportedScript;return!f||f(u.evaluate(g))}],upcase:[gi,[gi],(g,[u])=>u.evaluate(g).toUpperCase()],downcase:[gi,[gi],(g,[u])=>u.evaluate(g).toLowerCase()],concat:[gi,s0(wi),(g,u)=>u.map(f=>Tn(f.evaluate(g))).join("")],"resolved-locale":[gi,[Jv],(g,[u])=>u.evaluate(g).resolvedLocale()],random:[Zr,[Zr,Zr,wi],(g,u)=>{const[f,_,C]=u.map(P=>P.evaluate(g));if(f>_||f===_)return f;let M;if(typeof C=="string")M=function(P){let B=0;if(P.length===0)return B;for(let U=0;UJSON.stringify(se)).join(", ")}, but found ${JSON.stringify(ee)} instead.`);return ee}catch(ee){const se=ee;return this._warningHistory[se.message]||(this._warningHistory[se.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${se.message}`)),this._defaultValue}}}function $2(g){return Array.isArray(g)&&g.length>0&&typeof g[0]=="string"&&g[0]in h_}function n0(g,u,f,_,C){const M=new T5(h_,[],u?function(B){const U={color:rh,string:gi,number:Zr,enum:gi,boolean:_i,formatted:g2,resolvedImage:y2};return B.type==="array"?Su(U[B.value]||wi,B.length):U[B.type]}(u):void 0,void 0,void 0,f,_,C),P=M.parse(g,void 0,void 0,void 0,u&&u.type==="string"?{typeAnnotation:"coerce"}:void 0);return P?_z(new U5(P,u,f,_,C)):r0(M.errors)}class m_{constructor(u,f,_,C){this.kind=u,this._styleExpression=f,this.isLightConstant=_,this.isLineProgressConstant=C,this.isStateDependent=u!=="constant"&&!o_(f.expression),this.configDependencies=F5(f.expression),this.isIndoorDependent=B5(f.expression)}evaluateWithoutErrorHandling(u,f,_,C,M,P){return this._styleExpression.evaluateWithoutErrorHandling(u,f,_,C,M,P)}evaluate(u,f,_,C,M,P,B){return this._styleExpression.evaluate(u,f,_,C,M,P,void 0,void 0,B)}}class o1{constructor(u,f,_,C,M,P){this.kind=u,this.zoomStops=_,this._styleExpression=f,this.isStateDependent=u!=="camera"&&!o_(f.expression),this.isIndoorDependent=B5(f.expression),this.isLightConstant=M,this.isLineProgressConstant=P,this.configDependencies=F5(f.expression),this.interpolationType=C}evaluateWithoutErrorHandling(u,f,_,C,M,P){return this._styleExpression.evaluateWithoutErrorHandling(u,f,_,C,M,P)}evaluate(u,f,_,C,M,P){return this._styleExpression.evaluate(u,f,_,C,M,P)}interpolationFactor(u,f,_){return this.interpolationType?ou.interpolationFactor(this.interpolationType,u,f,_):0}}function aP(g,u,f,_,C){if((g=n0(g,u,f,_,C)).result==="error")return g;const M=g.value.expression,P=a1(M);if(!P&&!z5(u))return r0([new sh("","data expressions not supported")]);const B=vx(M,["zoom","pitch","distance-from-center"]);if(!B&&!rP(u))return r0([new sh("","zoom expressions not supported")]);const U=vx(M,["measure-light"]);if(!U&&!wz(u))return r0([new sh("","measure-light expression not supported")]);const W=vx(M,["line-progress"]);if(!W&&!function(ae){return z2(ae.expression,"line-progress")}(u))return r0([new sh("","line-progress expression not supported")]);const ee=u.expression&&u.expression.relaxZoomRestriction,se=mp(M);return se||B||ee?se instanceof sh?r0([se]):se instanceof ou&&!$5(u)?r0([new sh("",'"interpolate" expressions cannot be used with this property')]):_z(se?new o1(P&&W?"camera":"composite",g.value,se.labels,se instanceof ou?se.interpolation:void 0,U,W):new m_(P&&W?"constant":"source",g.value,U,W)):r0([new sh("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class q5{constructor(u,f){this._parameters=u,this._specification=f,Object.assign(this,Nz(this._parameters,this._specification))}static deserialize(u){return new q5(u._parameters,u._specification)}static serialize(u){return{_parameters:u._parameters,_specification:u._specification}}}function mp(g){let u=null;if(g instanceof M5)u=mp(g.result);else if(g instanceof P2){for(const f of g.args)if(u=mp(f),u)break}else(g instanceof M2||g instanceof ou)&&g.input instanceof Mc&&g.input.name==="zoom"&&(u=g);return u instanceof sh||g.eachChild(f=>{const _=mp(f);_ instanceof sh?u=_:u&&_&&u!==_&&(u=new sh("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),u}var iP,Cz,U2=function(){if(Cz)return iP;Cz=1,iP=u;var g=3;function u(f,_,C){var M=this.cells=[];if(f instanceof ArrayBuffer){this.arrayBuffer=f;var P=new Int32Array(this.arrayBuffer);f=P[0],this.d=(_=P[1])+2*(C=P[2]);for(var B=0;B=ae[we+0]&&M>=ae[we+1])?(U[ge]=!0,B.push(se[ge])):U[ge]=!1}}},u.prototype._forEachCell=function(f,_,C,M,P,B,U,W){for(var ee=this._convertToCellCoord(f),se=this._convertToCellCoord(_),ae=this._convertToCellCoord(C),me=this._convertToCellCoord(M),ge=ee;ge<=ae;ge++)for(var we=se;we<=me;we++){var Ee=this.d*we+ge;if((!W||W(this._convertFromCellCoord(ge),this._convertFromCellCoord(we),this._convertFromCellCoord(ge+1),this._convertFromCellCoord(we+1)))&&P.call(this,f,_,C,M,Ee,B,U,W))return}},u.prototype._convertFromCellCoord=function(f){return(f-this.padding)/this.scale},u.prototype._convertToCellCoord=function(f){return Math.max(0,Math.min(this.d-1,Math.floor(f*this.scale)+this.padding))},u.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var f=this.cells,_=g+this.cells.length+1+1,C=0,M=0;M=0||(C[M]=Rg(g[M],u)));g instanceof Error&&(C.message=g.message)}if(C.$name)throw new Error("$name property is reserved for worker serialization logic.");return _!=="Object"&&(C.$name=_),C}throw new Error("can't serialize object of type "+typeof g)}function a0(g){if(g==null||typeof g=="boolean"||typeof g=="number"||typeof g=="string"||g instanceof Boolean||g instanceof Number||g instanceof String||g instanceof Date||g instanceof RegExp||q2(g)||g instanceof ImageBitmap||ArrayBuffer.isView(g)||g instanceof ImageData)return g;if(Array.isArray(g))return g.map(a0);if(typeof g=="object"){const u=g.$name||"Object";if(u==="Map"){const C=g.entries||[],M=new Map;for(let P=0;Pg>=1536&&g<=1791,V5=g=>g>=1872&&g<=1919,H5=g=>g>=2208&&g<=2303,G5=g=>g>=11904&&g<=12031,Og=g=>g>=12032&&g<=12255,oP=g=>g>=12272&&g<=12287,V2=g=>g>=12288&&g<=12351,H2=g=>g>=12352&&g<=12447,c1=g=>g>=12448&&g<=12543,lP=g=>g>=12544&&g<=12591,W5=g=>g>=12704&&g<=12735,_x=g=>g>=12736&&g<=12783,Ez=g=>g>=12784&&g<=12799,Az=g=>g>=12800&&g<=13055,Mz=g=>g>=13056&&g<=13311,cP=g=>g>=13312&&g<=19903,K5=g=>g>=19968&&g<=40959,G2=g=>g>=40960&&g<=42127,dP=g=>g>=42128&&g<=42191,uP=g=>g>=44032&&g<=55215,Y5=g=>g>=63744&&g<=64255,hP=g=>g>=64336&&g<=65023,Iz=g=>g>=65040&&g<=65055,mP=g=>g>=65072&&g<=65103,Lz=g=>g>=65104&&g<=65135,fP=g=>g>=65136&&g<=65279,pP=g=>g>=65280&&g<=65519;function xP(g){for(const u of g)if(gP(u.charCodeAt(0)))return!0;return!1}function bge(g){for(const u of g)if(!_ge(u.charCodeAt(0)))return!1;return!0}function _ge(g){return!(Tz(g)||V5(g)||H5(g)||hP(g)||fP(g))}function wge(g){return!(g<11904||!(W5(g)||lP(g)||mP(g)||Y5(g)||Mz(g)||G5(g)||_x(g)||V2(g)||cP(g)||K5(g)||Az(g)||pP(g)||H2(g)||oP(g)||Og(g)||Ez(g)||c1(g)||Iz(g)||dP(g)||G2(g)))}function gP(g){return!(g!==746&&g!==747&&(g<4352||!(W5(g)||lP(g)||mP(g)&&!(g>=65097&&g<=65103)||Y5(g)||Mz(g)||G5(g)||_x(g)||!(!V2(g)||g>=12296&&g<=12305||g>=12308&&g<=12319||g===12336)||cP(g)||K5(g)||Az(g)||(u=>u>=12592&&u<=12687)(g)||(u=>u>=43360&&u<=43391)(g)||(u=>u>=55216&&u<=55295)(g)||(u=>u>=4352&&u<=4607)(g)||uP(g)||H2(g)||oP(g)||(u=>u>=12688&&u<=12703)(g)||Og(g)||Ez(g)||c1(g)&&g!==12540||!(!pP(g)||g===65288||g===65289||g===65293||g>=65306&&g<=65310||g===65339||g===65341||g===65343||g>=65371&&g<=65503||g===65507||g>=65512&&g<=65519)||!(!Lz(g)||g>=65112&&g<=65118||g>=65123&&g<=65126)||(u=>u>=5120&&u<=5759)(g)||(u=>u>=6320&&u<=6399)(g)||Iz(g)||(u=>u>=19904&&u<=19967)(g)||G2(g)||dP(g))))}function Pz(g){return g===12312||g===12313||g===12316||g===12540||g===12448}function d1(g){return!(gP(g)||function(u){return!!((f=>f>=128&&f<=255)(u)&&(u===167||u===169||u===174||u===177||u===188||u===189||u===190||u===215||u===247)||(f=>f>=8192&&f<=8303)(u)&&(u===8214||u===8224||u===8225||u===8240||u===8241||u===8251||u===8252||u===8258||u===8263||u===8264||u===8265||u===8273)||(f=>f>=8448&&f<=8527)(u)||(f=>f>=8528&&f<=8591)(u)||(f=>f>=8960&&f<=9215)(u)&&(u>=8960&&u<=8967||u>=8972&&u<=8991||u>=8996&&u<=9e3||u===9003||u>=9085&&u<=9114||u>=9150&&u<=9165||u===9167||u>=9169&&u<=9179||u>=9186&&u<=9215)||(f=>f>=9216&&f<=9279)(u)&&u!==9251||(f=>f>=9280&&f<=9311)(u)||(f=>f>=9312&&f<=9471)(u)||(f=>f>=9632&&f<=9727)(u)||(f=>f>=9728&&f<=9983)(u)&&!(u>=9754&&u<=9759)||(f=>f>=11008&&f<=11263)(u)&&(u>=11026&&u<=11055||u>=11088&&u<=11097||u>=11192&&u<=11243)||V2(u)||c1(u)||(f=>f>=57344&&f<=63743)(u)||mP(u)||Lz(u)||pP(u)||u===8734||u===8756||u===8757||u>=9984&&u<=10087||u>=10102&&u<=10131||u===65532||u===65533)}(g))}function Dz(g){return Tz(g)||V5(g)||H5(g)||hP(g)||fP(g)}function yP(g){return g>=1424&&g<=2303||hP(g)||fP(g)}function Z5(g,u){return!(!u&&yP(g)||g>=2304&&g<=3583||g>=3840&&g<=4255||(f=>f>=6016&&f<=6143)(g))}function jge(g){for(const u of g)if(yP(u.charCodeAt(0)))return!0;return!1}const im={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let wx=null,Cu=im.unavailable,Fm=null;const Rz=function(g){g&&typeof g=="string"&&g.indexOf("NetworkError")>-1&&(Cu=im.error),wx&&wx(g)};function vP(){bP.fire(new Pm("pluginStateChange",{pluginStatus:Cu,pluginURL:Fm}))}const bP=new Qv,_P=function(){return Cu},Oz=function(){if(Cu!==im.deferred||!Fm)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Cu=im.loading,vP(),Fm&&Yy({url:Fm},g=>{g?Rz(g):(Cu=im.loaded,vP())})},Fg={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Cu===im.loaded||Fg.applyArabicShaping!=null,isLoading:()=>Cu===im.loading,setState(g){Cu=g.pluginStatus,Fm=g.pluginURL},isParsing:()=>Cu===im.parsing,isParsed:()=>Cu===im.parsed,getPluginURL:()=>Fm},Fz=function(){Fg.isLoading()||Fg.isLoaded()||_P()!=="deferred"||Oz()};class ui{constructor(u,f){this.zoom=u,f?(this.now=f.now,this.fadeDuration=f.fadeDuration,this.transition=f.transition,this.pitch=f.pitch,this.brightness=f.brightness,this.worldview=f.worldview,this.activeFloors=f.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(u){return function(f,_){for(const C of f)if(!Z5(C.charCodeAt(0),_))return!1;return!0}(u,Fg.isLoaded())}}class p_{constructor(u,f,_,C,M){this.property=u,this.value=f,this.expression=function(P,B,U,W,ee){if(nP(P))return new q5(P,B);if($2(P)||Array.isArray(P)&&P.length>0){const se=aP(P,B,U,W,ee);if(se.result==="error")throw new Error(se.value.map(ae=>`${ae.key}: ${ae.message}`).join(", "));return se.value}{let se=P;return typeof P=="string"&&B.type==="color"&&(se=wr.parse(P)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>se}}}(f===void 0?u.specification.default:f,u.specification,_,C,M)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(u,f,_,C){return this.property.possiblyEvaluate(this,u,f,_,C)}}class X5{constructor(u,f,_,C){this.property=u,this.value=new p_(u,void 0,f,_,C)}transitioned(u,f){return new x_(this.property,this.value,f,Object.assign({},u.transition,this.transition),u.now)}untransitioned(){return new x_(this.property,this.value,null,{},0)}}class Q5{constructor(u,f,_,C){this._properties=u,this._values=Object.create(u.defaultTransitionablePropertyValues),this._scope=f,this._options=_,this._iconImageUseTheme=C,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(u){return xr(this._values[u].value.value)}setValue(u,f){this._values.hasOwnProperty(u)||(this._values[u]=new X5(this._values[u].property,this._scope,this._options,this._iconImageUseTheme)),this._values[u].value=new p_(this._values[u].property,f===null?void 0:xr(f),this._scope,this._options,this._iconImageUseTheme),this._values[u].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[u].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[u].value.isIndoorDependent())}setTransitionOrValue(u,f){f&&(this._options=f);const _=this._properties.properties;if(u)for(const C in u){const M=u[C];if(C.endsWith("-transition")){const P=C.slice(0,-11);_[P]&&this.setTransition(P,M)}else _.hasOwnProperty(C)&&this.setValue(C,M)}}getTransition(u){return xr(this._values[u].transition)}setTransition(u,f){this._values.hasOwnProperty(u)||(this._values[u]=new X5(this._values[u].property)),this._values[u].transition=xr(f)||void 0}serialize(){const u={};for(const f of Object.keys(this._values)){const _=this.getValue(f);_!==void 0&&(u[f]=_);const C=this.getTransition(f);C!==void 0&&(u[`${f}-transition`]=C)}return u}transitioned(u,f){const _=new wP(this._properties);for(const C of Object.keys(this._values))_._values[C]=this._values[C].transitioned(u,f._values[C]);return _}untransitioned(){const u=new wP(this._properties);for(const f of Object.keys(this._values))u._values[f]=this._values[f].untransitioned();return u}isIndoorDependent(){return this._isIndoorDependent}}class x_{constructor(u,f,_,C,M){const P=C.delay||0,B=C.duration||0;M=M||0,this.property=u,this.value=f,this.begin=M+P,this.end=this.begin+B,u.specification.transition&&(C.delay||C.duration)&&(this.prior=_)}possiblyEvaluate(u,f,_){const C=u.now||0,M=this.value.possiblyEvaluate(u,f,_),P=this.prior;if(P){if(C>this.end)return this.prior=null,M;if(this.value.isDataDriven())return this.prior=null,M;if(C":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 Bz(g){return g instanceof Number||g instanceof String||g instanceof Boolean?g.valueOf():g}function J5(g){if(Array.isArray(g))return g.map(J5);if(g instanceof Object&&!(g instanceof Number||g instanceof String||g instanceof Boolean)){const u={};for(const f in g)u[f]=J5(g[f]);return u}return Bz(g)}function NP(g){if(g===!0||g===!1)return!0;if(!Array.isArray(g)||g.length===0)return!1;switch(g[0]){case"has":return g.length>=2&&g[1]!=="$id"&&g[1]!=="$type";case"in":return g.length>=3&&(typeof g[1]!="string"||Array.isArray(g[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return g.length!==3||Array.isArray(g[1])||Array.isArray(g[2]);case"any":case"all":for(const u of g.slice(1))if(!NP(u)&&typeof u!="boolean")return!1;return!0;default:return!0}}function eT(g,u="",f=null,_="fill"){if(g==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};NP(g)||(g=tT(g));const C=g;let M=!0;try{M=function(ee){if(!y_(ee))return ee;let se=J5(ee);return $z(se),se=zz(se),se}(C)}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(C,null,2)} `)}let P=null,B=null;if(_!=="background"&&_!=="sky"&&_!=="slot"){B=Yt[`filter_${_}`];const ee=n0(M,B,u,f);if(ee.result==="error")throw new Error(ee.value.map(se=>`${se.key}: ${se.message}`).join(", "));P=(se,ae,me)=>ee.value.evaluate(se,ae,{},me)}let U=null,W=null;if(M!==C){const ee=n0(C,B,u,f);if(ee.result==="error")throw new Error(ee.value.map(se=>`${se.key}: ${se.message}`).join(", "));U=(se,ae,me,ge,we)=>ee.value.evaluate(se,ae,{},me,void 0,void 0,ge,we),W=!a1(ee.value.expression)}return{filter:P,dynamicFilter:U||void 0,needGeometry:qz(M),needFeature:!!W}}function zz(g){if(!Array.isArray(g))return g;const u=function(f){if(Uz.has(f[0])){for(let _=1;_zz(f))}function $z(g){let u=!1;const f=[];if(g[0]==="case"){for(let _=1;_",">=","<","<=","to-boolean"]);function Nge(g,u){return gu?1:0}function qz(g){if(!Array.isArray(g))return!1;if(g[0]==="within"||g[0]==="distance")return!0;for(let u=1;u"||u==="<="||u===">="?sT(g[1],g[2],u):u==="any"?(f=g.slice(1),["any"].concat(f.map(tT))):u==="all"?["all"].concat(g.slice(1).map(tT)):u==="none"?["all"].concat(g.slice(1).map(tT).map(W2)):u==="in"?kP(g[1],g.slice(2)):u==="!in"?W2(kP(g[1],g.slice(2))):u==="has"?zg(g[1]):u!=="!has"||W2(zg(g[1]));var f}function sT(g,u,f){switch(g){case"$type":return[`filter-type-${f}`,u];case"$id":return[`filter-id-${f}`,u];default:return[`filter-${f}`,g,u]}}function kP(g,u){if(u.length===0)return!1;switch(g){case"$type":return["filter-type-in",["literal",u]];case"$id":return["filter-id-in",["literal",u]];default:return u.length>200&&!u.some(f=>typeof f!=typeof u[0])?["filter-in-large",g,["literal",u.sort(Nge)]]:["filter-in-small",g,["literal",u]]}}function zg(g){switch(g){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",g]}}function W2(g){return["!",g]}const K2="";function h1(g,u){return u?`${g}${K2}${u}`:g}function Vz(g){const u=g.indexOf(K2);return u>=0?g.slice(u+1):""}let Hz;const SP=()=>Hz||(Hz=new jo({"icon-size":new Qs(Yt.layout_symbol["icon-size"]),"icon-image":new Qs(Yt.layout_symbol["icon-image"]),"icon-rotate":new Qs(Yt.layout_symbol["icon-rotate"]),"icon-offset":new Qs(Yt.layout_symbol["icon-offset"]),"text-size":new Qs(Yt.layout_symbol["text-size"]),"text-rotate":new Qs(Yt.layout_symbol["text-rotate"]),"text-offset":new Qs(Yt.layout_symbol["text-offset"])}));let CP;const TP=()=>CP||(CP=new jo({"icon-opacity":new Qs(Yt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Qs(Yt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Qs(Yt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Qs(Yt.paint_symbol["text-emissive-strength"]),"icon-color":new Qs(Yt.paint_symbol["icon-color"]),"icon-halo-color":new Qs(Yt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Qs(Yt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Qs(Yt.paint_symbol["icon-halo-blur"]),"icon-translate":new Qs(Yt.paint_symbol["icon-translate"]),"text-opacity":new Qs(Yt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Qs(Yt.paint_symbol["text-occlusion-opacity"]),"text-color":new Qs(Yt.paint_symbol["text-color"],{runtimeType:rh,getOverride:g=>g.textColor,hasOverride:g=>!!g.textColor}),"text-halo-color":new Qs(Yt.paint_symbol["text-halo-color"]),"text-halo-width":new Qs(Yt.paint_symbol["text-halo-width"]),"text-halo-blur":new Qs(Yt.paint_symbol["text-halo-blur"]),"text-translate":new Qs(Yt.paint_symbol["text-translate"]),"symbol-z-offset":new Qs(Yt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"})}));class kge{constructor(u,f,_,C,M,P){this._conditionSpec=u,this._propertiesSpec=_;const B=n0(u,Yt.appearance.condition);if(B.result==="success"&&(this.condition=B.value),this.name=f,_){this.layoutProperties=new Bg(SP()),this.unevaluatedLayout=new jP(SP(),C,M,P),this.paintProperties=new Bg(TP()),this.unevaluatedPaint=new jP(TP(),C,M,"");for(const U in _)U in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(U,_[U]):U in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(U,_[U])}}isActive(u){return!(this.condition||!u.isHidden||this.name!=="hidden")||this.condition.evaluate(u.globals,u.feature,u.featureState,u.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(u){return this.layoutProperties.get(u)}getPaintProperty(u){return this.paintProperties.get(u)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(u){return this.unevaluatedLayout._values[u]}getUnevaluatedPaintProperty(u){return this.unevaluatedPaint._values[u]}recalculate(u,f,_){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(u,void 0,f,_)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(u,void 0,f,""))}serialize(){const u={};u.condition=this.condition.expression.serialize(),this.name&&(u.name=this.name);const f=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},_=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},C=Object.assign({},f,_);return Object.keys(C).length>0&&(u.properties=C),u}hasIconLayoutProperties(){const u=this.hasLayoutProperty("icon-image"),f=this.hasLayoutProperty("icon-size"),_=this.hasLayoutProperty("icon-offset"),C=this.hasLayoutProperty("icon-rotate");return u||f||_||C}hasTextLayoutProperties(){const u=this.hasLayoutProperty("text-size"),f=this.hasLayoutProperty("text-offset"),_=this.hasLayoutProperty("text-rotate");return u||f||_}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(u=>!u.endsWith("-use-theme")).some(u=>(u.startsWith("icon-")||u==="symbol-z-offset")&&this.hasPaintProperty(u))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(u=>!u.endsWith("-use-theme")).some(u=>(u.startsWith("text-")||u==="symbol-z-offset")&&this.hasPaintProperty(u))}hasLayoutProperty(u){return this.unevaluatedLayout&&this.unevaluatedLayout._values[u].value!==void 0}hasPaintProperty(u){return this.unevaluatedPaint&&this.unevaluatedPaint._values[u].value!==void 0}}const EP="-transition",Sge=new Set(["fill","line","background","hillshade","raster"]);class Tu extends Qv{constructor(u,f,_,C,M,P){if(super(),this.id=u.id,this.fqid=h1(this.id,_),this.type=u.type,this.scope=_,this.lut=C,this.options=M,this.iconImageUseTheme=P,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},u.type!=="custom"){if(this.metadata=u.metadata,this.minzoom=u.minzoom,this.maxzoom=u.maxzoom,u.type&&u.type!=="background"&&u.type!=="sky"&&u.type!=="slot"){this.source=u.source,this.sourceLayer=u["source-layer"],this.filter=u.filter;const B=n0(this.filter,Yt[`filter_${u.type}`]);B.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...B.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||B.value.isIndoorDependent)}if(u.slot&&(this.slot=u.slot),u.appearances&&this.setAppearances(u.appearances),f.layout&&(this._unevaluatedLayout=new jP(f.layout,this.scope,M,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),f.paint){this._transitionablePaint=new Q5(f.paint,this.scope,M);for(const B in u.paint)this.setPaintProperty(B,u.paint[B]);for(const B in u.layout)this.setLayoutProperty(B,u.layout[B]);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 Bg(f.paint)}}}onAdd(u){}onRemove(u){}isDraped(u){return!this.is3D(!0)&&Sge.has(this.type)}getLayoutProperty(u){return u==="visibility"?this.visibility:this._unevaluatedLayout.getValue(u)}setLayoutProperty(u,f){if(this.type==="custom"&&u==="visibility")return void(this.visibility=f);const _=this._unevaluatedLayout;_._properties.properties[u]&&(_.setValue(u,f),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,..._.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||_.isIndoorDependent(),u==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(u){this.appearances=[],u.forEach(f=>{this.appearances.push(new kge(f.condition,f.name,f.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(u){return u.endsWith(EP)?this._transitionablePaint.getTransition(u.slice(0,-11)):this._transitionablePaint.getValue(u)}isPaintProperty(u){return!!this._transitionablePaint._properties.properties[u]}setPaintProperty(u,f){const _=this._transitionablePaint,C=_._properties.properties;if(u.endsWith(EP)){const se=u.slice(0,-11);return C[se]&&_.setTransition(se,f||void 0),!1}if(!C[u])return!1;const M=_._values[u],P=M.value.isDataDriven(),B=M.value;_.setValue(u,f),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,..._.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||_.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(u);const U=_._values[u].value,W=U.isDataDriven(),ee=u.endsWith("pattern")||u==="line-dasharray";return W||P||ee||this._handleOverridablePaintPropertyUpdate(u,B,U)}_handleSpecialPaintPropertyUpdate(u){}getProgramIds(){return null}getDefaultProgramParams(u,f,_){return null}_handleOverridablePaintPropertyUpdate(u,f,_){return!1}isHidden(u){return!!(this.minzoom&&u=this.maxzoom)||this.visibility==="none"}updateTransitions(u){this._transitioningPaint=this._transitionablePaint.transitioned(u,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(u,f){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(u,void 0,f,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(u,void 0,f)}serialize(){const u={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&&(u.appearances=this.appearances.map(f=>f.serialize())),Cs(u,(f,_)=>!(f===void 0||_==="layout"&&!Object.keys(f).length||_==="paint"&&!Object.keys(f).length))}is3D(u){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 u in this.paint._values){const f=this.paint.get(u);if(f instanceof u1&&z5(f.property.specification)&&(f.value.kind==="source"||f.value.kind==="composite")&&f.value.isStateDependent)return!0}for(const u of this.appearances)if(!o_(u.condition.expression))return!0;return!1}compileFilter(u){this._filterCompiled||(this._featureFilter=eT(this.filter,this.scope,u),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(u){this._stats&&(u.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(u,f,_){return{}}queryRadius(u){}queryIntersectsFeature(u,f,_,C,M,P,B,U,W,ee){}}const rT={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Y2{constructor(u,f){this._structArray=u,this._pos1=f*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Cge=new ArrayBuffer(0);class to{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(u,f){return u._trim(),f&&u.arrayBuffer&&f.add(u.arrayBuffer),{length:u.length,arrayBuffer:u.arrayBuffer}}static deserialize(u){const f=Object.create(this.prototype);return f.arrayBuffer=u.arrayBuffer,f.length=u.length,u.arrayBuffer?f.capacity=u.arrayBuffer.byteLength/f.bytesPerElement:(f.capacity=0,f.arrayBuffer=Cge),f._refreshViews(),f}_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(u){this.reserve(u),this.length=u}reserve(u){if(u>this.capacity){this._reallocCount++,this.capacity=Math.max(u,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const f=this.uint8;this._refreshViews(),f&&this.uint8.set(f)}}reserveForAdditional(u){this.reserve(this.length+u)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...u){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...u){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 Ta(g,u=1){let f=0,_=0;return{members:g.map(C=>{const M=rT[C.type].BYTES_PER_ELEMENT,P=f=Gz(f,Math.max(u,M)),B=C.components||1;return _=Math.max(_,M),f+=M*B,{name:C.name,type:C.type,components:B,offset:P}}),size:Gz(f,Math.max(_,u)),alignment:u}}function Gz(g,u){return Math.ceil(g/u)*u}class om extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f){const _=this.length;return this.resize(_+1),this.emplace(_,u,f)}emplace(u,f,_){const C=2*u;return this.int16[C+0]=f,this.int16[C+1]=_,u}}om.prototype.bytesPerElement=4,Dr(om,"StructArrayLayout2i4");class jx extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,_)}emplace(u,f,_,C){const M=3*u;return this.int16[M+0]=f,this.int16[M+1]=_,this.int16[M+2]=C,u}}jx.prototype.bytesPerElement=6,Dr(jx,"StructArrayLayout3i6");class $d extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,f,_,C)}emplace(u,f,_,C,M){const P=4*u;return this.int16[P+0]=f,this.int16[P+1]=_,this.uint16[P+2]=C,this.uint16[P+3]=M,u}}$d.prototype.bytesPerElement=8,Dr($d,"StructArrayLayout2i2ui8");class Bm extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.float32[1*u+0]=f,u}}Bm.prototype.bytesPerElement=4,Dr(Bm,"StructArrayLayout1f4");class AP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,_)}emplace(u,f,_,C){const M=4*u,P=2*u;return this.int16[M+0]=f,this.int16[M+1]=_,this.float32[P+1]=C,u}}AP.prototype.bytesPerElement=8,Dr(AP,"StructArrayLayout2i1f8");class MP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,_)}emplace(u,f,_,C){const M=4*u;return this.int16[M+0]=f,this.int16[M+1]=_,this.int16[M+2]=C,u}}MP.prototype.bytesPerElement=8,Dr(MP,"StructArrayLayout3i8");class IP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,f,_,C)}emplace(u,f,_,C,M){const P=4*u;return this.int16[P+0]=f,this.int16[P+1]=_,this.int16[P+2]=C,this.int16[P+3]=M,u}}IP.prototype.bytesPerElement=8,Dr(IP,"StructArrayLayout4i8");class LP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M){const P=this.length;return this.resize(P+1),this.emplace(P,u,f,_,C,M)}emplace(u,f,_,C,M,P){const B=5*u;return this.int16[B+0]=f,this.int16[B+1]=_,this.int16[B+2]=C,this.int16[B+3]=M,this.int16[B+4]=P,u}}LP.prototype.bytesPerElement=10,Dr(LP,"StructArrayLayout5i10");class Z2 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,_,C,M,P,B)}emplace(u,f,_,C,M,P,B,U){const W=6*u,ee=12*u,se=3*u;return this.int16[W+0]=f,this.int16[W+1]=_,this.uint8[ee+4]=C,this.uint8[ee+5]=M,this.uint8[ee+6]=P,this.uint8[ee+7]=B,this.float32[se+2]=U,u}}Z2.prototype.bytesPerElement=12,Dr(Z2,"StructArrayLayout2i4ub1f12");class Tf extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,_)}emplace(u,f,_,C){const M=3*u;return this.float32[M+0]=f,this.float32[M+1]=_,this.float32[M+2]=C,u}}Tf.prototype.bytesPerElement=12,Dr(Tf,"StructArrayLayout3f12");class Nx extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M){const P=this.length;return this.resize(P+1),this.emplace(P,u,f,_,C,M)}emplace(u,f,_,C,M,P){const B=6*u,U=3*u;return this.uint16[B+0]=f,this.uint16[B+1]=_,this.uint16[B+2]=C,this.uint16[B+3]=M,this.float32[U+2]=P,u}}Nx.prototype.bytesPerElement=12,Dr(Nx,"StructArrayLayout4ui1f12");class v_ extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,f,_,C)}emplace(u,f,_,C,M){const P=4*u;return this.uint16[P+0]=f,this.uint16[P+1]=_,this.uint16[P+2]=C,this.uint16[P+3]=M,u}}v_.prototype.bytesPerElement=8,Dr(v_,"StructArrayLayout4ui8");class nT extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,_,C,M,P)}emplace(u,f,_,C,M,P,B){const U=6*u;return this.int16[U+0]=f,this.int16[U+1]=_,this.int16[U+2]=C,this.int16[U+3]=M,this.int16[U+4]=P,this.int16[U+5]=B,u}}nT.prototype.bytesPerElement=12,Dr(nT,"StructArrayLayout6i12");class PP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B,U,W,ee,se,ae){const me=this.length;return this.resize(me+1),this.emplace(me,u,f,_,C,M,P,B,U,W,ee,se,ae)}emplace(u,f,_,C,M,P,B,U,W,ee,se,ae,me){const ge=12*u;return this.int16[ge+0]=f,this.int16[ge+1]=_,this.int16[ge+2]=C,this.int16[ge+3]=M,this.uint16[ge+4]=P,this.uint16[ge+5]=B,this.uint16[ge+6]=U,this.uint16[ge+7]=W,this.int16[ge+8]=ee,this.int16[ge+9]=se,this.int16[ge+10]=ae,this.int16[ge+11]=me,u}}PP.prototype.bytesPerElement=24,Dr(PP,"StructArrayLayout4i4ui4i24");class DP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,_,C,M,P)}emplace(u,f,_,C,M,P,B){const U=10*u,W=5*u;return this.int16[U+0]=f,this.int16[U+1]=_,this.int16[U+2]=C,this.float32[W+2]=M,this.float32[W+3]=P,this.float32[W+4]=B,u}}DP.prototype.bytesPerElement=20,Dr(DP,"StructArrayLayout3i3f20");class $g extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,f,_,C)}emplace(u,f,_,C,M){const P=4*u;return this.float32[P+0]=f,this.float32[P+1]=_,this.float32[P+2]=C,this.float32[P+3]=M,u}}$g.prototype.bytesPerElement=16,Dr($g,"StructArrayLayout4f16");class X2 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.uint32[1*u+0]=f,u}}X2.prototype.bytesPerElement=4,Dr(X2,"StructArrayLayout1ul4");class Ef extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f){const _=this.length;return this.resize(_+1),this.emplace(_,u,f)}emplace(u,f,_){const C=2*u;return this.uint16[C+0]=f,this.uint16[C+1]=_,u}}Ef.prototype.bytesPerElement=4,Dr(Ef,"StructArrayLayout2ui4");class aT extends to{_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(u,f,_,C,M,P,B,U,W,ee,se,ae,me){const ge=this.length;return this.resize(ge+1),this.emplace(ge,u,f,_,C,M,P,B,U,W,ee,se,ae,me)}emplace(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge){const we=20*u,Ee=10*u;return this.int16[we+0]=f,this.int16[we+1]=_,this.int16[we+2]=C,this.int16[we+3]=M,this.int16[we+4]=P,this.float32[Ee+3]=B,this.float32[Ee+4]=U,this.float32[Ee+5]=W,this.float32[Ee+6]=ee,this.int16[we+14]=se,this.uint32[Ee+8]=ae,this.uint16[we+18]=me,this.uint16[we+19]=ge,u}}aT.prototype.bytesPerElement=40,Dr(aT,"StructArrayLayout5i4f1i1ul2ui40");class Q2 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,_,C,M,P,B)}emplace(u,f,_,C,M,P,B,U){const W=8*u;return this.int16[W+0]=f,this.int16[W+1]=_,this.int16[W+2]=C,this.int16[W+4]=M,this.int16[W+5]=P,this.int16[W+6]=B,this.int16[W+7]=U,u}}Q2.prototype.bytesPerElement=16,Dr(Q2,"StructArrayLayout3i2i2i16");class RP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M){const P=this.length;return this.resize(P+1),this.emplace(P,u,f,_,C,M)}emplace(u,f,_,C,M,P){const B=4*u,U=8*u;return this.float32[B+0]=f,this.float32[B+1]=_,this.float32[B+2]=C,this.int16[U+6]=M,this.int16[U+7]=P,u}}RP.prototype.bytesPerElement=16,Dr(RP,"StructArrayLayout2f1f2i16");class J2 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,_,C,M,P)}emplace(u,f,_,C,M,P,B){const U=20*u,W=5*u;return this.uint8[U+0]=f,this.uint8[U+1]=_,this.float32[W+1]=C,this.float32[W+2]=M,this.float32[W+3]=P,this.float32[W+4]=B,u}}J2.prototype.bytesPerElement=20,Dr(J2,"StructArrayLayout2ub4f20");class ll extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,_){const C=this.length;return this.resize(C+1),this.emplace(C,u,f,_)}emplace(u,f,_,C){const M=3*u;return this.uint16[M+0]=f,this.uint16[M+1]=_,this.uint16[M+2]=C,u}}ll.prototype.bytesPerElement=6,Dr(ll,"StructArrayLayout3ui6");class iT extends to{_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(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut){const ft=this.length;return this.resize(ft+1),this.emplace(ft,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut)}emplace(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut,ft){const Bt=30*u,Et=15*u,Ot=60*u;return this.int16[Bt+0]=f,this.int16[Bt+1]=_,this.int16[Bt+2]=C,this.float32[Et+2]=M,this.float32[Et+3]=P,this.uint16[Bt+8]=B,this.uint16[Bt+9]=U,this.uint32[Et+5]=W,this.uint32[Et+6]=ee,this.uint32[Et+7]=se,this.uint16[Bt+16]=ae,this.uint16[Bt+17]=me,this.uint16[Bt+18]=ge,this.float32[Et+10]=we,this.float32[Et+11]=Ee,this.uint8[Ot+48]=Fe,this.uint8[Ot+49]=Qe,this.uint8[Ot+50]=Ve,this.uint32[Et+13]=at,this.int16[Bt+28]=ut,this.uint8[Ot+58]=ft,u}}iT.prototype.bytesPerElement=60,Dr(iT,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class OP extends to{_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(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut,ft,Bt,Et,Ot,Lt,Pt,hs,bs,Ts,Rs,Es,Ws){const ls=this.length;return this.resize(ls+1),this.emplace(ls,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut,ft,Bt,Et,Ot,Lt,Pt,hs,bs,Ts,Rs,Es,Ws)}emplace(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut,ft,Bt,Et,Ot,Lt,Pt,hs,bs,Ts,Rs,Es,Ws,ls){const Ps=20*u,zs=40*u,Ks=80*u;return this.float32[Ps+0]=f,this.float32[Ps+1]=_,this.int16[zs+4]=C,this.int16[zs+5]=M,this.int16[zs+6]=P,this.int16[zs+7]=B,this.int16[zs+8]=U,this.int16[zs+9]=W,this.int16[zs+10]=ee,this.int16[zs+11]=se,this.int16[zs+12]=ae,this.uint16[zs+13]=me,this.uint16[zs+14]=ge,this.uint16[zs+15]=we,this.uint16[zs+16]=Ee,this.uint16[zs+17]=Fe,this.uint16[zs+18]=Qe,this.uint16[zs+19]=Ve,this.uint16[zs+20]=at,this.uint16[zs+21]=ut,this.uint16[zs+22]=ft,this.uint16[zs+23]=Bt,this.uint16[zs+24]=Et,this.uint16[zs+25]=Ot,this.uint16[zs+26]=Lt,this.uint16[zs+27]=Pt,this.uint32[Ps+14]=hs,this.float32[Ps+15]=bs,this.float32[Ps+16]=Ts,this.float32[Ps+17]=Rs,this.float32[Ps+18]=Es,this.uint8[Ks+76]=Ws,this.uint16[zs+39]=ls,u}}OP.prototype.bytesPerElement=80,Dr(OP,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class oT extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P){const B=this.length;return this.resize(B+1),this.emplace(B,u,f,_,C,M,P)}emplace(u,f,_,C,M,P,B){const U=6*u;return this.float32[U+0]=f,this.float32[U+1]=_,this.float32[U+2]=C,this.float32[U+3]=M,this.float32[U+4]=P,this.float32[U+5]=B,u}}oT.prototype.bytesPerElement=24,Dr(oT,"StructArrayLayout6f24");class m1 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M){const P=this.length;return this.resize(P+1),this.emplace(P,u,f,_,C,M)}emplace(u,f,_,C,M,P){const B=5*u;return this.float32[B+0]=f,this.float32[B+1]=_,this.float32[B+2]=C,this.float32[B+3]=M,this.float32[B+4]=P,u}}m1.prototype.bytesPerElement=20,Dr(m1,"StructArrayLayout5f20");class eN extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,_,C,M,P,B)}emplace(u,f,_,C,M,P,B,U){const W=7*u;return this.float32[W+0]=f,this.float32[W+1]=_,this.float32[W+2]=C,this.float32[W+3]=M,this.float32[W+4]=P,this.float32[W+5]=B,this.float32[W+6]=U,u}}eN.prototype.bytesPerElement=28,Dr(eN,"StructArrayLayout7f28");class FP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B,U,W,ee,se){const ae=this.length;return this.resize(ae+1),this.emplace(ae,u,f,_,C,M,P,B,U,W,ee,se)}emplace(u,f,_,C,M,P,B,U,W,ee,se,ae){const me=11*u;return this.float32[me+0]=f,this.float32[me+1]=_,this.float32[me+2]=C,this.float32[me+3]=M,this.float32[me+4]=P,this.float32[me+5]=B,this.float32[me+6]=U,this.float32[me+7]=W,this.float32[me+8]=ee,this.float32[me+9]=se,this.float32[me+10]=ae,u}}FP.prototype.bytesPerElement=44,Dr(FP,"StructArrayLayout11f44");class BP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B,U,W){const ee=this.length;return this.resize(ee+1),this.emplace(ee,u,f,_,C,M,P,B,U,W)}emplace(u,f,_,C,M,P,B,U,W,ee){const se=9*u;return this.float32[se+0]=f,this.float32[se+1]=_,this.float32[se+2]=C,this.float32[se+3]=M,this.float32[se+4]=P,this.float32[se+5]=B,this.float32[se+6]=U,this.float32[se+7]=W,this.float32[se+8]=ee,u}}BP.prototype.bytesPerElement=36,Dr(BP,"StructArrayLayout9f36");class f1 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f){const _=this.length;return this.resize(_+1),this.emplace(_,u,f)}emplace(u,f,_){const C=2*u;return this.float32[C+0]=f,this.float32[C+1]=_,u}}f1.prototype.bytesPerElement=8,Dr(f1,"StructArrayLayout2f8");class zP extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u,f,_,C){const M=this.length;return this.resize(M+1),this.emplace(M,u,f,_,C)}emplace(u,f,_,C,M){const P=6*u;return this.uint32[3*u+0]=f,this.uint16[P+2]=_,this.uint16[P+3]=C,this.uint16[P+4]=M,u}}zP.prototype.bytesPerElement=12,Dr(zP,"StructArrayLayout1ul3ui12");class p1 extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.uint16[1*u+0]=f,u}}p1.prototype.bytesPerElement=2,Dr(p1,"StructArrayLayout1ui2");class $P extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee){const Fe=this.length;return this.resize(Fe+1),this.emplace(Fe,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee)}emplace(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe){const Qe=16*u;return this.float32[Qe+0]=f,this.float32[Qe+1]=_,this.float32[Qe+2]=C,this.float32[Qe+3]=M,this.float32[Qe+4]=P,this.float32[Qe+5]=B,this.float32[Qe+6]=U,this.float32[Qe+7]=W,this.float32[Qe+8]=ee,this.float32[Qe+9]=se,this.float32[Qe+10]=ae,this.float32[Qe+11]=me,this.float32[Qe+12]=ge,this.float32[Qe+13]=we,this.float32[Qe+14]=Ee,this.float32[Qe+15]=Fe,u}}$P.prototype.bytesPerElement=64,Dr($P,"StructArrayLayout16f64");class lT extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(u,f,_,C,M,P,B){const U=this.length;return this.resize(U+1),this.emplace(U,u,f,_,C,M,P,B)}emplace(u,f,_,C,M,P,B,U){const W=10*u,ee=5*u;return this.uint16[W+0]=f,this.uint16[W+1]=_,this.uint16[W+2]=C,this.uint16[W+3]=M,this.float32[ee+2]=P,this.float32[ee+3]=B,this.float32[ee+4]=U,u}}lT.prototype.bytesPerElement=20,Dr(lT,"StructArrayLayout4ui3f20");class cT extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.int16[1*u+0]=f,u}}cT.prototype.bytesPerElement=2,Dr(cT,"StructArrayLayout1i2");class dT extends to{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(u){const f=this.length;return this.resize(f+1),this.emplace(f,u)}emplace(u,f){return this.uint8[1*u+0]=f,u}}dT.prototype.bytesPerElement=1,Dr(dT,"StructArrayLayout1ub1");class Wz extends Y2{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]}}Wz.prototype.size=40;class UP extends aT{get(u){return new Wz(this,u)}}Dr(UP,"CollisionBoxArray");class Kz extends Y2{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(u){this._structArray.uint8[this._pos1+49]=u}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(u){this._structArray.uint8[this._pos1+50]=u}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(u){this._structArray.uint32[this._pos4+13]=u}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(u){this._structArray.uint8[this._pos1+58]=u}}Kz.prototype.size=60;class Yz extends iT{get(u){return new Kz(this,u)}}Dr(Yz,"PlacedSymbolArray");class tN extends Y2{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(u){this._structArray.uint32[this._pos4+14]=u}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(u){this._structArray.float32[this._pos4+18]=u}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}tN.prototype.size=80;class Zz extends OP{get(u){return new tN(this,u)}}Dr(Zz,"SymbolInstanceArray");class Xz extends Bm{getoffsetX(u){return this.float32[1*u+0]}}Dr(Xz,"GlyphOffsetArray");class sN extends om{getx(u){return this.int16[2*u+0]}gety(u){return this.int16[2*u+1]}}Dr(sN,"SymbolLineVertexArray");class Qz extends Y2{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]}}Qz.prototype.size=12;class qP extends zP{get(u){return new Qz(this,u)}}Dr(qP,"FeatureIndexArray");class Jz extends Ef{geta_centroid_pos0(u){return this.uint16[2*u+0]}geta_centroid_pos1(u){return this.uint16[2*u+1]}}Dr(Jz,"FillExtrusionCentroidArray");class VP extends Y2{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]}}VP.prototype.size=6;class HP extends jx{get(u){return new VP(this,u)}}Dr(HP,"FillExtrusionWallArray");const e7=Ta([{name:"a_pos",components:2,type:"Int16"}],4),Tge=Ta([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),Ege=Ta([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Bi{constructor(u=[]){this.segments=u}_prepareSegment(u,f,_,C,M){let P=this.segments[this.segments.length-1];return u>Bi.MAX_VERTEX_ARRAY_LENGTH&&Rr(`Max vertices per segment is ${Bi.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${u}`),(!P||P.vertexLength+u>Bi.MAX_VERTEX_ARRAY_LENGTH||P.sortKey!==C||M!==void 0&&P&&P.batchIndex!==void 0&&P.batchIndex!==M)&&(P={vertexOffset:f,primitiveOffset:_,vertexLength:0,primitiveLength:0},C!==void 0&&(P.sortKey=C),M!==void 0&&(P.batchIndex=M),this.segments.push(P)),P}prepareSegment(u,f,_,C,M){return this._prepareSegment(u,f.length,_.length,C,M)}get(){return this.segments}destroy(){for(const u of this.segments)for(const f in u.vaos)u.vaos[f].destroy()}static simpleSegment(u,f,_,C){return new Bi([{vertexOffset:u,primitiveOffset:f,vertexLength:_,primitiveLength:C,vaos:{},sortKey:0}])}}function uT(g,u){return 256*(g=ze(Math.floor(g),0,255))+ze(Math.floor(u),0,255)}Bi.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Dr(Bi,"SegmentVector");const Age=Ta([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),Mge=Ta([{name:"a_pattern_b",components:4,type:"Uint16"}]),Ige=Ta([{name:"a_dash",components:4,type:"Uint16"}]);class rN{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(u,f,_,C){this.ids.push(GP(u)),this.positions.push(f,_,C)}eachPosition(u,f){const _=GP(u);let C=0,M=this.ids.length-1;for(;C>1;this.ids[P]>=_?M=P:C=P+1}for(;this.ids[C]===_;)f(this.positions[3*C],this.positions[3*C+1],this.positions[3*C+2]),C++}static serialize(u,f){const _=new Float64Array(u.ids),C=new Uint32Array(u.positions);return nN(_,C,0,_.length-1),f&&(f.add(_.buffer),f.add(C.buffer)),{ids:_,positions:C}}static deserialize(u){const f=new rN;let _;f.ids=u.ids,f.positions=u.positions;for(const C of f.ids)C!==_&&f.uniqueIds.push(C),_=C;return f.indexed=!0,f}}function GP(g){const u=+g;return Number.isSafeInteger(u)?u:yx(String(g))}function nN(g,u,f,_){for(;f<_;){const C=g[f+_>>1];let M=f-1,P=_+1;for(;;){do M++;while(g[M]C);if(M>=P)break;zm(g,M,P),zm(u,3*M,3*P),zm(u,3*M+1,3*P+1),zm(u,3*M+2,3*P+2)}P-f<_-P?(nN(g,u,f,P),f=P+1):(nN(g,u,P+1,_),_=P)}}function zm(g,u,f){const _=g[u];g[u]=g[f],g[f]=_}Dr(rN,"FeaturePositionMap");class Af{constructor(u){this.gl=u.gl,this.initialized=!1}fetchUniformLocation(u,f){return this.location||this.initialized||(this.location=this.gl.getUniformLocation(u,f),this.initialized=!0),!!this.location}set(u,f,_){throw new Error("Uniform#set() must be implemented by each concrete Uniform")}}class aN extends Af{constructor(u){super(u),this.current=0}set(u,f,_){this.fetchUniformLocation(u,f)&&this.current!==_&&(this.current=_,this.gl.uniform1i(this.location,_))}}class sc extends Af{constructor(u){super(u),this.current=0}set(u,f,_){this.fetchUniformLocation(u,f)&&this.current!==_&&(this.current=_,this.gl.uniform1f(this.location,_))}}class Mf extends Af{constructor(u){super(u),this.current=[0,0]}set(u,f,_){this.fetchUniformLocation(u,f)&&(_[0]===this.current[0]&&_[1]===this.current[1]||(this.current=_,this.gl.uniform2f(this.location,_[0],_[1])))}}class iN extends Af{constructor(u){super(u),this.current=[0,0,0]}set(u,f,_){this.fetchUniformLocation(u,f)&&(_[0]===this.current[0]&&_[1]===this.current[1]&&_[2]===this.current[2]||(this.current=_,this.gl.uniform3f(this.location,_[0],_[1],_[2])))}}class Lge extends Af{constructor(u){super(u),this.current=[0,0,0,0]}set(u,f,_){this.fetchUniformLocation(u,f)&&(_[0]===this.current[0]&&_[1]===this.current[1]&&_[2]===this.current[2]&&_[3]===this.current[3]||(this.current=_,this.gl.uniform4ui(this.location,_[0],_[1],_[2],_[3])))}}class hT extends Af{constructor(u){super(u),this.current=[0,0,0,0]}set(u,f,_){this.fetchUniformLocation(u,f)&&(_[0]===this.current[0]&&_[1]===this.current[1]&&_[2]===this.current[2]&&_[3]===this.current[3]||(this.current=_,this.gl.uniform4f(this.location,_[0],_[1],_[2],_[3])))}}class Pge extends Af{constructor(u){super(u),this.current=wr.transparent.toPremultipliedRenderColor(null)}set(u,f,_){this.fetchUniformLocation(u,f)&&(_.r===this.current.r&&_.g===this.current.g&&_.b===this.current.b&&_.a===this.current.a||(this.current=_,this.gl.uniform4f(this.location,_.r,_.g,_.b,_.a)))}}const E=new Float32Array(16);class p extends Af{constructor(u){super(u),this.current=E}set(u,f,_){if(this.fetchUniformLocation(u,f)){if(_[12]!==this.current[12]||_[0]!==this.current[0])return this.current=_,void this.gl.uniformMatrix4fv(this.location,!1,_);for(let C=1;C<16;C++)if(_[C]!==this.current[C]){this.current=_,this.gl.uniformMatrix4fv(this.location,!1,_);break}}}}const j=new Float32Array(9),L=new Float32Array(4);class O extends Af{constructor(u){super(u),this.current=L}set(u,f,_){if(this.fetchUniformLocation(u,f)){for(let C=0;C<4;C++)if(_[C]!==this.current[C]){this.current=_,this.gl.uniformMatrix2fv(this.location,!1,_);break}}}}function q(g){return[uT(255*g.r,255*g.g),uT(255*g.b,255*g.a)]}function H(g,u,f,_,C,M,P,B){return!!g&&(g.kind==="composite"||g.kind==="source"?g.evaluate(new ui(0,{brightness:M,worldview:B}),u,f,C,_,P)==="none":g.value==="none")}class Y{constructor(u,f,_,C){this.value=u,this.uniformNames=f.map(M=>`u_${M}`),this.type=_,this.context=C}setUniform(u,f,_,C,M){const P=C.constantOr(this.value);f.set(u,M,P instanceof wr?P.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):P)}getBinding(u,f){return this.type==="color"?new Pge(u):new sc(u)}}class te{constructor(u,f){this.uniformNames=f.map(_=>`u_${_}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(u,f){this.pixelRatio=u.pixelRatio||1,this.pattern=u.tl.concat(u.br),this.patternTransition=f?f.tl.concat(f.br):this.pattern}setUniform(u,f,_,C,M){let P=null;M!=="u_pattern"&&M!=="u_dash"||(P=this.pattern),M==="u_pattern_b"&&(P=this.patternTransition),M==="u_pixel_ratio"&&(P=this.pixelRatio),P&&f.set(u,M,P)}getBinding(u,f){return f==="u_pattern"||f==="u_pattern_b"||f==="u_dash"?new Lge(u):new sc(u)}}class de{constructor(u,f,_,C){this.expression=u,this.type=_,this.maxValue=0,this.paintVertexAttributes=f.map(M=>({name:`a_${M}`,type:"Float32",components:_==="color"?2:1,offset:0})),this.paintVertexArray=new C}populatePaintArray(u,f,_,C,M,P,B,U){const W=this.paintVertexArray.length,ee=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new ui(0,{brightness:P,worldview:U}),f,{},M,C,B):this.expression.kind==="constant"&&this.expression.value,se=H(this.lutExpression,f,{},C,M,P,B,U);this.paintVertexArray.resize(u),this._setPaintValue(W,u,ee,se?null:this.context.lut)}updatePaintArray(u,f,_,C,M,P,B,U){const W=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:B,worldview:U},_,C,void 0,M):this.expression.kind==="constant"&&this.expression.value,ee=H(this.lutExpression,_,C,M,void 0,B,void 0,U);this._setPaintValue(u,f,W,ee?null:this.context.lut)}_setPaintValue(u,f,_,C){if(this.type==="color"){const M=q(_.toPremultipliedRenderColor(C));for(let P=u;P`u_${B}_t`),this.type=_,this.useIntegerZoom=C,this.context=M,this.maxValue=0,this.paintVertexAttributes=f.map(B=>({name:`a_${B}`,type:"Float32",components:_==="color"?4:2,offset:0})),this.paintVertexArray=new P}populatePaintArray(u,f,_,C,M,P,B,U){const W=this.expression.evaluate(new ui(this.context.zoom,{brightness:P,worldview:U}),f,{},M,C,B),ee=this.expression.evaluate(new ui(this.context.zoom+1,{brightness:P,worldview:U}),f,{},M,C,B),se=H(this.lutExpression,f,{},C,M,P,B,U),ae=this.paintVertexArray.length;this.paintVertexArray.resize(u),this._setPaintValue(ae,u,W,ee,se?null:this.context.lut)}updatePaintArray(u,f,_,C,M,P,B,U){const W=this.expression.evaluate({zoom:this.context.zoom,brightness:B,worldview:U},_,C,void 0,M),ee=this.expression.evaluate({zoom:this.context.zoom+1,brightness:B,worldview:U},_,C,void 0,M),se=H(this.lutExpression,_,C,M,void 0,B,void 0,U);this._setPaintValue(u,f,W,ee,se?null:this.context.lut)}_setPaintValue(u,f,_,C,M){if(this.type==="color"){const P=q(_.toPremultipliedRenderColor(M)),B=q(C.toPremultipliedRenderColor(M));for(let U=u;U!0){this.binders={},this._buffers=[],this.context=f;const C=[],M=u;for(const P in u.paint._values){const B=M.paint.get(P);if(P.endsWith("-use-theme")||!_(P)||!(B instanceof u1&&z5(B.property.specification)))continue;const U=$e(P,u.type),W=B.value,ee=B.property.specification.type,se=!!B.property.useIntegerZoom,ae=P==="line-dasharray"||P.endsWith("pattern"),me=M.paint.get(`${P}-use-theme`),ge=P==="line-dasharray"&&M.layout.get("line-cap").value.kind!=="constant"||me&&me.value.kind!=="constant";if(W.kind!=="constant"||ge)if(W.kind==="source"||ge||ae){const we=pt(P,ee,"source");this.binders[P]=ae?new Ce(W,U,ee,we,u.id):new de(W,U,ee,we),C.push(`/a_${P}`)}else{const we=pt(P,ee,"composite");this.binders[P]=new pe(W,U,ee,se,f,we),C.push(`/z_${P}`)}else this.binders[P]=ae?new te(W.value,U):new Y(W.value,U,ee,f),C.push(`/u_${P}`);me&&(this.binders[P].lutExpression=me.value)}this.cacheKey=C.sort().join("")}getMaxValue(u){const f=this.binders[u];return f instanceof de||f instanceof pe?f.maxValue:0}populatePaintArrays(u,f,_,C,M,P,B,U){for(const W in this.binders){const ee=this.binders[W];ee.context=this.context,(ee instanceof de||ee instanceof pe||ee instanceof Ce)&&ee.populatePaintArray(u,f,_,C,M,P,B,U)}}setConstantPatternPositions(u,f){for(const _ in this.binders){const C=this.binders[_];C instanceof te&&C.setConstantPatternPositions(u,f)}}getPatternTransitionVertexBuffer(u){const f=this.binders[u];return f instanceof Ce?f.paintTransitionVertexBuffer:null}updatePaintArrays(u,f,_,C,M,P,B,U,W,ee){let se=!1;const ae=Object.keys(u),me=ae.length!==0&&!U,ge=me?ae:f.uniqueIds;this.context.lut=M.lut;for(const we in this.binders){const Ee=this.binders[we];if(Ee.context=this.context,(Ee instanceof de||Ee instanceof pe||Ee instanceof Ce)&&Ee.expression&&Ee.expression.kind&&Ee.expression.kind!=="constant"&&(Ee.expression.isStateDependent===!0||Ee.expression.isLightConstant===!1)){const Fe=M.paint.get(we);Ee.expression=Fe.value;for(const Qe of ge){const Ve=u[Qe.toString()];f.eachPosition(Qe,(at,ut,ft)=>{const Bt=C.feature(at);Ee.updatePaintArray(ut,ft,Bt,Ve,P,B,W,ee)})}if(!me)for(const Qe of _.uniqueIds){const Ve=u[Qe.toString()];_.eachPosition(Qe,(at,ut,ft)=>{const Bt=C.feature(at);Ee.updatePaintArray(ut,ft,Bt,Ve,P,B,W,ee)})}se=!0}}return se}defines(){const u=[];for(const f in this.binders){const _=this.binders[f];(_ instanceof Y||_ instanceof te)&&u.push(..._.uniformNames.map(C=>`#define HAS_UNIFORM_${C}`))}return u}getPaintVertexBuffers(){return this._buffers}getUniforms(u){const f=[];for(const _ in this.binders){const C=this.binders[_];if(C instanceof Y||C instanceof te||C instanceof pe)for(const M of C.uniformNames)f.push({name:M,property:_,binding:C.getBinding(u,M)})}return f}setUniforms(u,f,_,C,M){for(const{name:P,property:B,binding:U}of _)this.binders[B].setUniform(u,U,M,C.get(B),P)}updatePaintBuffers(){this._buffers=[];for(const u in this.binders){const f=this.binders[u];(f instanceof de||f instanceof pe||f instanceof Ce)&&f.paintVertexBuffer&&this._buffers.push(f.paintVertexBuffer),f instanceof Ce&&f.paintTransitionVertexBuffer&&this._buffers.push(f.paintTransitionVertexBuffer)}}upload(u){for(const f in this.binders){const _=this.binders[f];(_ instanceof de||_ instanceof pe||_ instanceof Ce)&&_.upload(u)}this.updatePaintBuffers()}destroy(){for(const u in this.binders){const f=this.binders[u];(f instanceof de||f instanceof pe||f instanceof Ce)&&f.destroy()}}}class Me{constructor(u,f,_=()=>!0){this.programConfigurations={};for(const C of u)this.programConfigurations[C.id]=new je(C,f,_);this.needsUpload=!1,this._featureMap=new rN,this._featureMapWithoutIds=new rN,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(u,f,_,C,M,P,B,U,W){for(const ee in this.programConfigurations)this.programConfigurations[ee].populatePaintArrays(u,f,C,M,P,B,U,W);f.id!==void 0?this._featureMap.add(f.id,_,this._bufferOffset,u):(this._featureMapWithoutIds.add(this._idlessCounter,_,this._bufferOffset,u),this._idlessCounter+=1),this._bufferOffset=u,this.needsUpload=!0}updatePaintArrays(u,f,_,C,M,P,B,U){for(const W of _)this.needsUpload=this.programConfigurations[W.id].updatePaintArrays(u,this._featureMap,this._featureMapWithoutIds,f,W,C,M,P,B||0,U)||this.needsUpload}get(u){return this.programConfigurations[u]}upload(u){if(this.needsUpload){for(const f in this.programConfigurations)this.programConfigurations[f].upload(u);this.needsUpload=!1}}destroy(){for(const u in this.programConfigurations)this.programConfigurations[u].destroy()}}const qe={"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 $e(g,u){return qe[g]||[g.replace(`${u}-`,"").replace(/-/g,"_")]}const nt={"line-pattern":{source:Nx,composite:Nx},"fill-pattern":{source:Nx,composite:Nx},"fill-extrusion-pattern":{source:Nx,composite:Nx},"line-dasharray":{source:v_,composite:v_}},rt={color:{source:f1,composite:$g},number:{source:Bm,composite:f1}};function pt(g,u,f){const _=nt[g];return _&&_[f]||rt[u][f]}Dr(Y,"ConstantBinder"),Dr(te,"PatternConstantBinder"),Dr(de,"SourceExpressionBinder"),Dr(Ce,"PatternCompositeBinder"),Dr(pe,"CompositeExpressionBinder"),Dr(je,"ProgramConfiguration",{omit:["_buffers"]}),Dr(Me,"ProgramConfigurationSet");const vt=fr/Math.PI/2,ot=64,Ut=[ot,32,16],Tt=-vt,$t=vt;function _t(g,u,f,_=vt){return f=Pr(f),[g*Math.sin(f)*_,-u*_,g*Math.cos(f)*_]}function St(g,u,f){return _t(Math.cos(Pr(g)),Math.sin(Pr(g)),u,f)}const Rt=63710088e-1,Zt=2*Math.PI*Rt;class qt{constructor(u,f){if(isNaN(u)||isNaN(f))throw new Error(`Invalid LngLat object: (${u}, ${f})`);if(this.lng=+u,this.lat=+f,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new qt(gt(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(u){const f=Math.PI/180,_=this.lat*f,C=u.lat*f,M=Math.sin(_)*Math.sin(C)+Math.cos(_)*Math.cos(C)*Math.cos((u.lng-this.lng)*f);return Rt*Math.acos(Math.min(M,1))}toBounds(u=0){const f=360*u/40075017,_=f/Math.cos(Math.PI/180*this.lat);return new xs({lng:this.lng-_,lat:this.lat-f},{lng:this.lng+_,lat:this.lat+f})}toEcef(u){return St(this.lat,this.lng,vt+u*vt/Rt)}static convert(u){if(u instanceof qt)return u;if(Array.isArray(u)&&(u.length===2||u.length===3))return new qt(Number(u[0]),Number(u[1]));if(!Array.isArray(u)&&typeof u=="object"&&u!==null)return new qt(Number("lng"in u?u.lng:u.lon),Number(u.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 xs{constructor(u,f){u&&(f?this.setSouthWest(u).setNorthEast(f):Array.isArray(u)&&u.length===4?this.setSouthWest([u[0],u[1]]).setNorthEast([u[2],u[3]]):this.setSouthWest(u[0]).setNorthEast(u[1]))}setNorthEast(u){return this._ne=u instanceof qt?new qt(u.lng,u.lat):qt.convert(u),this}setSouthWest(u){return this._sw=u instanceof qt?new qt(u.lng,u.lat):qt.convert(u),this}extend(u){const f=this._sw,_=this._ne;let C,M;if(u instanceof qt)C=u,M=u;else{if(!(u instanceof xs))return Array.isArray(u)?u.length===4||u.every(Array.isArray)?this.extend(xs.convert(u)):this.extend(qt.convert(u)):typeof u=="object"&&u!==null&&u.hasOwnProperty("lat")&&(u.hasOwnProperty("lon")||u.hasOwnProperty("lng"))?this.extend(qt.convert(u)):this;if(C=u._sw,M=u._ne,!C||!M)return this}return f||_?(f.lng=Math.min(C.lng,f.lng),f.lat=Math.min(C.lat,f.lat),_.lng=Math.max(M.lng,_.lng),_.lat=Math.max(M.lat,_.lat)):(this._sw=new qt(C.lng,C.lat),this._ne=new qt(M.lng,M.lat)),this}getCenter(){return new qt((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 qt(this.getWest(),this.getNorth())}getSouthEast(){return new qt(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(u){const{lng:f,lat:_}=qt.convert(u);let C=this._sw.lng<=f&&f<=this._ne.lng;return this._sw.lng>this._ne.lng&&(C=this._sw.lng>=f&&f>=this._ne.lng),this._sw.lat<=_&&_<=this._ne.lat&&C}static convert(u){if(u)return u instanceof xs?u:new xs(u)}}function as(g){return Zt*Math.cos(g*Math.PI/180)}function Os(g){return(180+g)/360}function Hs(g){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+g*Math.PI/360)))/360}function Qt(g,u){return g/as(u)}function Ht(g){return 360*g-180}function us(g){return 360/Math.PI*Math.atan(Math.exp((180-360*g)*Math.PI/180))-90}function vs(g,u){return g*as(us(u))}const ks=85.051129;function cr(g){return Math.cos(Pr(ze(g,-85.051129,ks)))}function Js(g,u){const f=ze(u,0,25.5),_=Math.pow(2,f);return cr(g)*Zt/(512*_)}function er(g){return 1/Math.cos(g*Math.PI/180)}function Us(g,u=0){const f=Math.exp(Math.PI*(1-(g.y+u/fr)/(1<=U?(Kr(g,u,f,W,ee,M,se,B,U),Kr(g,W,ee,_,C,se,P,B,U)):g.push(P)}function Er(g,u,f){let _=g[0],C=_.x,M=_.y;u(_);const P=[_];for(let B=1;Bg.x+1||_g.y+1)&&Rr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),g}function pn(g,u,f){const _=g.loadGeometry(),C=g.extent,M=fr/C;if(u&&f&&f.projection.isReprojectedInTileSpace){const P=1<{const me=Ht((u.x+ae.x/C)/P),ge=us((u.y+ae.y/C)/P),we=ee.project(me,ge);ae.x=(we.x*B-U)*C,ae.y=(we.y*B-W)*C};for(let ae=0;ae<_.length;ae++)if(g.type!==1)_[ae]=Er(_[ae],se,1);else{const me=[];for(const ge of _[ae])ge.x<0||ge.x>=C||ge.y<0||ge.y>=C||(se(ge),me.push(ge));_[ae]=me}}for(const P of _)for(const B of P)oa(B,M);return _}function la(g,u){return{type:g.type,id:g.id,properties:g.properties,geometry:u?pn(g):[]}}class Dn{constructor(u,f,_,C,M){this.properties={},this.extent=_,this.type=0,this.id=void 0,this._pbf=u,this._geometry=-1,this._keys=C,this._values=M,u.readFields(Wa,this,f)}loadGeometry(){const u=this._pbf;u.pos=this._geometry;const f=u.readVarint()+u.pos,_=[];let C,M=1,P=0,B=0,U=0;for(;u.pos>3}if(P--,M===1||M===2)B+=u.readSVarint(),U+=u.readSVarint(),M===1&&(C&&_.push(C),C=[]),C&&C.push(new ss(B,U));else{if(M!==7)throw new Error(`unknown command ${M}`);C&&C.push(C[0].clone())}}return C&&_.push(C),_}bbox(){const u=this._pbf;u.pos=this._geometry;const f=u.readVarint()+u.pos;let _=1,C=0,M=0,P=0,B=1/0,U=-1/0,W=1/0,ee=-1/0;for(;u.pos>3}if(C--,_===1||_===2)M+=u.readSVarint(),P+=u.readSVarint(),MU&&(U=M),Pee&&(ee=P);else if(_!==7)throw new Error(`unknown command ${_}`)}return[B,W,U,ee]}toGeoJSON(u,f,_){const C=this.extent*Math.pow(2,_),M=this.extent*u,P=this.extent*f,B=this.loadGeometry();function U(ae){return[360*(ae.x+M)/C-180,360/Math.PI*Math.atan(Math.exp((1-2*(ae.y+P)/C)*Math.PI))-90]}function W(ae){return ae.map(U)}let ee;if(this.type===1){const ae=[];for(const ge of B)ae.push(ge[0]);const me=W(ae);ee=ae.length===1?{type:"Point",coordinates:me[0]}:{type:"MultiPoint",coordinates:me}}else if(this.type===2){const ae=B.map(W);ee=ae.length===1?{type:"LineString",coordinates:ae[0]}:{type:"MultiLineString",coordinates:ae}}else{if(this.type!==3)throw new Error("unknown feature type");{const ae=function(ge){const we=ge.length;if(we<=1)return[ge];const Ee=[];let Fe,Qe;for(let Ve=0;Ve=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[u];const f=this._pbf.readVarint()+this._pbf.pos;return new Dn(this._pbf,f,this.extent,this._keys,this._values)}}function zi(g,u,f){g===15?u.version=f.readVarint():g===1?u.name=f.readString():g===5?u.extent=f.readVarint():g===2?u._features.push(f.pos):g===3?u._keys.push(f.readString()):g===4&&u._values.push(function(_){let C=null;const M=_.readVarint()+_.pos;for(;_.pos>3;C=P===1?_.readString():P===2?_.readFloat():P===3?_.readDouble():P===4?_.readVarint64():P===5?_.readVarint():P===6?_.readSVarint():P===7?_.readBoolean():null}if(C==null)throw new Error("unknown feature value");return C}(f))}class ri{constructor(u,f){this.layers=u.readFields(Jn,{},f)}}function Jn(g,u,f){if(g===3){const _=new yo(f,f.readVarint()+f.pos);_.length&&(u[_.name]=_)}}const ea="3d_elevation_id",$i="level";class No{constructor(){this._valid=!1}reset(u){return this.feature=u,this._valid=!0,this._geometry=u.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(u,f){return this._valid&&u(f(this._geometry)),this}require(u,f,_){return this.get(u,!0,f,_)}optional(u,f,_){return this.get(u,!1,f,_)}success(){return this._valid}get(u,f,_,C){const M=this.feature.properties.hasOwnProperty(u)?+this.feature.properties[u]:void 0;return this._valid&&M!==void 0&&!Number.isNaN(M)?_(C?C(M):M):f&&(this._valid=!1),this}}class ni{constructor(u,f){this.featureFunc=u,this.vertexFunc=f}parseFeature(u,f,_){return this.featureFunc(u,f,_)}parseVertex(u,f,_){return this.vertexFunc(u,f,_)}}const qn=new ni((g,u,f)=>g.reset(u).require(ea,_=>{f.id=_}).optional("fixed_height_relative",_=>{f.constantHeight=_},Ei.decodeRelativeHeight).geometry(_=>{f.bounds=_},FL).success(),(g,u,f)=>g.reset(u).require(ea,_=>{f.id=_}).require("elevation_idx",_=>{f.idx=_}).require("extent",_=>{f.extent=_}).require("height_relative",_=>{f.height=_},Ei.decodeRelativeHeight).geometry(_=>{f.position=_},Ei.getPoint).success()),uo=new ni((g,u,f)=>g.reset(u).require(ea,_=>{f.id=_}).optional("fixed_height",_=>{f.constantHeight=_},Ei.decodeMetricHeight).geometry(_=>{f.bounds=_},FL).success(),(g,u,f)=>g.reset(u).require(ea,_=>{f.id=_}).require("elevation_idx",_=>{f.idx=_}).require("extent",_=>{f.extent=_}).require("height",_=>{f.height=_},Ei.decodeMetricHeight).geometry(_=>{f.position=_},Ei.getPoint).success());class Ei{static getPoint(u){return is(u[0][0].x,u[0][0].y)}static decodeRelativeHeight(u){return 1e-4*u*5}static decodeMetricHeight(u){return 1e-4*u}static getVersionSchema(u){return u?u==="1.0.1"?uo:void 0:qn}static parse(u){const f=[],_=[],C=u.length,M=new No;for(let P=0;P=0);if(M===0)return 0;M!==u.length&&(f=!1)}return f?2:1}function rc(g,u){for(const f of g.projections){const _=Ul(u,g.points[0],f.axis);if(f.projection[1]<_[0]||f.projection[0]>_[1])return 0}return 1}function Yc(g,u){let f=0;const _=[0,0,0,0];for(let C=0;C=0&&f++;return f}class lm{constructor(u,f){this.points=u||new Array(8).fill([0,0,0]),this.planes=f||new Array(6).fill([0,0,0,0]),this.bounds=fi.fromPoints(this.points),this.projections=[],this.frustumEdges=[We([],this.points[2],this.points[3]),We([],this.points[0],this.points[3]),We([],this.points[4],this.points[0]),We([],this.points[5],this.points[1]),We([],this.points[6],this.points[2]),We([],this.points[7],this.points[3])];for(const _ of this.frustumEdges){const C=[0,-_[2],_[1]],M=[_[2],0,-_[0]];this.projections.push({axis:C,projection:Ul(this.points,this.points[0],C)}),this.projections.push({axis:M,projection:Ul(this.points,this.points[0],M)})}}static fromInvProjectionMatrix(u,f,_,C){const M=Math.pow(2,_),P=[[-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(W=>{const ee=xt([],W,u),se=1/ee[3]/f*M;return(ae=ee)[0]=(me=ee)[0]*(ge=[se,se,C?1/ee[3]:se,se])[0],ae[1]=me[1]*ge[1],ae[2]=me[2]*ge[2],ae[3]=me[3]*ge[3],ae;var ae,me,ge}),B=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(W=>{const ee=Le([],Te([],We([],P[W[0]],P[W[1]]),We([],P[W[2]],P[W[1]]))),se=-Ie(ee,P[W[1]]);return ee.concat(se)}),U=[];for(let W=0;WW[1]||W[0]>U[1])return 0}return 1}containsPoint(u){for(const f of this.planes){const _=f[3];if(Ie([f[0],f[1],f[2]],u)+_<0)return!1}return!0}}class fi{static fromPoints(u){const f=[1/0,1/0,1/0],_=[-1/0,-1/0,-1/0];for(const C of u)ce(f,f,C),ve(_,_,C);return new fi(f,_)}static fromTileIdAndHeight(u,f,_){const C=1<u.max[f]||u.min[f]>this.max[f])return!1;return!0}intersectsAabbXY(u){return!(this.min[0]>u.max[0]||u.min[0]>this.max[0]||this.min[1]>u.max[1]||u.min[1]>this.max[1])}encapsulate(u){for(let f=0;f<3;f++)this.min[f]=Math.min(this.min[f],u.min[f]),this.max[f]=Math.max(this.max[f],u.max[f])}encapsulatePoint(u){for(let f=0;f<3;f++)this.min[f]=Math.min(this.min[f],u[f]),this.max[f]=Math.max(this.max[f],u[f])}closestPoint(u){return[Math.max(Math.min(this.max[0],u[0]),this.min[0]),Math.max(Math.min(this.max[1],u[1]),this.min[1]),Math.max(Math.min(this.max[2],u[2]),this.min[2])]}}Dr(fi,"Aabb");class $m{constructor(u,f){this.feature=u,this.metersToTile=f,this.index=0}get(){const u=this.feature.vertices[this.index],f=this.feature.vertexProps[this.index].dir,_=f[1],C=-f[0],M=(u.extent+1)*this.metersToTile;return[new ss(Math.trunc(u.position[0]+_*M),Math.trunc(u.position[1]+C*M)),new ss(Math.trunc(u.position[0]-_*M),Math.trunc(u.position[1]-C*M))]}next(){this.index++}valid(){return this.index{return B.a0?be(U,U,1/W):oe(U,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(u){if(this.edges.length===0)return;let f=0,_=Number.POSITIVE_INFINITY,C=0;const[M,P,B,U,W,ee,se]=this._tmpVec2;Bs(se,u.x,u.y);const ae=new jl(se,null);for(let me=0;me0?Ur(U,B)/at:0,ft=ze(ut,0,1),Bt=Math.abs((ut-ft)*this.edgeProps[me].len);lr(W,se,Ee),Bs(ee,we[1],-we[0]);const Et=Bt+Math.abs(Ur(W,ee));Et<_&&(f=me,_=Et,C=ft)}return[f,C]}tessellate(u){const f=X(),_=X(),C=X(),M=X();for(let P=this.edges.length-1;P>=0;--P){const B=this.edges[P].a,U=this.edges[P].b,{position:W,height:ee,extent:se}=this.vertices[B],{position:ae,height:me,extent:ge}=this.vertices[U],we=this.vertexProps[B].dir,Ee=this.vertexProps[U].dir;if(oe(f,W[0]/u,W[1]/u,ee),oe(_,ae[0]/u,ae[1]/u,me),oe(C,we[1],-we[0],0),be(C,C,se),oe(M,Ee[1],-Ee[0],0),be(M,M,ge),this.distSqLines(le(f[0]+.5*C[0],f[1]+.5*C[1],f[2]+.5*C[2]),le(_[0]-.5*M[0],_[1]-.5*M[1],_[2]-.5*M[2]),le(f[0]-.5*C[0],f[1]-.5*C[1],f[2]-.5*C[2]),le(_[0]+.5*M[0],_[1]+.5*M[1],_[2]+.5*M[2]))<=.0025000000000000005)continue;const Fe=this.vertices.length,Qe=ps(yt(),W,ae);this.vertices.push({position:kr(Qe,Qe,.5),height:.5*(ee+me),extent:.5*(se+ge)});const Ve=ps(yt(),we,Ee);this.vertexProps.push({dir:qr(Ve,Ve)}),this.edges.splice(P,1),this.edgeProps.splice(P,1),this.edges.push({a:B,b:Fe}),this.edges.push({a:Fe,b:U});const at=lr(yt(),this.vertices[Fe].position,W),ut=Lr(at),ft={vec:at,dir:kr(yt(),at,1/ut),len:ut};this.edgeProps.push(ft),this.edgeProps.push(ft)}}distSqLines(u,f,_,C){const M=ie(X(),f,u),P=ie(X(),C,_),B=ie(X(),u,_),U=Ie(M,M),W=Ie(M,P),ee=Ie(M,B),se=Ie(P,P),ae=Ie(P,B),me=U*se-W*W;if(me===0)return De(xe(M,_,C,Ie(B,P)/Ie(P,P)),u);const ge=(U*ae-W*ee)/me;return De(xe(M,u,f,(W*ae-ee*se)/me),xe(P,_,C,ge))}}class qi{static parseFrom(u,f){const _=Ei.parse(u);if(!_)return[];let{vertices:C,features:M}=_;const P=1/Us(f);M.sort((ee,se)=>ee.id-se.id),C.sort((ee,se)=>ee.id-se.id||ee.idx-se.idx),C=C.filter((ee,se,ae)=>se===ae.findIndex(me=>me.id===ee.id&&me.idx===ee.idx));const B=new Array;let U=0;const W=C.length;for(const ee of M){if(ee.constantHeight){B.push(new Um(ee.id,ee.bounds,ee.constantHeight));continue}for(;U!==W&&C[U].idC.id===_)}}class Yi{constructor(u,f){this.zScale=1,this.xOffset=0,this.yOffset=0,u.equals(f)||(this.zScale=Math.pow(2,f.z-u.z),this.xOffset=(u.x*this.zScale-f.x)*fr,this.yOffset=(u.y*this.zScale-f.y)*fr)}constantElevation(u,f){if(u.constantHeight!=null)return this.computeBiasedHeight(u.constantHeight,f)}pointElevation(u,f,_){const C=this.constantElevation(f,_);return C??(u.x=u.x*this.zScale+this.xOffset,u.y=u.y*this.zScale+this.yOffset,this.computeBiasedHeight(f.pointElevation(u),_))}computeBiasedHeight(u,f){return f<=0?u:u+f*st(0,f,u>=0?u:Math.abs(.5*u))}}Dr(Um,"ElevationFeature");class ji{constructor(u){this.zoom=u.zoom,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.projection=u.projection,this.layoutVertexArray=new om,this.indexArray=new ll,this.segments=new Bi,this.programConfigurations=new Me(u.layers,{zoom:u.zoom,lut:u.lut}),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Bm),this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,_,C){const M=this.layers[0],P=[];let B=null;M.type==="circle"&&(B=M.layout.get("circle-sort-key"));for(const{feature:W,id:ee,index:se,sourceLayerIndex:ae}of u){const me=this.layers[0]._featureFilter.needGeometry,ge=la(W,me);if(!this.layers[0]._featureFilter.filter(new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),ge,_))continue;const we=B?B.evaluate(ge,{},_):void 0,Ee={id:ee,properties:W.properties,type:W.type,sourceLayerIndex:ae,index:se,geometry:me?ge.geometry:pn(W,_,C),patterns:{},sortKey:we};P.push(Ee)}B&&P.sort((W,ee)=>W.sortKey-ee.sortKey);let U=null;C.projection.name==="globe"&&(this.globeExtVertexArray=new nT,U=C.projection);for(const W of P){const{geometry:ee,index:se,sourceLayerIndex:ae}=W,me=u[se].feature;this.addFeature(W,ee,se,f.availableImages,_,U,f.brightness,f.elevationFeatures),f.featureIndex.insert(me,ee,se,ae,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(u,f,_,C,M,P,B){this.programConfigurations.updatePaintArrays(u,f,M,_,C,P,B,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,e7.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=u.createVertexBuffer(this.globeExtVertexArray,Ege.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=u.createVertexBuffer(this.elevatedLayoutVertexArray,Tge.members))),this.programConfigurations.upload(u),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(u,f,_,C,M,P,B,U){let W;this.elevationMode!=="none"&&(W=qi.getElevationFeature(u,U));for(const ee of f)for(const se of ee){const ae=se.x,me=se.y;if(ae<0||ae>=fr||me<0||me>=fr)continue;if(P){const Ee=P.projectTilePoint(ae,me,M),Fe=P.upVector(M,ae,me);this.addGlobeExtVertex(Ee,Fe),this.addGlobeExtVertex(Ee,Fe),this.addGlobeExtVertex(Ee,Fe),this.addGlobeExtVertex(Ee,Fe)}const ge=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,u.sortKey),we=ge.vertexLength;if(this.addCircleVertex(ae,me,-1,-1),this.addCircleVertex(ae,me,1,-1),this.addCircleVertex(ae,me,1,1),this.addCircleVertex(ae,me,-1,1),this.elevationMode!=="none"){const Ee=W?W.pointElevation(new ss(ae,me)):0;this.hasElevation=this.hasElevation||Ee!==0;for(let Fe=0;Fe<4;Fe++)this.elevatedLayoutVertexArray.emplaceBack(Ee)}this.indexArray.emplaceBack(we,we+1,we+2),this.indexArray.emplaceBack(we,we+2,we+3),ge.vertexLength+=4,ge.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,_,{},C,M,B,void 0,this.worldview)}addCircleVertex(u,f,_,C){this.layoutVertexArray.emplaceBack(2*u+(_+1)/2,2*f+(C+1)/2)}addGlobeExtVertex(u,f){this.globeExtVertexArray.emplaceBack(u.x,u.y,u.z,f[0]*16384,f[1]*16384,f[2]*16384)}}function gl(g,u){for(let f=0;f1){if(i0(g,u))return!0;for(let _=0;_1?f:f.sub(u)._mult(C)._add(u))}function __(g,u){let f,_,C,M=!1;for(let P=0;Pu.y!=C.y>u.y&&u.x<(C.x-_.x)*(u.y-_.y)/(C.y-_.y)+_.x&&(M=!M)}return M}function Ph(g,u){let f=!1;for(let _=0,C=g.length-1;_u.y!=P.y>u.y&&u.x<(P.x-M.x)*(u.y-M.y)/(P.y-M.y)+M.x&&(f=!f)}return f}function o0(g,u,f,_,C){for(const P of g)if(u<=P.x&&f<=P.y&&_>=P.x&&C>=P.y)return!0;const M=[new ss(u,f),new ss(u,C),new ss(_,C),new ss(_,f)];if(g.length>2){for(const P of M)if(Ph(g,P))return!0}for(let P=0;PC.x&&u.x>C.x||g.y<_.y&&u.y<_.y||g.y>C.y&&u.y>C.y)return!1;const M=sn(g,u,f[0]);return M!==sn(g,u,f[1])||M!==sn(g,u,f[2])||M!==sn(g,u,f[3])}function c0(g,u,f,_,C,M){let P=u.y-g.y,B=g.x-u.x;if(M=M||0){const U=P*P+B*B;if(U===0)return!0;const W=Math.sqrt(U);P/=W,B/=W}return!((f.x-g.x)*P+(f.y-g.y)*B-M<0||(_.x-g.x)*P+(_.y-g.y)*B-M<0||(C.x-g.x)*P+(C.y-g.y)*B-M<0)}function mT(g,u,f,_,C,M,P){return!(c0(g,u,_,C,M,P)||c0(u,f,_,C,M,P)||c0(f,g,_,C,M,P)||c0(_,C,g,u,f,P)||c0(C,M,g,u,f,P)||c0(M,_,g,u,f,P))}function w_(g,u,f){const _=u.paint.get(g).value;return _.kind==="constant"?_.value:f.programConfigurations.get(u.id).getMaxValue(g)}function t7(g){return Math.sqrt(g[0]*g[0]+g[1]*g[1])}function CAe(g,u,f,_,C){if(!u[0]&&!u[1])return g;const M=ss.convert(u)._mult(C);f==="viewport"&&M._rotate(-_);const P=[];for(let B=0;B>f&&u.y===this.y>>f}url(u,f){const _=function(M,P,B){const U=2**B,W=2*Math.PI*6378137,ee=W*(M/U-.5),se=W*(.5-(P+1)/U);return`${ee},${se},${ee+W/U},${se+W/U}`}(this.x,this.y,this.z),C=function(M,P,B){let U,W="";for(let ee=M;ee>0;ee--)U=1<this.canonical.z?new nh(u,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new nh(u,this.wrap,u,this.canonical.x>>f,this.canonical.y>>f)}calculateScaledKey(u,f=!0){if(this.overscaledZ===u&&f)return this.key;if(u>this.canonical.z)return fT(this.wrap*+f,u,this.canonical.z,this.canonical.x,this.canonical.y);{const _=this.canonical.z-u;return fT(this.wrap*+f,u,u,this.canonical.x>>_,this.canonical.y>>_)}}isChildOf(u){if(u.wrap!==this.wrap)return!1;const f=this.canonical.z-u.canonical.z;return u.overscaledZ===0||u.overscaledZ>f&&u.canonical.y===this.canonical.y>>f}children(u){if(this.overscaledZ>=u)return[new nh(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const f=this.canonical.z+1,_=2*this.canonical.x,C=2*this.canonical.y;return[new nh(f,this.wrap,f,_,C),new nh(f,this.wrap,f,_+1,C),new nh(f,this.wrap,f,_,C+1),new nh(f,this.wrap,f,_+1,C+1)]}isLessThan(u){return this.wrapu.wrap)&&(this.overscaledZu.overscaledZ)&&(this.canonical.xu.canonical.x)&&this.canonical.y{let u=g.canonical.x-1,f=g.wrap;return u<0&&(u=(1<{let u=g.canonical.x+1,f=g.wrap;return u===1<new nh(g.overscaledZ,g.wrap,g.canonical.z,g.canonical.x,(g.canonical.y===0?1<new nh(g.overscaledZ,g.wrap,g.canonical.z,g.canonical.x,g.canonical.y===(1<1?null:function(_,C,M,P){const B=Math.sin(M);return _*(Math.sin((1-P)*M)/B)+C*(Math.sin(P*M)/B)}(g.a[u],g.b[u],g.angle,ze(f,0,1))+g.center[u]}function d0(g){if(g.z<=1)return Syt[g.z+2*g.y+g.x];const u=Rge(n7(g));return fi.fromPoints(u)}function y1(g,u,f){return be(g,g,1-f),Ue(g,g,u,f)}function PAe(g,u){const f=v1(u.zoom);if(f===0)return d0(g);const _=n7(g),C=Rge(_),M=Os(_.getWest())*u.worldSize,P=Os(_.getEast())*u.worldSize,B=Hs(_.getNorth())*u.worldSize,U=Hs(_.getSouth())*u.worldSize,W=[M,B,0],ee=[P,B,0],se=[M,U,0],ae=[P,U,0],me=N([],u.globeMatrix);return et(W,W,me),et(ee,ee,me),et(se,se,me),et(ae,ae,me),C[0]=y1(C[0],se,f),C[1]=y1(C[1],ae,f),C[2]=y1(C[2],ee,f),C[3]=y1(C[3],W,f),fi.fromPoints(C)}function DAe(g,u,f){for(const _ of g)et(_,_,u),be(_,_,f)}function RAe(g,u,f,_){const C=u/g.worldSize,M=g.globeMatrix;if(f.z<=1){const Ot=d0(f).getCorners();return DAe(Ot,M,C),fi.fromPoints(Ot)}const P=n7(f,_),B=Rge(P,vt+r7(g._tileCoverLift));DAe(B,M,C);const U=Number.MAX_VALUE,W=[-U,-U,-U],ee=[U,U,U];if(P.contains(g.center)){for(const Pt of B)ce(ee,ee,Pt),ve(W,W,Pt);W[2]=0;const Ot=g.point,Lt=[Ot.x*C,Ot.y*C,0];return ce(ee,ee,Lt),ve(W,W,Lt),new fi(ee,W)}if(g._tileCoverLift>0){for(const Ot of B)ce(ee,ee,Ot),ve(W,W,Ot);return new fi(ee,W)}const se=[M[12]*C,M[13]*C,M[14]*C],ae=P.getCenter(),me=ze(g.center.lat,-85.051129,ks),ge=ze(ae.lat,-85.051129,ks),we=Os(g.center.lng),Ee=Hs(me);let Fe=we-Os(ae.lng);const Qe=Ee-Hs(ge);Fe>.5?Fe-=1:Fe<-.5&&(Fe+=1);let Ve=0;Math.abs(Fe)>Math.abs(Qe)?Ve=Fe>=0?1:3:(Ve=Qe>=0?0:2,Ue(se,se,[M[4]*C,M[5]*C,M[6]*C],-Math.sin(Pr(Qe>=0?P.getSouth():P.getNorth()))*vt));const at=B[Ve],ut=B[(Ve+1)%4],ft=new Cyt(at,ut,se),Bt=[Dge(ft,0)||at[0],Dge(ft,1)||at[1],Dge(ft,2)||at[2]],Et=v1(g.zoom);if(Et>0){const Ot=function({x:Pt,y:hs,z:bs},Ts,Rs,Es,Ws){const ls=1/(1<.5?Ar=-1:ur<-.5&&(Ar=1),Ps=((Ps+Ar)*Ts-(Es*=Ts))*Rs+Es,zs=((zs+Ar)*Ts-Es)*Rs+Es,Ks=(Ks*Ts-(Ws*=Ts))*Rs+Ws,tr=(tr*Ts-Ws)*Rs+Ws,[[Ps,tr,0],[zs,tr,0],[zs,Ks,0],[Ps,Ks,0]]}(f,u,g._pixelsPerMercatorPixel,we,Ee);for(let Pt=0;PtMath.PI/2*1.01}const $Ae=Pr(85),Tyt=Math.cos($Ae),Eyt=Math.sin($Ae),Ayt=v(),UAe=g=>{const u=[];return g.paint.get("circle-pitch-alignment")==="map"&&u.push("PITCH_WITH_MAP"),g.paint.get("circle-pitch-scale")==="map"&&u.push("SCALE_WITH_MAP"),u};function qAe(g,u,f,_,C,M,P,B,U){if(M&&g.queryGeometry.isAboveHorizon)return!1;M&&(U*=g.pixelToTileUnitsFactor);const W=g.tileID.canonical,ee=f.projection.upVectorScale(W,f.center.lat,f.worldSize).metersToTile;for(const se of u)for(const ae of se){const me=ae.add(B),ge=C&&f.elevation?f.elevation.exaggeration()*C.getElevationAt(me.x,me.y,!0):0,we=f.projection.projectTilePoint(me.x,me.y,W);if(ge>0){const Ve=f.projection.upVector(W,me.x,me.y);we.x+=Ve[0]*ee*ge,we.y+=Ve[1]*ee*ge,we.z+=Ve[2]*ee*ge}const Ee=M?me:Myt(we.x,we.y,we.z,_),Fe=M?g.tilespaceRays.map(Ve=>Lyt(Ve,ge)):g.queryGeometry.screenGeometry,Qe=xt([],[we.x,we.y,we.z,1],_);if(!P&&M?U*=Qe[3]/f.cameraToCenterDistance:P&&!M&&(U*=f.cameraToCenterDistance/Qe[3]),M){const Ve=us((ae.y/fr+W.y)/(1<g.width||C.height>g.height||f.x>g.width-C.width||f.y>g.height-C.height)throw new RangeError("out of range source coordinates for image copy");if(C.width>u.width||C.height>u.height||_.x>u.width-C.width||_.y>u.height-C.height)throw new RangeError("out of range destination coordinates for image copy");const U=g.data,W=u.data,ee=M===4&&B;for(let se=0;se{u[g.evaluationKey]=U;const W=g.expression.evaluate(u),ee=W?W.toNonPremultipliedRenderColor(null):null;ee&&(C.data[P+B+0]=Math.floor(255*ee.r),C.data[P+B+1]=Math.floor(255*ee.g),C.data[P+B+2]=Math.floor(255*ee.b),C.data[P+B+3]=Math.floor(255*ee.a))};if(g.clips)for(let P=0,B=0;P<_;++P,B+=4*f)for(let U=0,W=0;U80*f){B=g[0],U=g[1];let ee=B,se=U;for(let ae=f;aeee&&(ee=me),ge>se&&(se=ge)}W=Math.max(ee-B,se-U),W=W!==0?32767/W:0}return XP(M,P,f,B,U,W,0),P}function JAe(g,u,f,_,C){let M;if(C===function(P,B,U,W){let ee=0;for(let se=B,ae=U-W;se0)for(let P=u;P=u;P-=_)M=rMe(P/_|0,g[P],g[P+1],M);return M&&xT(M,M.next)&&(e6(M),M=M.next),M}function lN(g,u){if(!g)return g;u||(u=g);let f,_=g;do if(f=!1,_.steiner||!xT(_,_.next)&&Zc(_.prev,_,_.next)!==0)_=_.next;else{if(e6(_),_=u=_.prev,_===_.next)break;f=!0}while(f||_!==u);return u}function XP(g,u,f,_,C,M,P){if(!g)return;!P&&M&&function(U,W,ee,se){let ae=U;do ae.z===0&&(ae.z=$ge(ae.x,ae.y,W,ee,se)),ae.prevZ=ae.prev,ae.nextZ=ae.next,ae=ae.next;while(ae!==U);ae.prevZ.nextZ=null,ae.prevZ=null,function(me){let ge,we=1;do{let Ee,Fe=me;me=null;let Qe=null;for(ge=0;Fe;){ge++;let Ve=Fe,at=0;for(let ft=0;ft0||ut>0&&Ve;)at!==0&&(ut===0||!Ve||Fe.z<=Ve.z)?(Ee=Fe,Fe=Fe.nextZ,at--):(Ee=Ve,Ve=Ve.nextZ,ut--),Qe?Qe.nextZ=Ee:me=Ee,Ee.prevZ=Qe,Qe=Ee;Fe=Ve}Qe.nextZ=null,we*=2}while(ge>1)}(ae)}(g,_,C,M);let B=g;for(;g.prev!==g.next;){const U=g.prev,W=g.next;if(M?Byt(g,_,C,M):Fyt(g))u.push(U.i,g.i,W.i),e6(g),g=W.next,B=W.next;else if((g=W)===B){P?P===1?XP(g=zyt(lN(g),u),u,f,_,C,M,2):P===2&&$yt(g,u,f,_,C,M):XP(lN(g),u,f,_,C,M,1);break}}}function Fyt(g){const u=g.prev,f=g,_=g.next;if(Zc(u,f,_)>=0)return!1;const C=u.x,M=f.x,P=_.x,B=u.y,U=f.y,W=_.y,ee=Math.min(C,M,P),se=Math.min(B,U,W),ae=Math.max(C,M,P),me=Math.max(B,U,W);let ge=_.next;for(;ge!==u;){if(ge.x>=ee&&ge.x<=ae&&ge.y>=se&&ge.y<=me&&QP(C,B,M,U,P,W,ge.x,ge.y)&&Zc(ge.prev,ge,ge.next)>=0)return!1;ge=ge.next}return!0}function Byt(g,u,f,_){const C=g.prev,M=g,P=g.next;if(Zc(C,M,P)>=0)return!1;const B=C.x,U=M.x,W=P.x,ee=C.y,se=M.y,ae=P.y,me=Math.min(B,U,W),ge=Math.min(ee,se,ae),we=Math.max(B,U,W),Ee=Math.max(ee,se,ae),Fe=$ge(me,ge,u,f,_),Qe=$ge(we,Ee,u,f,_);let Ve=g.prevZ,at=g.nextZ;for(;Ve&&Ve.z>=Fe&&at&&at.z<=Qe;){if(Ve.x>=me&&Ve.x<=we&&Ve.y>=ge&&Ve.y<=Ee&&Ve!==C&&Ve!==P&&QP(B,ee,U,se,W,ae,Ve.x,Ve.y)&&Zc(Ve.prev,Ve,Ve.next)>=0||(Ve=Ve.prevZ,at.x>=me&&at.x<=we&&at.y>=ge&&at.y<=Ee&&at!==C&&at!==P&&QP(B,ee,U,se,W,ae,at.x,at.y)&&Zc(at.prev,at,at.next)>=0))return!1;at=at.nextZ}for(;Ve&&Ve.z>=Fe;){if(Ve.x>=me&&Ve.x<=we&&Ve.y>=ge&&Ve.y<=Ee&&Ve!==C&&Ve!==P&&QP(B,ee,U,se,W,ae,Ve.x,Ve.y)&&Zc(Ve.prev,Ve,Ve.next)>=0)return!1;Ve=Ve.prevZ}for(;at&&at.z<=Qe;){if(at.x>=me&&at.x<=we&&at.y>=ge&&at.y<=Ee&&at!==C&&at!==P&&QP(B,ee,U,se,W,ae,at.x,at.y)&&Zc(at.prev,at,at.next)>=0)return!1;at=at.nextZ}return!0}function zyt(g,u){let f=g;do{const _=f.prev,C=f.next.next;!xT(_,C)&&tMe(_,f,f.next,C)&&JP(_,C)&&JP(C,_)&&(u.push(_.i,f.i,C.i),e6(f),e6(f.next),f=g=C),f=f.next}while(f!==g);return lN(f)}function $yt(g,u,f,_,C,M){let P=g;do{let B=P.next.next;for(;B!==P.prev;){if(P.i!==B.i&&Gyt(P,B)){let U=sMe(P,B);return P=lN(P,P.next),U=lN(U,U.next),XP(P,u,f,_,C,M,0),void XP(U,u,f,_,C,M,0)}B=B.next}P=P.next}while(P!==g)}function Uyt(g,u){let f=g.x-u.x;return f===0&&(f=g.y-u.y,f===0)&&(f=(g.next.y-g.y)/(g.next.x-g.x)-(u.next.y-u.y)/(u.next.x-u.x)),f}function qyt(g,u){const f=function(C,M){let P=M;const B=C.x,U=C.y;let W,ee=-1/0;if(xT(C,P))return P;do{if(xT(C,P.next))return P.next;if(U<=P.y&&U>=P.next.y&&P.next.y!==P.y){const we=P.x+(U-P.y)*(P.next.x-P.x)/(P.next.y-P.y);if(we<=B&&we>ee&&(ee=we,W=P.x=P.x&&P.x>=ae&&B!==P.x&&eMe(UW.x||P.x===W.x&&Vyt(W,P)))&&(W=P,ge=we)}P=P.next}while(P!==se);return W}(g,u);if(!f)return u;const _=sMe(f,g);return lN(_,_.next),lN(f,f.next)}function Vyt(g,u){return Zc(g.prev,g,u.prev)<0&&Zc(u.next,g,g.next)<0}function $ge(g,u,f,_,C){return(g=1431655765&((g=858993459&((g=252645135&((g=16711935&((g=(g-f)*C|0)|g<<8))|g<<4))|g<<2))|g<<1))|(u=1431655765&((u=858993459&((u=252645135&((u=16711935&((u=(u-_)*C|0)|u<<8))|u<<4))|u<<2))|u<<1))<<1}function Hyt(g){let u=g,f=g;do(u.x=(g-P)*(M-B)&&(g-P)*(_-B)>=(f-P)*(u-B)&&(f-P)*(M-B)>=(C-P)*(_-B)}function QP(g,u,f,_,C,M,P,B){return!(g===P&&u===B)&&eMe(g,u,f,_,C,M,P,B)}function Gyt(g,u){return g.next.i!==u.i&&g.prev.i!==u.i&&!function(f,_){let C=f;do{if(C.i!==f.i&&C.next.i!==f.i&&C.i!==_.i&&C.next.i!==_.i&&tMe(C,C.next,f,_))return!0;C=C.next}while(C!==f);return!1}(g,u)&&(JP(g,u)&&JP(u,g)&&function(f,_){let C=f,M=!1;const P=(f.x+_.x)/2,B=(f.y+_.y)/2;do C.y>B!=C.next.y>B&&C.next.y!==C.y&&P<(C.next.x-C.x)*(B-C.y)/(C.next.y-C.y)+C.x&&(M=!M),C=C.next;while(C!==f);return M}(g,u)&&(Zc(g.prev,g,u.prev)||Zc(g,u.prev,u))||xT(g,u)&&Zc(g.prev,g,g.next)>0&&Zc(u.prev,u,u.next)>0)}function Zc(g,u,f){return(u.y-g.y)*(f.x-u.x)-(u.x-g.x)*(f.y-u.y)}function xT(g,u){return g.x===u.x&&g.y===u.y}function tMe(g,u,f,_){const C=o7(Zc(g,u,f)),M=o7(Zc(g,u,_)),P=o7(Zc(f,_,g)),B=o7(Zc(f,_,u));return C!==M&&P!==B||!(C!==0||!i7(g,f,u))||!(M!==0||!i7(g,_,u))||!(P!==0||!i7(f,g,_))||!(B!==0||!i7(f,u,_))}function i7(g,u,f){return u.x<=Math.max(g.x,f.x)&&u.x>=Math.min(g.x,f.x)&&u.y<=Math.max(g.y,f.y)&&u.y>=Math.min(g.y,f.y)}function o7(g){return g>0?1:g<0?-1:0}function JP(g,u){return Zc(g.prev,g,g.next)<0?Zc(g,u,g.next)>=0&&Zc(g,g.prev,u)>=0:Zc(g,u,g.prev)<0||Zc(g,g.next,u)<0}function sMe(g,u){const f=Uge(g.i,g.x,g.y),_=Uge(u.i,u.x,u.y),C=g.next,M=u.prev;return g.next=u,u.prev=g,f.next=C,C.prev=f,_.next=f,f.prev=_,M.next=_,_.prev=M,_}function rMe(g,u,f,_){const C=Uge(g,u,f);return _?(C.next=_.next,C.prev=_,_.next.prev=C,_.next=C):(C.prev=C,C.next=C),C}function e6(g){g.next.prev=g.prev,g.prev.next=g.next,g.prevZ&&(g.prevZ.nextZ=g.nextZ),g.nextZ&&(g.nextZ.prevZ=g.prevZ)}function Uge(g,u,f){return{i:g,x:u,y:f,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function t6(g,u){const f=g.length;if(f<=1)return[g];const _=[];let C,M;for(let P=0;P1)for(let P=0;P<_.length;P++)_[P].length<=u||(YB(_[P],u,1,_[P].length-1,Wyt),_[P]=_[P].slice(0,u));return _}function Wyt(g,u){return u.area-g.area}function nMe(g,u,f=1){if(!g)return null;const _=typeof g=="string"?Lh.from(g).getPrimary():g.getPrimary(),C=typeof g=="string"?null:g.getSecondary();for(const M of[_,C]){if(!M)continue;const P=M.id.toString();u.has(P)||u.set(P,[]),M.scaleSelf(f),u.get(P).push(M)}return{primary:_.toString(),secondary:C?C.toString():null}}function qge(g,u,f,_){const C=_.patternDependencies;let M=!1;for(const P of u){const B=P.paint.get(`${g}-pattern`);B.isConstant()||(M=!0),nMe(B.constantOr(null),C,f)&&(M=!0)}return M}function Vge(g,u,f,_,C,M){const P=M.patternDependencies;for(const B of u){const U=B.paint.get(`${g}-pattern`).value;if(U.kind!=="constant"){const W=nMe(U.evaluate({zoom:_},f,{},void 0,M.availableImages),P,C);if(!W)continue;const{primary:ee,secondary:se}=W;ee&&(f.patterns[B.id]=[ee,se].filter(Boolean))}}return f}class b1{constructor(){this.portals=[]}static isOnBorder(u,f){return u<=0&&f<=0||u>=fr&&f>=fr}static evaluate(u){if(u.length===0)return new b1;let f=[];for(const U of u)f.push(...U.portals);if(f.length===0)return new b1;for(const U of f){const W=U.va,ee=U.vb;(b1.isOnBorder(W.x,ee.x)||b1.isOnBorder(W.y,ee.y))&&(U.type="border")}const _=f.filter(U=>U.type!=="unevaluated"),C=f.filter(U=>U.type==="unevaluated");if(C.length===0)return new b1;C.sort((U,W)=>U.hash===W.hash?U.isTunnel===W.isTunnel?0:U.isTunnel?-1:1:U.hashU.hashM!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Me(f,{zoom:_,lut:C},M=>M!=="fill-bridge-guard-rail-color")}addVertices(u,f){const _=this.unevalVertices.length;for(let C=0;C=M.min.x&&se.x<=M.max.x&&se.y>=M.min.y&&se.y<=M.max.y||ae.x>=M.min.x&&ae.x<=M.max.x&&ae.y>=M.min.y&&ae.y<=M.max.y||l0(se,ae,B))||this.isOnBorder(se.x,ae.x)||this.isOnBorder(se.y,ae.y))continue;const me=qm.computeEdgeHash(this.unevalVertices[W],this.unevalVertices[ee]);let ge,we=this.vertexHashLookup.get(qm.computePosHash(se));we!=null?ge=we.next:(we=this.vertexHashLookup.get(qm.computePosHash(ae)),ge=we!=null?we.prev:me),this.unevalEdges.push({polygonIdx:u,a:W,b:ee,hash:me,portalHash:ge,isTunnel:C,type:"unevaluated",featureInfo:P})}}addPortalCandidates(u,f,_,C,M){if(f.length!==0){this.vertexHashLookup.clear();for(const P of f){if(P.length===0)continue;const B=P[0];let U=qm.computeEdgeHash(B[B.length-2],B[B.length-1]);for(let W=0;W({vertexOffset:0,primitiveOffset:this.indexArray.length}),_=ae=>{ae.primitiveLength=this.indexArray.length-ae.primitiveOffset},C=new Kyt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(u.portals,this.unevalEdges);const M=f(),P=f(),B=f(),U=(ae,me)=>{ae.sort((we,Ee)=>we.type===me&&Ee.type!==me?-1:we.type!==me&&Ee.type===me?1:0);const ge=ae.findIndex(we=>we.type!==me);return ge>=0?ge:ae.length};let W=0;this.unevalEdges.length>0&&(W=U(this.unevalEdges,"none"),this.constructBridgeStructures(C,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:W},this.tileToMeters)),_(B);const ee=f(),se=f();if(this.unevalEdges.length>0){const ae=this.unevalEdges.splice(W),me=U(ae,"tunnel")+W;this.unevalEdges.push(...ae),this.constructTunnelStructures(C,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:W},{min:W,max:me})}_(ee),C.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),_(se),C.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),_(P),C.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),_(M),this.maskSegments=Bi.simpleSegment(0,se.primitiveOffset,0,se.primitiveLength),this.depthSegments=Bi.simpleSegment(0,P.primitiveOffset,0,P.primitiveLength),this.renderableBridgeSegments=Bi.simpleSegment(0,B.primitiveOffset,0,B.primitiveLength),this.renderableTunnelSegments=Bi.simpleSegment(0,ee.primitiveOffset,0,ee.primitiveLength),this.shadowCasterSegments=Bi.simpleSegment(0,M.primitiveOffset,0,M.primitiveLength)}update(u,f,_,C,M,P,B,U){this.bridgeProgramConfigurations.updatePaintArrays(u,f,M,_,C,P,B,U),this.tunnelProgramConfigurations.updatePaintArrays(u,f,M,_,C,P,B,U)}upload(u){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=u.createVertexBuffer(this.vertexPositions,Ryt.members),this.vertexBufferNormal=u.createVertexBuffer(this.vertexNormals,Oyt.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(u),this.tunnelProgramConfigurations.upload(u))}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(u,f,_,C,M){const P=(B,U)=>{for(let W=0;Woe(Rs,f[Es].x,f[Es].y,_[Es]*U),se=X(),ae=X(),me=X(),ge=X(),we=X(),Ee=(Rs,Es)=>{const Ws=B.get(qm.computePosHash(f[Es])),ls=Ws.from,Ps=Ws.to;if(!ls||!Ps)return;ee(se,ls),ee(ae,Es),ee(me,Ps),Oe(ge),Ye(se,ae)||(We(we,ae,se),Le(ge,we)),Ye(me,ae)||(We(we,me,ae),ne(ge,ge,Le(we,we)));const zs=Re(ge);return zs>0?be(Rs,ge,1/zs):void 0};let Fe=Number.POSITIVE_INFINITY;this.sortSubarray(C,M.min,M.max,(Rs,Es)=>Rs.featureInfo.featureIndex-Es.featureInfo.featureIndex);const Qe=X(),Ve=X(),at=X(),ut=X(),ft=X(),Bt=X(),Et=X(),Ot=X(),Lt=X(),Pt=[X(),X(),X(),X()],hs=[X(),X(),X(),X()],bs=[{coord:new ss(0,0),height:0},{coord:new ss(0,0),height:0}],Ts=(Rs,Es)=>Rs>Es;for(let Rs=M.min;RsFe.featureInfo.featureIndex-Qe.featureInfo.featureIndex;this.sortSubarray(C,M.min,M.max,U),this.sortSubarray(C,P.min,P.max,U);const W=Fe=>Le(Fe,Fe),ee=[{coord:new ss(0,0),height:0},{coord:new ss(0,0),height:0}],se=(Fe,Qe)=>FeB.hash===U.hash?U.polygonIdx-B.polygonIdx:U.hash>B.hash?1:-1);let _=0,C=0,M=0,P=f[_].polygonIdx;do C++,(C===f.length||f[_].hash!==f[C].hash)&&((C-_===1||f[C-1].polygonIdx!==P)&&(M<_&&(f[M]=f[_],f[_]=null),f[M].type="none",M++),_=C,_!==f.length&&(P=f[_].polygonIdx));while(_!==f.length);if(f.splice(M),f.length!==0&&u.length!==0){f.sort((W,ee)=>W.portalHashee.hash?B++:ee.hash>W.portalHash?U++:(W.type=ee.type,B++)}}}isOnBorder(u,f){return u<=0&&f<=0||u>=fr&&f>=fr}addFeatureSection(u,f,_,C){return u!==f&&(f=u,_.push({featureIndex:u,vertexStart:C.getVertexCount()}),C.clearVertexLookup()),f}sortSubarray(u,f,_,C){const M=u.slice(f,_);M.sort(C),u.splice(f,M.length,...M)}static computeEdgeHash(u,f){return(u.y===f.y&&u.x>f.x||u.y>f.y)&&([u,f]=[f,u]),BigInt(qm.computePosHash(u))<<32n|BigInt(qm.computePosHash(f))}static computePosHash(u){return((65535&u.x)<<16|65535&u.y)>>>0}}function Yyt(g,u){return g>u?1:g0))return f;f=f.left}}return null}contains(u){for(var f=this._root,_=this._compare;f;){var C=_(u,f.key);if(C===0)return!0;f=C<0?f.left:f.right}return!1}remove(u){var f=this.find(u);if(!f)return!1;if(this.splay(f),f.left)if(f.right){var _=this.minNode(f.right);_.parent!==f&&(this.replace(_,_.right),_.right=f.right,_.right.parent=_),this.replace(f,_),_.left=f.left,_.left.parent=_}else this.replace(f,f.left);else this.replace(f,f.right);return this._size--,!0}removeNode(u){if(!u)return!1;if(this.splay(u),u.left)if(u.right){var f=this.minNode(u.right);f.parent!==u&&(this.replace(f,f.right),f.right=u.right,f.right.parent=f),this.replace(u,f),f.left=u.left,f.left.parent=f}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}erase(u){var f=this.find(u);if(f){this.splay(f);var _=f.left,C=f.right,M=null;_&&(_.parent=null,M=this.maxNode(_),this.splay(M),this._root=M),C&&(_?M.right=C:this._root=C,C.parent=M),this._size--}}pop(){var u=this._root,f=null;if(u){for(;u.left;)u=u.left;f={key:u.key,data:u.data},this.remove(u.key)}return f}next(u){var f=u;if(f)if(f.right)for(f=f.right;f&&f.left;)f=f.left;else for(f=u.parent;f&&f.right===u;)u=f,f=f.parent;return f}prev(u){var f=u;if(f)if(f.left)for(f=f.left;f&&f.right;)f=f.right;else for(f=u.parent;f&&f.left===u;)u=f,f=f.parent;return f}forEach(u){for(var f=this._root,_=[],C=!1,M=0;!C;)f?(_.push(f),f=f.left):_.length>0?(u(f=_.pop(),M++),f=f.right):C=!0;return this}range(u,f,_,C){const M=[],P=this._compare;let B,U=this._root;for(;M.length!==0||U;)if(U)M.push(U),U=U.left;else{if(U=M.pop(),B=P(U.key,f),B>0)break;if(P(U.key,u)>=0&&_.call(C,U))return this;U=U.right}return this}keys(){for(var u=this._root,f=[],_=[],C=!1;!C;)u?(f.push(u),u=u.left):f.length>0?(u=f.pop(),_.push(u.key),u=u.right):C=!0;return _}values(){for(var u=this._root,f=[],_=[],C=!1;!C;)u?(f.push(u),u=u.left):f.length>0?(u=f.pop(),_.push(u.data),u=u.right):C=!0;return _}at(u){for(var f=this._root,_=[],C=!1,M=0;!C;)if(f)_.push(f),f=f.left;else if(_.length>0){if(f=_.pop(),M===u)return f;M++,f=f.right}else C=!0;return null}load(u=[],f=[],_=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const C=u.length;return _&&Wge(u,f,0,C-1,this._compare),this._root=Gge(null,u,f,0,C),this._size=C,this}min(){var u=this.minNode(this._root);return u?u.key:null}max(){var u=this.maxNode(this._root);return u?u.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(u,f,_,C,M){return new Hge(_,M).load(u,f,C)}}function Gge(g,u,f,_,C){const M=C-_;if(M>0){const P=_+Math.floor(M/2),B={key:u[P],data:f[P],parent:g};return B.left=Gge(B,u,f,_,P),B.right=Gge(B,u,f,P+1,C),B}return null}function Wge(g,u,f,_,C){if(f>=_)return;const M=g[f+_>>1];let P=f-1,B=_+1;for(;;){do P++;while(C(g[P],M)<0);do B--;while(C(g[B],M)>0);if(P>=B)break;let U=g[P];g[P]=g[B],g[B]=U,U=u[P],u[P]=u[B],u[B]=U}Wge(g,u,f,B,C),Wge(g,u,B+1,_,C)}const aMe=11102230246251565e-32,dm=134217729,Zyt=(3+8*aMe)*aMe;function Kge(g,u,f,_,C){let M,P,B,U,W=u[0],ee=_[0],se=0,ae=0;ee>W==ee>-W?(M=W,W=u[++se]):(M=ee,ee=_[++ae]);let me=0;if(seW==ee>-W?(P=W+M,B=M-(P-W),W=u[++se]):(P=ee+M,B=M-(P-ee),ee=_[++ae]),M=P,B!==0&&(C[me++]=B);seW==ee>-W?(P=M+W,U=P-M,B=M-(P-U)+(W-U),W=u[++se]):(P=M+ee,U=P-M,B=M-(P-U)+(ee-U),ee=_[++ae]),M=P,B!==0&&(C[me++]=B);for(;se0:(_[0]-u[0])*(f[1]-u[1])-(f[0]-u[0])*(_[1]-u[1])>0}isAbove(u){return!this.isBelow(u)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const u=new yT(this.point,this.left,this.otherEvent,this.isSubject,this.type);return u.contourId=this.contourId,u.resultTransition=this.resultTransition,u.prevInResult=this.prevInResult,u.isExteriorRing=this.isExteriorRing,u.inOut=this.inOut,u.otherInOut=this.otherInOut,u}}function u0(g,u){return g[0]===u[0]&&g[1]===u[1]}function Yge(g,u,f){const _=function(C,M,P,B,U,W){const ee=(M-W)*(P-U),se=(C-U)*(B-W),ae=ee-se;if(ee===0||se===0||ee>0!=se>0)return ae;const me=Math.abs(ee+se);return Math.abs(ae)>=33306690738754716e-32*me?ae:-function(ge,we,Ee,Fe,Qe,Ve,at){let ut,ft,Bt,Et,Ot,Lt,Pt,hs,bs,Ts,Rs,Es,Ws,ls,Ps,zs,Ks,tr;const Ar=ge-Qe,ur=Ee-Qe,dr=we-Ve,sr=Fe-Ve;ls=Ar*sr,Lt=dm*Ar,Pt=Lt-(Lt-Ar),hs=Ar-Pt,Lt=dm*sr,bs=Lt-(Lt-sr),Ts=sr-bs,Ps=hs*Ts-(ls-Pt*bs-hs*bs-Pt*Ts),zs=dr*ur,Lt=dm*dr,Pt=Lt-(Lt-dr),hs=dr-Pt,Lt=dm*ur,bs=Lt-(Lt-ur),Ts=ur-bs,Ks=hs*Ts-(zs-Pt*bs-hs*bs-Pt*Ts),Rs=Ps-Ks,Ot=Ps-Rs,gT[0]=Ps-(Rs+Ot)+(Ot-Ks),Es=ls+Rs,Ot=Es-ls,Ws=ls-(Es-Ot)+(Rs-Ot),Rs=Ws-zs,Ot=Ws-Rs,gT[1]=Ws-(Rs+Ot)+(Ot-zs),tr=Es+Rs,Ot=tr-Es,gT[2]=Es-(tr-Ot)+(Rs-Ot),gT[3]=tr;let Tr=function($a,Hn){let Va=Hn[0];for(let ca=1;ca<4;ca++)Va+=Hn[ca];return Va}(0,gT),zr=22204460492503146e-32*at;if(Tr>=zr||-Tr>=zr||(Ot=ge-Ar,ut=ge-(Ar+Ot)+(Ot-Qe),Ot=Ee-ur,Bt=Ee-(ur+Ot)+(Ot-Qe),Ot=we-dr,ft=we-(dr+Ot)+(Ot-Ve),Ot=Fe-sr,Et=Fe-(sr+Ot)+(Ot-Ve),ut===0&&ft===0&&Bt===0&&Et===0)||(zr=11093356479670487e-47*at+Zyt*Math.abs(Tr),Tr+=Ar*Et+sr*ut-(dr*Bt+ur*ft),Tr>=zr||-Tr>=zr))return Tr;ls=ut*sr,Lt=dm*ut,Pt=Lt-(Lt-ut),hs=ut-Pt,Lt=dm*sr,bs=Lt-(Lt-sr),Ts=sr-bs,Ps=hs*Ts-(ls-Pt*bs-hs*bs-Pt*Ts),zs=ft*ur,Lt=dm*ft,Pt=Lt-(Lt-ft),hs=ft-Pt,Lt=dm*ur,bs=Lt-(Lt-ur),Ts=ur-bs,Ks=hs*Ts-(zs-Pt*bs-hs*bs-Pt*Ts),Rs=Ps-Ks,Ot=Ps-Rs,Vm[0]=Ps-(Rs+Ot)+(Ot-Ks),Es=ls+Rs,Ot=Es-ls,Ws=ls-(Es-Ot)+(Rs-Ot),Rs=Ws-zs,Ot=Ws-Rs,Vm[1]=Ws-(Rs+Ot)+(Ot-zs),tr=Es+Rs,Ot=tr-Es,Vm[2]=Es-(tr-Ot)+(Rs-Ot),Vm[3]=tr;const mn=Kge(4,gT,4,Vm,iMe);ls=Ar*Et,Lt=dm*Ar,Pt=Lt-(Lt-Ar),hs=Ar-Pt,Lt=dm*Et,bs=Lt-(Lt-Et),Ts=Et-bs,Ps=hs*Ts-(ls-Pt*bs-hs*bs-Pt*Ts),zs=dr*Bt,Lt=dm*dr,Pt=Lt-(Lt-dr),hs=dr-Pt,Lt=dm*Bt,bs=Lt-(Lt-Bt),Ts=Bt-bs,Ks=hs*Ts-(zs-Pt*bs-hs*bs-Pt*Ts),Rs=Ps-Ks,Ot=Ps-Rs,Vm[0]=Ps-(Rs+Ot)+(Ot-Ks),Es=ls+Rs,Ot=Es-ls,Ws=ls-(Es-Ot)+(Rs-Ot),Rs=Ws-zs,Ot=Ws-Rs,Vm[1]=Ws-(Rs+Ot)+(Ot-zs),tr=Es+Rs,Ot=tr-Es,Vm[2]=Es-(tr-Ot)+(Rs-Ot),Vm[3]=tr;const Gr=Kge(mn,iMe,4,Vm,oMe);ls=ut*Et,Lt=dm*ut,Pt=Lt-(Lt-ut),hs=ut-Pt,Lt=dm*Et,bs=Lt-(Lt-Et),Ts=Et-bs,Ps=hs*Ts-(ls-Pt*bs-hs*bs-Pt*Ts),zs=ft*Bt,Lt=dm*ft,Pt=Lt-(Lt-ft),hs=ft-Pt,Lt=dm*Bt,bs=Lt-(Lt-Bt),Ts=Bt-bs,Ks=hs*Ts-(zs-Pt*bs-hs*bs-Pt*Ts),Rs=Ps-Ks,Ot=Ps-Rs,Vm[0]=Ps-(Rs+Ot)+(Ot-Ks),Es=ls+Rs,Ot=Es-ls,Ws=ls-(Es-Ot)+(Rs-Ot),Rs=Ws-zs,Ot=Ws-Rs,Vm[1]=Ws-(Rs+Ot)+(Ot-zs),tr=Es+Rs,Ot=tr-Es,Vm[2]=Es-(tr-Ot)+(Rs-Ot),Vm[3]=tr;const Vn=Kge(Gr,oMe,4,Vm,lMe);return lMe[Vn-1]}(C,M,P,B,U,W,me)}(g[0],g[1],u[0],u[1],f[0],f[1]);return _>0?-1:_<0?1:0}function N_(g,u){const f=g.point,_=u.point;return f[0]>_[0]?1:f[0]<_[0]?-1:f[1]!==_[1]?f[1]>_[1]?1:-1:function(C,M,P){return C.left!==M.left?C.left?1:-1:Yge(P,C.otherEvent.point,M.otherEvent.point)!==0?C.isBelow(M.otherEvent.point)?-1:1:!C.isSubject&&M.isSubject?1:-1}(g,u,f)}function k_(g,u,f){const _=new yT(u,!1,g,g.isSubject),C=new yT(u,!0,g.otherEvent,g.isSubject);return u0(g.point,g.otherEvent.point)&&console.warn("what is that, a collapsed segment?",g),_.contourId=C.contourId=g.contourId,N_(C,g.otherEvent)>0&&(g.otherEvent.left=!0,C.left=!1),g.otherEvent.otherEvent=C,g.otherEvent=_,f.push(C),f.push(_),f}function l7(g,u){return g[0]*u[1]-g[1]*u[0]}function Zge(g,u){return g[0]*u[0]+g[1]*u[1]}function Xge(g,u,f){const _=function(U,W,ee,se){const ae=[W[0]-U[0],W[1]-U[1]],me=[se[0]-ee[0],se[1]-ee[1]];function ge(Bt,Et,Ot){return[Bt[0]+Et*Ot[0],Bt[1]+Et*Ot[1]]}const we=[ee[0]-U[0],ee[1]-U[1]];let Ee=l7(ae,me),Fe=Ee*Ee;const Qe=Zge(ae,ae);if(Fe>0){const Bt=l7(we,me)/Ee;if(Bt<0||Bt>1)return null;const Et=l7(we,ae)/Ee;return Et<0||Et>1?null:Bt===0||Bt===1?[ge(U,Bt,ae)]:Et===0||Et===1?[ge(ee,Et,me)]:[ge(U,Bt,ae)]}if(Ee=l7(we,ae),Fe=Ee*Ee,Fe>0)return null;const Ve=Zge(ae,we)/Qe,at=Ve+Zge(ae,me)/Qe,ut=Math.min(Ve,at),ft=Math.max(Ve,at);return ut<=1&&ft>=0?ut===1?[ge(U,ut>0?ut:0,ae)]:ft===0?[ge(U,ft<1?ft:1,ae)]:[ge(U,ut>0?ut:0,ae),ge(U,ft<1?ft:1,ae)]:null}(g.point,g.otherEvent.point,u.point,u.otherEvent.point),C=_?_.length:0;if(C===0||C===1&&(u0(g.point,u.point)||u0(g.otherEvent.point,u.otherEvent.point))||C===2&&g.isSubject===u.isSubject)return 0;if(C===1)return!u0(g.point,_[0])&&!u0(g.otherEvent.point,_[0])&&k_(g,_[0],f),!u0(u.point,_[0])&&!u0(u.otherEvent.point,_[0])&&k_(u,_[0],f),1;const M=[];let P=!1,B=!1;return u0(g.point,u.point)?P=!0:N_(g,u)===1?M.push(u,g):M.push(g,u),u0(g.otherEvent.point,u.otherEvent.point)?B=!0:N_(g.otherEvent,u.otherEvent)===1?M.push(u.otherEvent,g.otherEvent):M.push(g.otherEvent,u.otherEvent),P&&B||P?(u.type=1,g.type=u.inOut===g.inOut?2:3,P&&!B&&k_(M[1].otherEvent,M[0].point,f),2):B?(k_(M[0],M[1].point,f),3):M[0]!==M[3].otherEvent?(k_(M[0],M[1].point,f),k_(M[1],M[2].point,f),3):(k_(M[0],M[1].point,f),k_(M[3].otherEvent,M[2].point,f),3)}function Xyt(g,u){if(g===u)return 0;if(Yge(g.point,g.otherEvent.point,u.point)!==0||Yge(g.point,g.otherEvent.point,u.otherEvent.point)!==0)return u0(g.point,u.point)?g.isBelow(u.otherEvent.point)?-1:1:g.point[0]===u.point[0]?g.point[1](u.contourId??0)?1:-1}return N_(g,u)===1?1:-1}class Qyt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Jyt(g,u,f,_){let C,M=g+1,P=u[g].point;const B=u.length;for(M_;)M--;return M}function e0t(g,u,f){const _=new Qyt;if(g.prevInResult!=null){const C=g.prevInResult,M=C.outputContourId;if(C.resultTransition>0){const P=u[M];if(P.holeOf!=null){const B=P.holeOf;u[B].holeIds.push(f),_.holeOf=B,_.depth=u[M].depth}else u[M].holeIds.push(f),_.holeOf=M,_.depth=u[M].depth+1}else _.holeOf=null,_.depth=u[M].depth}else _.holeOf=null,_.depth=0;return _}const dMe=Math.max,uMe=Math.min;let c7=0;function hMe(g,u,f,_,C,M){let P,B,U,W,ee,se;for(P=0,B=g.length-1;P0?se.left=!0:ee.left=!0;const ae=U[0],me=U[1];C[0]=uMe(C[0],ae),C[1]=uMe(C[1],me),C[2]=dMe(C[2],ae),C[3]=dMe(C[3],me),_.push(ee),_.push(se)}}const d7=[];function mMe(g,u,f){let _=g,C=u;typeof g[0][0][0]=="number"&&(_=[g]),typeof u[0][0][0]=="number"&&(C=[u]);let M=function(ae,me,ge){let we=null;return ae.length*me.length===0&&(ge===0?we=d7:ge===2?we=ae:(ge===1||ge===3)&&(we=ae.length===0?me:ae)),we}(_,C,f);if(M)return M===d7?null:M;const P=[1/0,1/0,-1/0,-1/0],B=[1/0,1/0,-1/0,-1/0],U=function(ae,me,ge,we,Ee){const Fe=new E2(void 0,N_);let Qe,Ve,at,ut,ft,Bt;for(at=0,ut=ae.length;atwe[2]||we[0]>ge[2]||ge[1]>we[3]||we[1]>ge[3])&&(Ee===0?Fe=d7:Ee===2?Fe=ae:(Ee===1||Ee===3)&&(Fe=ae.concat(me))),Fe}(_,C,P,B,f),M)return M===d7?null:M;const W=function(ae,me,ge,we,Ee,Fe){const Qe=new Hge(Xyt),Ve=[],at=Math.min(we[2],Ee[2]);let ut,ft,Bt;for(;ae.length!==0;){let Et=ae.pop();if(Ve.push(Et),Fe===0&&Et.point[0]>at||Fe===2&&Et.point[0]>we[2])break;if(Et.left){ft=ut=Qe.insert(Et),Bt=Qe.minNode(),ut=ut!==Bt?Qe.prev(ut):null,ft=Qe.next(ft);const Ot=ut?ut.key:null;let Lt;if(r6(Et,Ot,Fe),ft&&Xge(Et,ft.key,ae)===2&&(r6(Et,Ot,Fe),r6(ft.key,Et,Fe)),ut&&Xge(ut.key,Et,ae)===2){let Pt=ut;Pt=Pt!==Bt?Qe.prev(Pt):null,Lt=Pt?Pt.key:null,r6(Ot,Lt,Fe),r6(Et,Ot,Fe)}}else Et=Et.otherEvent,ft=ut=Qe.find(Et),ut&&ft&&(ut=ut!==Bt?Qe.prev(ut):null,ft=Qe.next(ft),Qe.remove(Et),ft&&ut&&Xge(ut.key,ft.key,ae))}return Ve}(U,0,0,P,B,f),ee=function(ae){let me,ge;const we=function(Qe){let Ve,at,ut,ft,Bt;const Et=[];for(at=0,ut=Qe.length;at{Ee[Bt]=!0,Bt=we.length)&&we[ut];);Fe.push(Ve)}return Fe}(W),se=[];for(let ae=0;ae{P.push(new ss(se,U+(se-B)/(W-B)*(ee-U)))}:(P,B,U,W,ee,se)=>{P.push(new ss(B+(se-U)/(ee-U)*(W-B),se))};for(const P of g){const B=[];for(const U of P){if(U.length<=2)continue;const W=[];for(let ae=0;aeu&&M(W,me,ge,we,Ee,u):Fe>f?Qe=u&&M(W,me,ge,we,Ee,u),Qe>f&&Fe<=f&&M(W,me,ge,we,Ee,f)}let ee=U[U.length-1];const se=_===0?ee.x:ee.y;se>=u&&se<=f&&W.push(ee),W.length&&(ee=W[W.length-1],W[0].x===ee.x&&W[0].y===ee.y||W.push(W[0]),B.push(W))}B.length&&C.push(B)}return C}function t0t(g,u){const f=mMe(Qge(g),Qge([u]),0);return f==null?[]:fMe(f)}function s0t(g,u,f=0){let C=Qge(g,65536);const M=[];for(;u.valid();u.next()){const[P,B]=u.get();let U=P.x*65536,W=P.y*65536,ee=B.x*65536,se=B.y*65536;const ae=ee-U,me=se-W,ge=Math.hypot(ae,me);if(ge===0)continue;U-=ae*f,W-=me*f,ee+=ae*f,se+=me*f;const we=Math.trunc(me/ge*3),Ee=-Math.trunc(ae/ge*3);M.push([[[U,W],[ee,se],[ee+we,se+Ee],[U+we,W+Ee],[U,W]]])}return M.length>0&&(C=mMe(C,M,2)),fMe(C,1/65536,128)}function Qge(g,u=1){return[g.map(f=>f.map(_=>[_.x*u,_.y*u]))]}function fMe(g,u=1,f){return g.map(_=>_.map((C,M)=>{const P=C.map(B=>{let U=B[0],W=B[1];return f&&(U=Math.round(U/f)*f,W=Math.round(W/f)*f),new ss(U*u,W*u)._round()});return M>0&&P.reverse(),P}))}class Jge{constructor(u,f){this.layoutVertexArray=new om,this.indexArray=new ll,this.lineIndexArray=new Ef,this.triangleSegments=new Bi,this.lineSegments=new Bi,this.programConfigurations=new Me(u.layers,{zoom:u.zoom,lut:u.lut}),this.uploaded=!1,f&&(this.elevatedLayoutVertexArray=new Bm)}update(u,f,_,C,M,P,B,U){this.programConfigurations.updatePaintArrays(u,f,M,_,C,P,B,U)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,Pyt.members),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.lineIndexBuffer=u.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=u.createVertexBuffer(this.elevatedLayoutVertexArray,Dyt.members))),this.programConfigurations.upload(u),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(u,f,_,C,M,P,B){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,f,_,C,M,P,void 0,B)}}class h7{constructor(u){this.zoom=u.zoom,this.pixelRatio=u.pixelRatio,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=u.lut,this.bufferData=new Jge(u,!1),this.elevationBufferData=new Jge(u,!0),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.projection=u.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=u.sourceLayerIndex,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,_,C){this.hasPattern=qge("fill",this.layers,this.pixelRatio,f);const M=this.layers[0].layout.get("fill-sort-key"),P=[];for(const{feature:B,id:U,index:W,sourceLayerIndex:ee}of u){const se=this.layers[0]._featureFilter.needGeometry,ae=la(B,se);if(!this.layers[0]._featureFilter.filter(new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),ae,_))continue;const me=M?M.evaluate(ae,{},_,f.availableImages):void 0,ge={id:U,properties:B.properties,type:B.type,sourceLayerIndex:ee,index:W,geometry:se?ae.geometry:pn(B,_,C),patterns:{},sortKey:me};P.push(ge)}M&&P.sort((B,U)=>B.sortKey-U.sortKey);for(const B of P){const{geometry:U,index:W,sourceLayerIndex:ee}=B;if(this.hasPattern){const se=Vge("fill",this.layers,B,this.zoom,this.pixelRatio,f);this.patternFeatures.push(se)}else this.addFeature(B,U,W,_,{},f.availableImages,f.brightness,f.elevationFeatures);f.featureIndex.insert(u[W].feature,U,W,ee,this.index)}}update(u,f,_,C,M,P,B){this.bufferData.update(u,f,_,C,M,P,B,this.worldview),this.elevationBufferData.update(u,f,_,C,M,P,B,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(u,f,_,C,M,P,B,this.worldview)}addFeatures(u,f,_,C,M,P){for(const B of this.patternFeatures)this.addFeature(B,B.geometry,B.index,f,_,C,P,u.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(u){this.bufferData.upload(u),this.elevationBufferData.upload(u),this.elevatedStructures&&this.elevatedStructures.upload(u)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(u,f,_,C,M,P=[],B,U){const W=t6(f,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(u,W,C,_,U):this.addGeometry(W,this.bufferData),this.bufferData.populatePaintArrays(u,_,M,P,C,B,this.worldview),this.elevationBufferData.populatePaintArrays(u,_,M,P,C,B,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(u,f,_,C,M){this.elevatedStructures&&(this.elevatedStructures.construct(u),this.elevatedStructures.populatePaintArrays(f,_,C,M,this.worldview))}addElevatedRoadFeature(u,f,_,C,M){const P=new Array,B=qi.getElevationFeature(u,M);if(!B)return void this.addGeometry(f,this.bufferData);{const W=this.clipPolygonsToTile(f,1);W.length>0&&P.push({polygons:W,elevationFeature:B,elevationTileID:_})}const U={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(u,{},_),featureIndex:C};for(const W of P)if(W.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new qm(W.elevationTileID,this.layers,this.zoom,this.lut));const se=W.elevationFeature.isTunnel();let ae=0;u.properties.hasOwnProperty($i)&&(ae=+u.properties[$i]),this.elevatedStructures.addPortalCandidates(W.elevationFeature.id,W.polygons,se,W.elevationFeature,ae)}W.elevationFeature.constantHeight==null&&(W.polygons=this.prepareElevatedPolygons(W.polygons,W.elevationFeature,W.elevationTileID));const ee=new Yi(_,W.elevationTileID);this.addElevatedGeometry(W.polygons,ee,W.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,C,U)}}addElevatedGeometry(u,f,_,C,M,P){const B={elevation:_,elevationSampler:f,bias:C,index:M,featureInfo:P},[U,W]=this.addGeometry(u,this.elevationBufferData,B);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:U,max:W}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,U),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,W))}addGeometry(u,f,_){let C=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,P=null;_&&(P=_.elevationSampler.constantElevation(_.elevation,_.bias),P!=null&&(C=P,M=P));const B=(U,W,ee)=>{if(_!=null)if(W.push(U),P!=null)f.elevatedLayoutVertexArray.emplaceBack(P),ee.push(P);else{const se=_.elevationSampler.pointElevation(U,_.elevation,_.bias);f.elevatedLayoutVertexArray.emplaceBack(se),ee.push(se),C=Math.min(C,se),M=Math.max(M,se)}};for(const U of u){let W=0;for(const Ve of U)W+=Ve.length;const ee=f.triangleSegments.prepareSegment(W,f.layoutVertexArray,f.indexArray),se=ee.vertexLength,ae=[],me=[],ge=[],we=[],Ee=[],Fe=f.layoutVertexArray.length;for(const Ve of U){if(Ve.length===0)continue;Ve!==U[0]&&me.push(ae.length/2);const at=f.lineSegments.prepareSegment(Ve.length,f.layoutVertexArray,f.lineIndexArray),ut=at.vertexLength;_&&Ee.push(f.layoutVertexArray.length-Fe),B(Ve[0],ge,we),f.layoutVertexArray.emplaceBack(Ve[0].x,Ve[0].y),f.lineIndexArray.emplaceBack(ut+Ve.length-1,ut),ae.push(Ve[0].x),ae.push(Ve[0].y);for(let ft=1;ft0&&_&&this.elevationMode==="hd-road-base"){const Ve=_.elevation.isTunnel(),at=_.elevation.safeArea,ut=this.elevatedStructures.addVertices(ge,we);this.elevatedStructures.addTriangles(Qe,ut,Ve);const ft=Ee.length;if(ft>0){for(let Bt=0;Bt=_&&me.max.x<=M&&me.min.y>=C&&me.max.y<=P?U:W).push(ae)}if(U.length===u.length)return u;const ee=[new ss(_,C),new ss(M,C),new ss(M,P),new ss(_,P),new ss(_,C)],se=U;for(const ae of W)se.push(...t0t(ae,ee));return se}}let pMe,xMe,gMe,yMe;Dr(h7,"FillBucket",{omit:["layers","patternFeatures"]}),Dr(Jge,"FillBufferData"),Dr(qm,"ElevatedStructures");class m7{constructor(u,f,_,C){if(this.triangleCount=f.length/3,this.min=new ss(0,0),this.max=new ss(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||u.length===0)return;const[M,P]=[u[0].clone(),u[0].clone()];for(let se=1;sese.cellIdx-ae.cellIdx||se.triIdx-ae.triIdx);let ee=0;for(;eethis.max.x||this.min.x>u.x||u.y>this.max.y||this.min.y>u.y)return;const _=h0(u.x-this.min.x,this.xScale,this.cellsX),C=h0(u.y-this.min.y,this.yScale,this.cellsY),M=this.cells[C*this.cellsX+_];if(M){this._lazyInitLookup();for(let P=0;Pthis.max.x||this.min.x>f.x||u.y>this.max.y||this.min.y>f.y)return;this._lazyInitLookup();const C=h0(u.x-this.min.x,this.xScale,this.cellsX),M=h0(f.x-this.min.x,this.xScale,this.cellsX),P=h0(u.y-this.min.y,this.yScale,this.cellsY),B=h0(f.y-this.min.y,this.yScale,this.cellsY);for(let U=P;U<=B;U++)for(let W=C;W<=M;W++){const ee=this.cells[U*this.cellsX+W];if(ee)for(let se=0;sef.fqid),this.index=u.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.footprints=[],this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){for(const _ of this.footprints)f.push({footprint:_,id:u})}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,_,C){const M=[];for(const{feature:P,id:B,index:U,sourceLayerIndex:W}of u){const ee=this.layers[0]._featureFilter.needGeometry,se=la(P,ee);if(!this.layers[0]._featureFilter.filter(new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),se,_))continue;const ae={id:B,properties:P.properties,type:P.type,sourceLayerIndex:W,index:U,geometry:ee?se.geometry:pn(P,_,C),patterns:{}};M.push(ae)}for(const P of M){const{geometry:B,index:U,sourceLayerIndex:W}=P;this.addFeature(P,B,U,_,{},f.availableImages,f.brightness),f.featureIndex.insert(u[U].feature,B,U,W,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(u){}update(u,f,_,C,M,P,B){}destroy(){}addFeature(u,f,_,C,M,P=[],B){for(const U of t6(f,2)){const W=[],ee=[],se=[],ae=new ss(1/0,1/0),me=new ss(-1/0,-1/0);for(const Ee of U)if(Ee.length!==0){Ee!==U[0]&&se.push(ee.length/2);for(let Fe=0;Feu.max.x||g.max.xu.max.y||g.max.ynew ss((U.x+M.x*fr)*B-P.x*fr,(U.y+M.y*fr)*B-P.y*fr))}return tye(f,C,g.indices,0,g.indices.length,0,0)}function NMe(g,u,f,_){const C=Math.pow(2,_.z-f.z);return new ss((g+f.x*fr)*C-_.x*fr,(u+f.y*fr)*C-_.y*fr)}function kMe(g,u){const f=[];u.grid.queryPoint(g,f);const _=u.indices,C=u.vertices;for(let M=0;M0&&(_.length>1&&f.push(_),_=[])}return _.length>1&&f.push(_),f}const rye=Dn.types,m0t=["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"],f0t=["fill-extrusion-flood-light-ground-radius"],p0t=Math.pow(2,13),x0t=Math.pow(2,15)-1,g7=new ss(0,1),_1=2147483648,y7=1073741824;function a6(g,u,f,_,C,M,P,B){g.emplaceBack((u<<1)+P,(f<<1)+M,(Math.floor(_*p0t)<<1)+C,Math.round(B))}function i6(g,u,f){g.emplaceBack(u.x*fr,u.y*fr,f?1:0)}function v7(g,u,f,_,C,M){g.emplaceBack(u.x,u.y,(f.x<<1)+_,(f.y<<1)+C,M)}function o6(g,u,f){g.emplaceBack(u.x,u.y,u.z,f[0]*16384,f[1]*16384,f[2]*16384)}class CMe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class nye{constructor(){this.centroidXY=new ss(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 ss(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new ss(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new ss(0,0)}span(){return new ss(this.max.x-this.min.x,this.max.y-this.min.y)}}class aye{constructor(){this.acc=new ss(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(u,f){u.min.x===Number.MAX_VALUE&&(u.min.x=u.max.x=f.x,u.min.y=u.max.y=f.y)}appendEdge(u,f,_){this.accCount++,this.acc._add(f);let C=!!this.borders;f.xu.max.x&&(u.max.x=f.x,C=!0),f.yu.max.y&&(u.max.y=f.y,C=!0),((f.x===0||f.x===fr)&&f.x===_.x)!=((f.y===0||f.y===fr)&&f.y===_.y)&&this.processBorderOverlap(f,_),C&&this.checkBorderIntersection(f,_)}checkBorderIntersection(u,f){f.x<0!=u.x<0&&this.addBorderIntersection(0,hn(f.y,u.y,(0-f.x)/(u.x-f.x))),f.x>fr!=u.x>fr&&this.addBorderIntersection(1,hn(f.y,u.y,(fr-f.x)/(u.x-f.x))),f.y<0!=u.y<0&&this.addBorderIntersection(2,hn(f.x,u.x,(0-f.y)/(u.y-f.y))),f.y>fr!=u.y>fr&&this.addBorderIntersection(3,hn(f.x,u.x,(fr-f.y)/(u.y-f.y)))}addBorderIntersection(u,f){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const _=this.borders[u];f<_[0]&&(_[0]=f),f>_[1]&&(_[1]=f)}processBorderOverlap(u,f){if(u.x===f.x){if(u.y===f.y)return;const _=u.x===0?0:1;this.addBorderIntersection(_,f.y),this.addBorderIntersection(_,u.y)}else{const _=u.y===0?2:3;this.addBorderIntersection(_,f.x),this.addBorderIntersection(_,u.x)}}centroid(){return this.accCount===0?new ss(0,0):new ss(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((u,f)=>u+ +(f[0]!==Number.MAX_VALUE),0):0}}function TMe(g,u){const f=g.add(u)._unit(),_=ze(g.x*f.x+g.y*f.y,-1,1);var C,M,P;return P=Math.acos(_),Math.min(4,Math.max(-4,Math.tan(P)))/4*x0t*((C=g).x*(M=u).y-C.y*M.x<0?-1:1)}const g0t=[g=>g.x<0,g=>g.x>fr,g=>g.y<0,g=>g.y>fr];function y0t(g,u,f,_){const C=[4];if(_===0)return C;f._mult(_);const M=g.sub(f),P=u.sub(f),B=[g,u,M,P];for(let U=0;U<4;U++)for(const W of B)if(g0t[U](W)){C.push(U);break}return C}class iye{constructor(u){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new LP,this.indexArray=new ll,this.programConfigurations=new Me(u.layers,{zoom:u.zoom,lut:u.lut},f=>f0t.includes(f)),this._segments=new Bi,this.hiddenByLandmarkVertexArray=new dT,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Bi}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(u,f,_,C=!1){const M=u.length;if(M>2){let P=Math.max(0,this._segments.get().length-1);const B=this._segments._prepareSegment(4*M,this.vertexArray.length,2*this._segmentToGroundQuads[P].length);let U;P!==this._segments.get().length-1&&(P++,this._segmentToGroundQuads[P]=[],this._segmentToRegionTriCounts[P]=[0,0,0,0,0]);{const W=u[0],ee=u[1];U=TMe(W.sub(u[M-1])._perp()._unit(),ee.sub(W)._perp()._unit())}for(let W=0;WC.region-M.region);for(let _=0;_U+W,0);let B=0;for(let U=0;U<=4;U++){const W=P[U];if(W!==0){let ee=this.regionSegments[U];ee||(ee=this.regionSegments[U]=new Bi);const se={vertexOffset:M.vertexOffset,primitiveOffset:M.primitiveOffset+B,vertexLength:M.vertexLength,primitiveLength:W};ee.get().push(se)}B+=W}for(let U=0;U0?this.hiddenByLandmarkVertexBuffer=u.createVertexBuffer(this.hiddenByLandmarkVertexArray,l0t.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 u=0;u<=4;u++){const f=this.regionSegments[u];f&&f.destroy()}}}}class b7{constructor(u){this.zoom=u.zoom,this.canonical=u.canonical,this.overscaling=u.overscaling,this.layers=u.layers,this.pixelRatio=u.pixelRatio,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=u.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new ll,this.footprintVertices=new om,this.footprintSegments=[],this.layoutVertexArray=new IP,this.centroidVertexArray=new Jz,this.wallVertexArray=new HP,this.indexArray=new ll,this.programConfigurations=new Me(u.layers,{zoom:u.zoom,lut:u.lut},f=>m0t.includes(f)),this.segments=new Bi,this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.groundEffect=new iye(u),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,_,C){this.features=[],this.hasPattern=qge("fill-extrusion",this.layers,this.pixelRatio,f),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=Us(_),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:M,id:P,index:B,sourceLayerIndex:U}of u){const W=this.layers[0]._featureFilter.needGeometry,ee=la(M,W);if(!this.layers[0]._featureFilter.filter(new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),ee,_))continue;const se={id:P,sourceLayerIndex:U,index:B,geometry:W?ee.geometry:pn(M,_,C),properties:M.properties,type:M.type,patterns:{}},ae=this.layoutVertexArray.length,me=rye[se.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:M.id,feature:Vge("fill-extrusion",this.layers,se,this.zoom,this.pixelRatio,f)});else if(this.wallMode)for(const ge of se.geometry)for(const we of SMe(ge,me))this.addFeature(M.id,se,[we],B,_,{},f.availableImages,C,f.brightness);else this.addFeature(M.id,se,se.geometry,B,_,{},f.availableImages,C,f.brightness);f.featureIndex.insert(M,se.geometry,B,U,this.index,ae)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(u,f,_,C,M,P){for(const{featureId:B,feature:U}of this.features){const W=rye[U.type]==="Polygon",{geometry:ee}=U;if(this.wallMode)for(const se of ee)for(const ae of SMe(se,W))this.addFeature(B,U,[ae],U.index,f,_,C,M,P);else this.addFeature(B,U,ee,U.index,f,_,C,M,P)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(u,f,_,C,M,P,B){this.programConfigurations.updatePaintArrays(u,f,M,_,C,P,B,this.worldview),this.groundEffect.update(u,f,M,_,C,P,B,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,d0t),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.wallVertexBuffer=u.createVertexBuffer(this.wallVertexArray,o0t.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=u.createVertexBuffer(this.layoutVertexExtArray,c0t.members,!0)),this.groundEffect.upload(u)),this.groundEffect.uploadPaintProperties(u),this.programConfigurations.upload(u),this.uploaded=!0}uploadCentroid(u){this.groundEffect.uploadHiddenByLandmark(u),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=u.createVertexBuffer(this.centroidVertexArray,i0t.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(u,f,_,C,M,P,B,U,W){const ee=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(f,{})/this.tileToMeter,se=[new ss(0,0),new ss(fr,fr)],ae=U.projection,me=ae.name==="globe",ge=this.wallMode||rye[f.type]==="Polygon",we=new aye;we.centroidDataIndex=this.centroidData.length;const Ee=new nye;Ee.buildingId=u,f.properties&&f.properties.hasOwnProperty("building_id")&&(Ee.buildingId=Number(f.properties.building_id)),we.buildingId=Ee.buildingId;const Fe=this.layers[0].paint.get("fill-extrusion-base").evaluate(f,{},M)<=0,Qe=this.layers[0].paint.get("fill-extrusion-height").evaluate(f,{},M);let Ve;if(Ee.height=Qe,Ee.vertexArrayOffset=this.layoutVertexArray.length,Ee.groundVertexArrayOffset=this.groundEffect.vertexArray.length,me&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new nT),this.wallMode){if(me)return void Rr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(_.length!==1)return;Ve=function(Lt){const Pt=Lt[0].x===Lt[Lt.length-1].x&&Lt[0].y===Lt[Lt.length-1].y;(function(dr){let sr=0;const Tr=dr.length;for(let zr=0;zr=0})(Lt)||(Lt=Lt.reverse());const bs={geometry:[],joinNormals:[],indices:[]},Ts=[],Rs=[],Es=[];let Ws=Lt.length;for(;Ws>=2&&Lt[Ws-1].equals(Lt[Ws-2]);)Ws--;if(Ws<(Pt?3:2))return bs;let ls,Ps,zs,Ks,tr,Ar=0;for(;Ar0;let Gr="miter";const Vn=2;Gr==="miter"&&zr>Vn&&(Gr="bevel"),Gr==="bevel"&&(zr>100&&(Gr="flipbevel"),zr{const hi=new ss(Hn.x,Hn.y),Za=new ss(Hn.x,Hn.y);hi.x+=Va.x*Ho,hi.y+=Va.y*Ho,Za.x-=Va.x*Math.max(ca,1),Za.y-=Va.y*Math.max(ca,1),Es.push(Va),Ts.push(hi),Rs.push(Za)};if(Gr==="miter")sr._mult(zr),$a(ls,sr,0,0);else if(Gr==="flipbevel")sr=tr.mult(-1),$a(ls,sr,0,0),$a(ls,sr.mult(-1),0,0);else{const Hn=-Math.sqrt(zr*zr-1),Va=mn?Hn:0,ca=mn?0:Hn;Ps&&$a(ls,Ks,Va,ca),zs&&$a(ls,tr,Va,ca)}}bs.geometry=[...Ts,...Rs.reverse(),Ts[0]],bs.joinNormals=[...Es,...Es.reverse(),Es[Es.length-1]];const ur=bs.geometry.length-1;for(let dr=0;drLt<(Pt.length-1)/2||Lt===Pt.length-1,ut=this.wallMode?[_]:t6(_,500);for(let Lt=ut.length-1;Lt>=0;Lt--){const Pt=ut[Lt];(Pt.length===0||b0t(Pt[0]))&&ut.splice(Lt,1)}let ft;if(me)ft=DMe(ut,se,M);else{ft=[];for(const Lt of ut)ft.push({polygon:Lt,bounds:se})}const Bt=ge?this.edgeRadius:0,Et=Bt>0&&this.zoom<17,Ot=(Lt,Pt)=>{if(Lt.length===0)return!1;const hs=Lt[Lt.length-1];return Pt.x===hs.x&&Pt.y===hs.y};for(const{polygon:Lt,bounds:Pt}of ft){let hs=0,bs=0;for(const Ws of Lt)ge&&!Ws[0].equals(Ws[Ws.length-1])&&Ws.push(Ws[0]),bs+=ge?Ws.length-1:Ws.length;const Ts=this.segments.prepareSegment((ge?5:4)*bs,this.layoutVertexArray,this.indexArray);Ee.footprintSegIdx<0&&(Ee.footprintSegIdx=this.footprintSegments.length),Ee.polygonSegIdx<0&&(Ee.polygonSegIdx=this.polygonSegments.length);const Rs={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Es=new CMe;if(Es.vertexOffset=this.footprintVertices.length,Es.indexOffset=3*this.footprintIndices.length,Es.ringIndices=[],ge){const Ws=[],ls=[];hs=Ts.vertexLength;for(let zs=0;zs4&&IMe(ls[ls.length-2],ls[0],ls[1]),zs=Bt?v0t(ls[ls.length-2],ls[0],ls[1],Bt):0;const Ks=[];let tr,Ar,ur;Ar=ls[1].sub(ls[0])._perp()._unit();let dr=!0;for(let sr=1,Tr=0;sr0?1:0,Va=zr.dist(mn);if(Tr+Va>32768&&(Tr=0),Bt){ur=Gr.sub(mn)._perp()._unit();let Za=AMe(zr,mn,Gr,EMe(Ar,ur),Bt);isNaN(Za)&&(Za=0);const Ui=mn.sub(zr)._unit();zr=zr.add(Ui.mult(zs))._round(),mn=mn.add(Ui.mult(-Za))._round(),zs=Za,Ar=ur,Fe&&this.zoom>=17&&(Ot(Ks,zr)||Ks.push(zr),Ot(Ks,mn)||Ks.push(mn))}const ca=Ts.vertexLength,Ho=ls.length>4&&IMe(zr,mn,Gr);let hi=LMe(Tr,Ps,dr);if(a6(this.layoutVertexArray,zr.x,zr.y,$a,Hn,0,0,hi),a6(this.layoutVertexArray,zr.x,zr.y,$a,Hn,0,1,hi),this.wallMode){const Za=at(sr-1,ls),Ui=Ve.joinNormals[sr-1];i6(this.wallVertexArray,Ui,Za),i6(this.wallVertexArray,Ui,Za)}if(Tr+=Va,hi=LMe(Tr,Ho,!dr),Ps=Ho,a6(this.layoutVertexArray,mn.x,mn.y,$a,Hn,0,0,hi),a6(this.layoutVertexArray,mn.x,mn.y,$a,Hn,0,1,hi),this.wallMode){const Za=at(sr,ls),Ui=Ve.joinNormals[sr];i6(this.wallVertexArray,Ui,Za),i6(this.wallVertexArray,Ui,Za)}if(Ts.vertexLength+=4,this.indexArray.emplaceBack(ca+0,ca+1,ca+2),this.indexArray.emplaceBack(ca+1,ca+3,ca+2),Ts.primitiveLength+=2,Bt){const Za=hs+(sr===1?ls.length-2:sr-2),Ui=sr===1?hs:Za+1;if(this.indexArray.emplaceBack(ca+1,Za,ca+3),this.indexArray.emplaceBack(Za,Ui,ca+3),Ts.primitiveLength+=2,tr===void 0&&(tr=ca),!oye(Gr,ls[sr],Pt)){const Io=sr===ls.length-1?tr:Ts.vertexLength;this.indexArray.emplaceBack(ca+2,ca+3,Io),this.indexArray.emplaceBack(ca+3,Io+1,Io),this.indexArray.emplaceBack(ca+3,Ui,Io+1),Ts.primitiveLength+=3}dr=!dr}if(me){const Za=this.layoutVertexExtArray,Ui=ae.projectTilePoint(zr.x,zr.y,M),Io=ae.projectTilePoint(mn.x,mn.y,M),Lc=ae.upVector(M,zr.x,zr.y),Lo=ae.upVector(M,mn.x,mn.y);o6(Za,Ui,Lc),o6(Za,Ui,Lc),o6(Za,Io,Lo),o6(Za,Io,Lo)}}ge&&(hs+=ls.length-1),Fe&&Bt&&this.zoom>=17&&(Ks.length!==0&&Ot(Ks,Ks[0])&&Ks.pop(),this.groundEffect.addData(Ks,Pt,ee,Bt>0))}this.footprintSegments.push(Es),Rs.triangleCount=this.indexArray.length-Rs.triangleArrayOffset,this.polygonSegments.push(Rs),++Ee.footprintSegLen,++Ee.polygonSegLen}if(Ee.vertexCount=this.layoutVertexArray.length-Ee.vertexArrayOffset,Ee.groundVertexCount=this.groundEffect.vertexArray.length-Ee.groundVertexArrayOffset,Ee.vertexCount!==0){if(Ee.centroidXY=we.borders?g7:this.encodeCentroid(we,Ee),f.properties&&f.properties.hasOwnProperty("building_id")){const Lt=Ee.buildingId;let Pt=this.buildingGroups.get(Lt);Pt||(Pt={accX:0,accY:0,accCount:0,mergedMin:new ss(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new ss(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Lt,Pt)),Pt.accX+=we.acc.x,Pt.accY+=we.acc.y,Pt.accCount+=we.accCount,Pt.mergedMin.x=Math.min(Pt.mergedMin.x,Ee.min.x),Pt.mergedMin.y=Math.min(Pt.mergedMin.y,Ee.min.y),Pt.mergedMax.x=Math.max(Pt.mergedMax.x,Ee.max.x),Pt.mergedMax.y=Math.max(Pt.mergedMax.y,Ee.max.y),Pt.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Ee),we.borders){this.featuresOnBorder.push(we);const Lt=this.featuresOnBorder.length-1;for(let Pt=0;Ptthis.featuresOnBorder[f].borders[u][0]-this.featuresOnBorder[_].borders[u][0])}splitToSubtiles(){const u=[];for(let B=0;Bfr),ee=2*W+(+(U.min.x+U.max.x>fr)^W);for(let se=0;seB.triangleSegmentIdx===U.triangleSegmentIdx?B.subtile-U.subtile:B.triangleSegmentIdx-U.triangleSegmentIdx);let _=0,C=0,M=0;for(const B of u){if(B.triangleSegmentIdx!==_)break;M++}const P=u.length;for(;C!==u.length;){_=u[C].triangleSegmentIdx;let B=0,U=C,W=C;for(let ee=U;ee0&&this.triangleSubSegments.push({segment:me,min:se,max:ae}),U=W;for(let ge=U;ge[we[0]*(1-Fe[0])+Ee[0]*Fe[0],we[1]*(1-Fe[1])+Ee[1]*Fe[1]],me=[],ge=[];for(const we of this.triangleSubSegments){me[0]=we.min.x/fr,me[1]=we.min.y/fr,ge[0]=we.max.x/fr,ge[1]=we.max.y/fr;const Ee=ae(ee,se,me),Fe=ae(ee,se,ge);if(new fi([Ee[0],Ee[1],M],[Fe[0],Fe[1],P]).intersectsPrecise(_)===0){W&&(C.segments.push(W),W=void 0);continue}const Qe=we.segment;W&&W.vertexOffset!==Qe.vertexOffset&&(C.segments.push(W),W=void 0),W?(W.vertexLength+=Qe.vertexLength,W.primitiveLength+=Qe.primitiveLength):W={vertexOffset:Qe.vertexOffset,primitiveLength:Qe.primitiveLength,vertexLength:Qe.vertexLength,primitiveOffset:Qe.primitiveOffset,sortKey:void 0,vaos:{}}}return W&&C.segments.push(W),C}encodeCentroid(u,f){const _=u.centroid(),C=f.span(),M=Math.min(7,Math.round(C.x*this.tileToMeter/10)),P=Math.min(6,Math.round(C.y*this.tileToMeter/10));return new ss(ze(_.x,1,8191)<<3|M,ze(_.y,1,8191)<<3|P)}encodeBorderCentroid(u){if(!u.borders)return new ss(0,0);const f=u.borders,_=Number.MAX_VALUE;if(f[0][0]!==_||f[1][0]!==_){const C=f[0][0]!==_?0:1;return new ss(6|(f[0][0]!==_?0:65528),(f[C][0]+f[C][1])/2<<3|6)}{const C=f[2][0]!==_?2:3;return new ss((f[C][0]+f[C][1])/2<<3|6,6|(f[2][0]!==_?0:65528))}}showCentroid(u){const f=this.centroidData[u.centroidDataIndex];if(f.flags&=_1,f.groupCentroidPos.x!==0||f.groupCentroidPos.y!==0){const _=f.span(),C=Math.min(7,Math.round(_.x*this.tileToMeter/10)),M=Math.min(6,Math.round(_.y*this.tileToMeter/10));f.centroidXY=new ss(ze(f.groupCentroidPos.x,1,8191)<<3|C,ze(f.groupCentroidPos.y,1,8191)<<3|M)}else f.centroidXY=new ss(0,0);this.writeCentroidToBuffer(f)}writeCentroidToBuffer(u){this.groundEffect.updateHiddenByLandmark(u);const f=u.vertexArrayOffset,_=u.vertexCount+u.vertexArrayOffset,C=-1073741824&u.flags?g7:u.centroidXY,M=this.centroidVertexArray.geta_centroid_pos0(f);if(this.centroidVertexArray.geta_centroid_pos1(f)!==C.y||M!==C.x){for(let P=f;P<_;++P)this.centroidVertexArray.emplace(P,C.x,C.y);this.needsCentroidUpdate=!0}}createCentroidsBuffer(){this.centroidVertexArray.resize(this.layoutVertexArray.length),this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const u of this.centroidData)this.writeCentroidToBuffer(u)}updateReplacement(u,f,_){if(f.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=f.updateTime;const C=f.getReplacementRegionsForTile(u.toUnwrapped());if(p7(this.activeReplacements,C))return;if(this.activeReplacements=C,this.centroidVertexArray.length===0)this.createCentroidsBuffer();else for(const P of this.centroidData)P.flags&=1073741823;const M=[];for(const P of this.activeReplacements){if(P.order<_)continue;const B=Math.max(1,Math.pow(2,P.footprintTileId.canonical.z-u.canonical.z));if(P.footprint.buildingIds)for(const U of this.centroidData)U.flags&_1||U.flags&y7||P.min.x>U.max.x||U.min.x>P.max.x||P.min.y>U.max.y||U.min.y>P.max.y||P.footprint.buildingIds.has(U.buildingId)&&(U.flags|=P.clipMask!==x7.None?-1073741824:_1);else for(const U of this.centroidData)if(!(U.flags&_1||U.flags&y7||P.min.x>U.max.x||U.min.x>P.max.x||P.min.y>U.max.y||U.min.y>P.max.y))for(let W=0;Wf!=me>f&&u<(this.footprintVertices.int16[2*(ee+P.vertexOffset)+0]-se)*(f-ae)/(me-ae)+se&&(C=!C)}B=U}}return C}getHeightAtTileCoord(u,f){let _=Number.NEGATIVE_INFINITY,C=!0;const M=4*(u+fr)*fr+(f+fr);if(this.partLookup.hasOwnProperty(M)){const P=this.partLookup[M];return P?{height:P.height,hidden:!!(P.flags&_1)}:void 0}for(const P of this.centroidData)u>P.max.x||P.min.x>u||f>P.max.y||P.min.y>f||P.height<=_||this.footprintContainsPoint(u,f,P)&&(_=P.height,this.partLookup[M]=P,C=!!(P.flags&_1));if(_!==Number.NEGATIVE_INFINITY)return{height:_,hidden:C};this.partLookup[M]=void 0}}function EMe(g,u){const f=g.add(u)._unit();return g.x*f.x+g.y*f.y}function v0t(g,u,f,_){const C=u.sub(g)._perp()._unit(),M=f.sub(u)._perp()._unit();return AMe(g,u,f,EMe(C,M),_)}function AMe(g,u,f,_,C){const M=Math.sqrt(1-_*_);return Math.min(g.dist(u)/3,u.dist(f)/3,C*M/_)}function oye(g,u,f){return g.xf[1].x&&u.x>f[1].x||g.yf[1].y&&u.y>f[1].y}function MMe(g,u){return g.xu[1].x||g.yu[1].y}function b0t(g){return g.every(u=>u.x<=0)||g.every(u=>u.x>=fr)||g.every(u=>u.y<=0)||g.every(u=>u.y>=fr)}function IMe(g,u,f){if(g.x<0||g.x>=fr||u.x<0||u.x>=fr||f.x<0||f.x>=fr)return!1;const _=f.sub(u),C=_.perp(),M=g.sub(u);return(_.x*M.x+_.y*M.y)/Math.sqrt((_.x*_.x+_.y*_.y)*(M.x*M.x+M.y*M.y))>-.866&&C.x*M.x+C.y*M.y<0}function LMe(g,u,f){const _=u?2|g:-3&g;return f?1|_:-2&_}function PMe(){const g=Math.PI/32,u=Math.tan(g),f=Rt;return f*Math.sqrt(1+2*u*u)-f}function DMe(g,u,f){const _=1<{for(const Et of ft)ge.push({polygon:Et,bounds:Bt})},Ee=Math.ceil(Math.log2(ee)),Fe=Math.ceil(Math.log2(se)),Qe=Ee-Fe,Ve=[];for(let ft=0;ft0?0:1);for(let ft=0;ftBt+1?ut.push({polygons:Ts,bounds:Es,depth:Bt+1}):we(Ts,Es)}if(Rs.length){const Es=[new ss(Et===0?bs:Ot.x,Et===1?bs:Ot.y),Lt];Ve.length>Bt+1?ut.push({polygons:Rs,bounds:Es,depth:Bt+1}):we(Rs,Es)}}return ge}(g,u,Math.ceil((M-C)/11.25),Math.ceil((P-B)/11.25),1,(U,W,ee)=>{if(U===0)return .5*(W+ee);{const se=us((f.y+W/fr)/_);return(Hs(.5*(us((f.y+ee/fr)/_)+se))*_-f.y)*fr}})}function _0t(g,u,f,_,C,M){const P=Math.pow(2,_.z-C.z);for(let B=0;B=U[P]&&(B=u,U=g),B[P]C&&BMe(B,U,P,C),B[P]M&&BMe(U,B,P,M)}}function _7(g,u,f,_,C,M){const P=[];for(let B=0;B=_&&ge.x>=_||(me.x>=_?me=new ss(_,me.y+(_-me.x)/(ge.x-me.x)*(ge.y-me.y))._round():ge.x>=_&&(ge=new ss(_,me.y+(_-me.x)/(ge.x-me.x)*(ge.y-me.y))._round()),me.y>=C&&ge.y>=C||(me.y>=C?me=new ss(me.x+(C-me.y)/(ge.y-me.y)*(ge.x-me.x),C)._round():ge.y>=C&&(ge=new ss(me.x+(C-me.y)/(ge.y-me.y)*(ge.x-me.x),C)._round()),W&&me.equals(W[W.length-1])||(W=[me],P.push(W),M&&M.push({progress:{min:Ee+$Me(Fe,Qe,me)*we,max:1},parentIndex:B,prevPoint:Fe,nextPoint:Qe})),W.push(ge),M&&(M[M.length-1].progress.max=Ee+$Me(Fe,Qe,ge)*we,M[M.length-1].nextPoint=Qe)))))}if(M&&se>0)for(let ae=ee;aeW.t-ee.t);let P=0,B=0,U=[];for(_.push(U);P!==g.length;){if(B===M.length){for(;P!==g.length;)U.length!==0&&U[U.length-1].equals(g[P])||U.push(g[P]),P++;break}M[B].t<=P?(U.length!==0&&U[U.length-1].equals(M[B].point)||U.push(M[B].point),Math.trunc(M[B].t),B++):(U.length!==0&&U[U.length-1].equals(g[P])||U.push(g[P]),P++)}}function $Me(g,u,f){return g.x!==u.x?(f.x-g.x)/(u.x-g.x):g.y!==u.y?(f.y-g.y)/(u.y-g.y):0}function l6(g,u){return g.x*u.x+g.y*u.y}function UMe(g,u){if(g.length===1){let f=0;const _=u[f++];let C;for(;!C||_.equals(C);)if(C=u[f++],!C)return 1/0;for(;f{bs[0]=Ts,bs[1]=Rs,bs[2]=Es,bs[3]=1},hs=PMe();me>0&&(me+=hs),ge+=hs;for(const bs of ae){const Ts=[],Rs=[];for(const Es of bs){const Ws=Es.x+we.x,ls=Es.y+we.y,Ps=se.projection.projectTilePoint(Ws,ls,ut),zs=se.projection.upVector(ut,Es.x,Es.y);let Ks=me,tr=ge;if(Fe){const Ar=HMe(Ws,ls,me,ge,Fe,Qe,Ve,at);Ks+=Ar.base,tr+=Ar.top}me!==0?Pt(Ot,Ps.x+zs[0]*Et*Ks,Ps.y+zs[1]*Et*Ks,Ps.z+zs[2]*Et*Ks):Pt(Ot,Ps.x,Ps.y,Ps.z),Pt(Lt,Ps.x+zs[0]*Et*tr,Ps.y+zs[1]*Et*tr,Ps.z+zs[2]*Et*tr),et(Ot,Ot,Ee),et(Lt,Lt,Ee),Ts.push(new cN(Ot[0],Ot[1],Ot[2])),Rs.push(new cN(Lt[0],Lt[1],Lt[2]))}ft.push(Ts),Bt.push(Rs)}return[ft,Bt]}(g,u,f,_,C,M,P,B,U,W,ee):P?function(se,ae,me,ge,we,Ee,Fe,Qe,Ve){const at=[],ut=[],ft=[0,0,0,1];for(const Bt of se){const Et=[],Ot=[];for(const Lt of Bt){const Pt=Lt.x+ge.x,hs=Lt.y+ge.y,bs=HMe(Pt,hs,ae,me,Ee,Fe,Qe,Ve);ft[0]=Pt,ft[1]=hs,ft[2]=bs.base,ft[3]=1,xt(ft,ft,we),ft[3]=Math.max(ft[3],1e-5);const Ts=new cN(ft[0]/ft[3],ft[1]/ft[3],ft[2]/ft[3]);ft[0]=Pt,ft[1]=hs,ft[2]=bs.top,ft[3]=1,xt(ft,ft,we),ft[3]=Math.max(ft[3],1e-5);const Rs=new cN(ft[0]/ft[3],ft[1]/ft[3],ft[2]/ft[3]);Et.push(Ts),Ot.push(Rs)}at.push(Et),ut.push(Ot)}return[at,ut]}(u,f,_,C,M,P,B,U,W):function(se,ae,me,ge,we){const Ee=[],Fe=[],Qe=we[8]*ae,Ve=we[9]*ae,at=we[10]*ae,ut=we[11]*ae,ft=we[8]*me,Bt=we[9]*me,Et=we[10]*me,Ot=we[11]*me;for(const Lt of se){const Pt=[],hs=[];for(const bs of Lt){const Ts=bs.x+ge.x,Rs=bs.y+ge.y,Es=we[0]*Ts+we[4]*Rs+we[12],Ws=we[1]*Ts+we[5]*Rs+we[13],ls=we[2]*Ts+we[6]*Rs+we[14],Ps=we[3]*Ts+we[7]*Rs+we[15],zs=Es+Qe,Ks=Ws+Ve,tr=ls+at,Ar=Math.max(Ps+ut,1e-5),ur=Es+ft,dr=Ws+Bt,sr=ls+Et,Tr=Math.max(Ps+Ot,1e-5);Pt.push(new cN(zs/Ar,Ks/Ar,tr/Ar)),hs.push(new cN(ur/Tr,dr/Tr,sr/Tr))}Ee.push(Pt),Fe.push(hs)}return[Ee,Fe]}(u,f,_,C,M)}function HMe(g,u,f,_,C,M,P,B){const U=P*C.getElevationAt(g,u,!0,!0),W=M[0]!==0,ee=W?M[1]===0?P*(M[0]/7-450):P*function(se,ae,me){const ge=Math.floor(ae[0]/8),we=Math.floor(ae[1]/8),Ee=10*(ae[0]-8*ge),Fe=10*(ae[1]-8*we),Qe=se.getElevationAt(ge,we,!0,!0),Ve=se.getMeterToDEM(me),at=Math.floor(.5*(Ee*Ve-1)),ut=Math.floor(.5*(Fe*Ve-1)),ft=se.tileCoordToPixel(ge,we),Bt=2*at+1,Et=2*ut+1,Ot=function(Rs,Es,Ws,ls,Ps){return[Rs.getElevationAtPixel(Es,Ws,!0),Rs.getElevationAtPixel(Es+Ps,Ws,!0),Rs.getElevationAtPixel(Es,Ws+Ps,!0),Rs.getElevationAtPixel(Es+ls,Ws+Ps,!0)]}(se,ft.x-at,ft.y-ut,Bt,Et),Lt=Math.abs(Ot[0]-Ot[1]),Pt=Math.abs(Ot[2]-Ot[3]),hs=Math.abs(Ot[0]-Ot[2])+Math.abs(Ot[1]-Ot[3]),bs=Math.min(.25,.5*Ve*(Lt+Pt)/Bt),Ts=Math.min(.25,.5*Ve*hs/Et);return Qe+Math.max(bs*Ee,Ts*Fe)}(C,M,B):U;return{base:U+(f===0?-1:f),top:W?Math.max(ee+_,U+f+2):U+_}}const lye=4096;class j0t{constructor(u){this.module=u,this.memoryStack=this.module.malloc(lye),this.memoryStackNextFree=this.memoryStack}createIntArray(u){const f=this.memoryStackNextFree;return this.memoryStackNextFree+=u.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>lye?-1:(new Int32Array(this.module.heap32.buffer,f,u.length).set(u),f)}createFloatArray(u){const f=this.memoryStackNextFree;return this.memoryStackNextFree+=u.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>lye?-1:(new Float32Array(this.module.heapF32.buffer,f,u.length).set(u),f)}readStringBuffer(u){let f="";for(;this.module.heapU8[u]!==0;)f+=String.fromCharCode(this.module.heapU8[u]),++u;return f}setStyle(u){const f=u.normalScale;this.module.setStyle(f[0],f[1],f[2],u.tileToMeters)}setAOOptions(u,f){this.module.setAOOptions(u?1:0,f)}setMetricOptions(u,f){this.module.setMetricOptions(u?1:0,f)}setStructuralOptions(u){this.module.setStructuralOptions(u?1:0)}setFacadeOptions(u,f){this.module.setFacadeOptions(u,f?1:0)}setFauxFacadeOptions(u,f,_){this.module.setFauxFacadeOptions(u?1:0,f?1:0,_)}setFacadeClassifierOptions(u){this.module.setFacadeClassifierOptions(u)}generateMesh(u,f){this.memoryStackNextFree=this.memoryStack;for(const B of u){const U=this.createIntArray(B.ringIndices),W=this.createFloatArray(B.coordinates);if(U===-1||W===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(B.id,B.sourceId,B.minHeight,B.height,B.roofType,W,U,B.ringIndices.length-1)}for(const B of f){let U;U=B.entrances?JSON.parse(B.entrances):[];const W=this.createFloatArray(U),ee=this.createFloatArray(B.coordinates);if(W===-1||ee===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(B.sourceId,B.crossPerc,B.distanceToRoad,W,U.length,ee,B.coordinates.length)}if(!this.module.generateMesh()){const B=this.module.getLastError();return this.readStringBuffer(B)}const _=this.module.getMeshCount(),C=new Array(_);for(let B=0;B<_;B++){const U=this.module.getPositionsPtr(B),W=this.module.getPositionsLength(B),ee=new Float32Array(this.module.heapF32.buffer,U,W),se=this.module.getNormalsPtr(B),ae=this.module.getNormalsLength(B),me=new Float32Array(this.module.heapF32.buffer,se,ae),ge=this.module.getAOPtr(B),we=this.module.getAOLength(B),Ee=new Float32Array(this.module.heapF32.buffer,ge,we),Fe=this.module.getUVPtr(B),Qe=this.module.getUVLength(B),Ve=new Float32Array(this.module.heapF32.buffer,Fe,Qe),at=this.module.getFauxFacadePtr(B),ut=this.module.getFauxFacadeLength(B),ft=new Uint8Array(this.module.heapU8.buffer,at,ut),Bt=this.module.getIndicesPtr(B),Et=this.module.getIndicesLength(B),Ot=new Int16Array(this.module.heap16.buffer,Bt,Et),Lt=this.module.getBuildingPart(B);C[B]={positions:ee,normals:me,ao:Ee,uv:Ve,isFauxFacade:ft,indices:Ot,buildingPart:Lt}}const M=this.module.getRingCount(),P=[];for(let B=0;B>2)-3,Ee=me[ge++]>>2;if(ge++,C.json=JSON.parse(tIe.decode(me.subarray(ge,ge+Ee))),ge+=Ee,ge>>0,Math.ceil(1.2*at)),ft=Math.ceil((ut-at)/65536);try{return we.grow(ft),Ee(),!0}catch{return!1}},b:Fe}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(me,Qe):me.then(Ve=>Ve.arrayBuffer()).then(Ve=>WebAssembly.instantiate(Ve,Qe))).then(Ve=>{const{Rb:at,Qb:ut,P:ft,T:Bt,X:Et,Ja:Ot,La:Lt,Qa:Pt,Va:hs,Wa:bs,eb:Ts,jb:Rs,f:Es,e:Ws,yb:ls,zb:Ps,Ab:zs,Bb:Ks,Db:tr,Gb:Ar}=Ve.instance.exports;we=Ws;const ur=(()=>{let dr=0,sr=0,Tr=0,zr=0;return mn=>{Tr&&(at(zr),at(dr),sr+=Tr,Tr=dr=0),dr||(sr+=128,dr=ut(sr));const Gr=mn.length+7&-8;let Vn=dr;Gr>=sr&&(Tr=Gr,Vn=zr=ut(Gr));for(let $a=0;$a{qg=me,c6=void 0}))}()),ae&&ee.push(function(){if(cye)return;const me=function(ge){let we;const Ee=WebAssembly.instantiateStreaming(ge,{}).then(Ve=>{we=Ve.instance,we.exports.__wasm_call_ctors()}),Fe={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},Qe={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:Ee,supported:!0,decodeGltfBuffer(Ve,at,ut,ft,Bt,Et){(function(Ot,Lt,Pt,hs,bs,Ts,Rs){const Es=Ot.exports.sbrk,Ws=hs+3&-4,ls=Es(Ws*bs),Ps=Es(Ts.length),zs=new Uint8Array(Ot.exports.memory.buffer);zs.set(Ts,Ps);const Ks=Lt(ls,hs,bs,Ps,Ts.length);if(Ks===0&&Rs&&Rs(ls,Ws,bs),Pt.set(zs.subarray(ls,ls+hs*bs)),Es(ls-Es(0)),Ks!==0)throw new Error(`Malformed buffer data: ${Ks}`)})(we,we.exports[Qe[Bt]],Ve,at,ut,ft,we.exports[Fe[Et]])}}}(fetch(ra()));return me.ready.then(()=>{cye=me})}()),P)for(let me=0;me{const B=Ky(_,(U,W)=>{U?P(U):M(W)});C&&C.addEventListener("abort",()=>{B.cancel(),P(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:g,type:"arrayBuffer"},u);return nIe(f,0,g,u)}function uye(g){switch(g){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 hye(g){switch(g){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 m0{constructor(u,f,_,C){this.context=u,this.format=_,this.useMipmap=C&&C.useMipmap,this.texture=u.gl.createTexture(),this.update(f,{premultiply:C&&C.premultiply})}update(u,f){const _=u&&u instanceof HTMLVideoElement&&u.width===0?u.videoWidth:u.width,C=u&&u instanceof HTMLVideoElement&&u.height===0?u.videoHeight:u.height,{context:M}=this,{gl:P}=M,{x:B,y:U}=f&&f.position?f.position:{x:0,y:0},W=B+_,ee=U+C;this.size&&(this.size[0]!==W||this.size[1]!==ee)&&(!f||f.recreateWhenResize===void 0||f.recreateWhenResize)&&(P.bindTexture(P.TEXTURE_2D,null),P.deleteTexture(this.texture),this.texture=P.createTexture(),this.size=null),P.bindTexture(P.TEXTURE_2D,this.texture),M.pixelStoreUnpackFlipY.set(!1),M.pixelStoreUnpack.set(1),M.pixelStoreUnpackPremultiplyAlpha.set(this.format===P.RGBA8&&(!f||f.premultiply!==!1));const se=u instanceof HTMLImageElement||u instanceof HTMLCanvasElement||u instanceof HTMLVideoElement||u instanceof ImageData||ImageBitmap&&u instanceof ImageBitmap;if(!this.size&&W>0&&ee>0){const ae=this.useMipmap?Math.floor(Math.log2(Math.max(W,ee)))+1:1;P.texStorage2D(P.TEXTURE_2D,ae,this.format,W,ee),this.size=[W,ee]}this.size&&(se?P.texSubImage2D(P.TEXTURE_2D,0,B,U,uye(this.format),hye(this.format),u):"data"in u&&u.data&&P.texSubImage2D(P.TEXTURE_2D,0,B,U,_,C,uye(this.format),hye(this.format),u.data)),this.useMipmap&&P.generateMipmap(P.TEXTURE_2D)}bind(u,f,_=!1){const{context:C}=this,{gl:M}=C;M.bindTexture(M.TEXTURE_2D,this.texture),u!==this.minFilter&&(M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MAG_FILTER,u),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MIN_FILTER,this.useMipmap&&!_?u===M.NEAREST?M.NEAREST_MIPMAP_NEAREST:M.LINEAR_MIPMAP_LINEAR:u),this.minFilter=u),f!==this.wrapS&&(M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_S,f),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_T,f),this.wrapS=f)}bindExtraParam(u,f,_,C,M){const{context:P}=this,{gl:B}=P;B.bindTexture(B.TEXTURE_2D,this.texture),f!==this.magFilter&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_MAG_FILTER,f),this.magFilter=f),u!==this.minFilter&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_MIN_FILTER,this.useMipmap?u===B.NEAREST?B.NEAREST_MIPMAP_NEAREST:B.LINEAR_MIPMAP_LINEAR:u),this.minFilter=u),_!==this.wrapS&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_WRAP_S,_),this.wrapS=_),C!==this.wrapT&&(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_WRAP_T,C),this.wrapT=C),M!==this.compareMode&&(M?(B.texParameteri(B.TEXTURE_2D,B.TEXTURE_COMPARE_MODE,B.COMPARE_REF_TO_TEXTURE),B.texParameteri(B.TEXTURE_2D,B.TEXTURE_COMPARE_FUNC,M)):B.texParameteri(B.TEXTURE_2D,B.TEXTURE_COMPARE_MODE,B.NONE),this.compareMode=M)}destroy(){const{gl:u}=this.context;u.deleteTexture(this.texture),this.texture=null}}class u6{constructor(u,f){this.context=u,this.texture=f}bind(u,f){const{context:_}=this,{gl:C}=_;C.bindTexture(C.TEXTURE_2D,this.texture),u!==this.minFilter&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MAG_FILTER,u),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_MIN_FILTER,u),this.minFilter=u),f!==this.wrapS&&(C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_S,f),C.texParameteri(C.TEXTURE_2D,C.TEXTURE_WRAP_T,f),this.wrapS=f)}}const A0t=Ta([{name:"a_pos_3f",components:3,type:"Float32"}]),M0t=Ta([{name:"a_color_3f",components:3,type:"Float32"}]),I0t=Ta([{name:"a_color_4f",components:4,type:"Float32"}]),L0t=Ta([{name:"a_uv_2f",components:2,type:"Float32"}]),P0t=Ta([{name:"a_normal_3f",components:3,type:"Float32"}]),D0t=Ta([{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"}]),R0t=Ta([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function iIe(g,u){const f=k7(g.projection,g.zoom,g.width,g.height),_=function(M,P,B,U,W){const ee=new qt(B.lng-180*S_,B.lat),se=new qt(B.lng+180*S_,B.lat),ae=M.project(ee.lng,ee.lat),me=M.project(se.lng,se.lat),ge=-Math.atan2(me.y-ae.y,me.x-ae.x),we=Br.fromLngLat(B);we.y=ze(we.y,-1+S_,1-S_);const Ee=we.toLngLat(),Fe=M.project(Ee.lng,Ee.lat),Qe=Br.fromLngLat(Ee);Qe.x+=S_;const Ve=Qe.toLngLat(),at=M.project(Ve.lng,Ve.lat),ut=lIe(at.x-Fe.x,at.y-Fe.y,ge),ft=Br.fromLngLat(Ee);ft.y+=S_;const Bt=ft.toLngLat(),Et=M.project(Bt.lng,Bt.lat),Ot=lIe(Et.x-Fe.x,Et.y-Fe.y,ge),Lt=Math.abs(ut.x)/Math.abs(Ot.y),Pt=b([]);R(Pt,Pt,-ge*(1-(W?0:U)));const hs=b([]);return A(hs,hs,[1,1-(1-Lt)*U,1]),hs[4]=-Ot.x/Ot.y*U,R(hs,hs,ge),S(hs,Pt,hs),hs}(g.projection,0,g.center,f,u),C=oIe(g);return A(_,_,[C,C,1]),_}function oIe(g){const u=g.projection,f=k7(g.projection,g.zoom,g.width,g.height),_=mye(u,g.center),C=mye(u,qt.convert(u.center));return Math.pow(2,_*f+(1-f)*C)}function k7(g,u,f,_,C=1/0){const M=g.range;if(!M)return 0;const P=Math.min(C,Math.max(f,_)),B=Math.log2(P/1024);return st(M[0]+B,M[1]+B,u)}const S_=1/4e4;function mye(g,u){const f=ze(u.lat,-85.051129,ks),_=new qt(u.lng-180*S_,f),C=new qt(u.lng+180*S_,f),M=g.project(_.lng,f),P=g.project(C.lng,f),B=Br.fromLngLat(_),U=Br.fromLngLat(C),W=P.x-M.x,ee=P.y-M.y,se=U.x-B.x,ae=U.y-B.y,me=Math.sqrt((se*se+ae*ae)/(W*W+ee*ee));return Math.log2(me)}function lIe(g,u,f){const _=Math.cos(f),C=Math.sin(f);return{x:g*_-u*C,y:g*C+u*_}}function cIe(g,u,f){b(g),R(g,g,Pr(u[2])),I(g,g,Pr(u[0])),D(g,g,Pr(u[1])),A(g,g,f),S(g,g,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function S7(g,u,f,_,C,M,P,B){const U=[f[0]-u[0],f[1]-u[1],0],W=[_[0]-u[0],_[1]-u[1],0];if(re(U)<1e-12||re(W)<1e-12)return Je(g);const ee=Te([],U,W);Le(ee,ee),ie(W,_,u),U[2]=(M-C)*B,W[2]=(P-C)*B;const se=U;return Te(se,U,W),Le(se,se),cs(g,ee,se)}function C7(g,u,f=!1){const _=v1(u.zoom),C=function(M,P,B){const U=P.worldSize,W=[M[12],M[13],M[14]],ee=us(W[1]/U),se=Ht(W[0]/U),ae=b([]),me=Qt(1,ee)*U,ge=Qt(1,0)*U*Js(ee,P.zoom),we=1/Fge(U);let Ee=ge*we;if(B){const at=k7(P.projection,P.zoom,P.width,P.height,1024);Ee=we*P.projection.pixelSpaceConversion(P.center.lat,U,at)}const Fe=St(ee,se);ne(Fe,Fe,be([],Le([],Fe),me*Ee*W[2]));const Qe=function(at){const ut=[at[0],at[1],at[2]];let ft=[0,1,0];const Bt=Te([],ft,ut);return Te(ft,ut,Bt),Ae(ft)===0&&(ft=[0,1,0],Te(Bt,ut,ft)),Le(Bt,Bt),Le(ft,ft),Le(ut,ut),[Bt[0],Bt[1],Bt[2],0,ft[0],ft[1],ft[2],0,ut[0],ut[1],ut[2],0,at[0],at[1],at[2],1]}(Fe);A(ae,ae,[Ee,Ee,Ee*me]),T(ae,ae,[-W[0],-W[1],-W[2]]);const Ve=S([],P.globeMatrix,Qe);return S(Ve,Ve,ae),S(Ve,Ve,M),Ve}(g,u,f);if(_>0){const M=function(P,B){const U=B.worldSize,W=Qt(1,0)*U*Js(B.center.lat,B.zoom)/Fge(U),ee=Qt(1,B.center.lat)*U,se=b([]);D(se,se,Pr(B.center.lng)),I(se,se,Pr(B.center.lat)),T(se,se,[0,0,vt]),A(se,se,[W,W,W*ee]);const ae=B.point;return T(se,se,[-ae.x,-ae.y,0]),S(se,se,P),S(se,B.globeMatrix,se)}(g,u);return function(P,B,U){const W=(ge,we,Ee)=>{const Fe=re(ge),Qe=re(we),Ve=y1(ge,we,Ee);return be(Ve,Ve,1/re(Ve)*hn(Fe,Qe,Ee))},ee=W([P[0],P[1],P[2]],[B[0],B[1],B[2]],U),se=W([P[4],P[5],P[6]],[B[4],B[5],B[6]],U),ae=W([P[8],P[9],P[10]],[B[8],B[9],B[10]],U),me=y1([P[12],P[13],P[14]],[B[12],B[13],B[14]],U);return[ee[0],ee[1],ee[2],0,se[0],se[1],se[2],0,ae[0],ae[1],ae[2],0,me[0],me[1],me[2],1]}(C,M,_)}return C}function fye(g,u,f,_){const C=fi.projectAabbCorners(_,f);let M=Number.MAX_VALUE;for(let B=0;B0||Ee===0&&ge[0]*we[0]+ge[1]*we[1]>=0&&ge[0]*ge[0]+ge[1]*ge[1]>we[0]*we[0]+we[1]*we[1])&&(ee=me)}se=ee}while(se!==W);return U.length>0&&U.push(U[0]),U}(C);if(gl(g,P))return M}const dN=64,bT={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function T7(g,u,f,_,C,M,P,B,U,W=!1){const ee=f.zoom,se=f.project(_),ae=Js(_.lat,ee),me=1/ae;b(g),T(g,g,[se.x+P[0]*me,se.y+P[1]*me,P[2]]);let ge=1,we=1;const Ee=f.worldSize;if(W){if(f.projection.name==="mercator"){let at=0;f.elevation&&(at=f.elevation.getAtPointOrZero(new Br(se.x/Ee,se.y/Ee),0));const ut=xt([],[se.x,se.y,at,1],f.projMatrix)[3]/f.cameraToCenterDistance;ge=ut,we=ut*Js(f.center.lat,ee)}else if(f.projection.name==="globe"){const at=C7(g,f),ut=[0,0,0,1];xt(ut,ut,S([],f.projMatrix,at));const ft=ut[3]/f.cameraToCenterDistance,Bt=v1(ee),Et=f.projection.pixelsPerMeter(_.lat,Ee)*Js(_.lat,ee),Ot=f.projection.pixelsPerMeter(f.center.lat,Ee)*Js(f.center.lat,ee);ge=ft/hn(Et,cr(f.center.lat),Bt),we=ft*ae/Et,ge*=Ot,we*=Ot}}else ge=me;A(g,g,[ge,ge,we]);const Fe=[...g],Qe=u.orientation,Ve=[];if(cIe(Ve,[Qe[0]+(C?C[0]:0),Qe[1]+(C?C[1]:0),Qe[2]+(C?C[2]:0)],M),S(g,Fe,Ve),B&&f.elevation){let at=0;const ut=[];if(U&&f.elevation){at=function(Bt,Et,Ot,Lt,Pt){const hs=Et.elevation;if(!hs)return 0;const bs=fi.projectAabbCorners(Ot,Lt),Ts=Qt(1,Pt.lat)*Et.worldSize,Rs=function(sr,Tr){const zr=[0,0,1],mn=[{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 Gr of mn){const Vn=sr[Gr.corners[0]],$a=sr[Gr.corners[1]],Hn=sr[Gr.corners[2]],Va=[$a[0]-Vn[0],$a[1]-Vn[1],Tr*($a[2]-Vn[2])],ca=Te(Va,Va,[Hn[0]-Vn[0],Hn[1]-Vn[1],Tr*(Hn[2]-Vn[2])]);Le(ca,ca),Gr.dotProductWithUp=Ie(ca,zr)}return mn.sort((Gr,Vn)=>Gr.dotProductWithUp-Vn.dotProductWithUp),mn[0].corners}(bs,Ts),Es=bs[Rs[0]],Ws=bs[Rs[1]],ls=bs[Rs[2]],Ps=bs[Rs[3]],zs=hs.getAtPointOrZero(new Br(Es[0]/Et.worldSize,Es[1]/Et.worldSize),0),Ks=hs.getAtPointOrZero(new Br(Ws[0]/Et.worldSize,Ws[1]/Et.worldSize),0),tr=hs.getAtPointOrZero(new Br(ls[0]/Et.worldSize,ls[1]/Et.worldSize),0),Ar=hs.getAtPointOrZero(new Br(Ps[0]/Et.worldSize,Ps[1]/Et.worldSize),0),ur=(zs+Ar)/2,dr=(Ks+tr)/2;return ur>dr?Ks=u.gl.NEAREST_MIPMAP_NEAREST}),g.uploaded=!0,g.image=null)}function O0t(g,u,f){g.indexBuffer=u.createIndexBuffer(g.indexArray,!1,!0),g.vertexBuffer=u.createVertexBuffer(g.vertexArray,A0t.members,!1,!0),g.normalArray&&(g.normalBuffer=u.createVertexBuffer(g.normalArray,P0t.members,!1,!0)),g.texcoordArray&&(g.texcoordBuffer=u.createVertexBuffer(g.texcoordArray,L0t.members,!1,!0)),g.colorArray&&(g.colorBuffer=u.createVertexBuffer(g.colorArray,(g.colorArray.bytesPerElement===12?M0t:I0t).members,!1,!0)),g.featureArray&&(g.pbrBuffer=u.createVertexBuffer(g.featureArray,R0t.members,!0)),g.segments=Bi.simpleSegment(0,0,g.vertexArray.length,g.indexArray.length);const _=g.material;_.pbrMetallicRoughness.baseColorTexture&&h6(_.pbrMetallicRoughness.baseColorTexture,u),_.pbrMetallicRoughness.metallicRoughnessTexture&&h6(_.pbrMetallicRoughness.metallicRoughnessTexture,u),_.normalTexture&&h6(_.normalTexture,u),_.occlusionTexture&&h6(_.occlusionTexture,u,f),_.emissionTexture&&h6(_.emissionTexture,u)}function pye(g,u,f){if(g.meshes)for(const _ of g.meshes)O0t(_,u,f);if(g.children)for(const _ of g.children)pye(_,u,f)}function E7(g){if(g.meshes)for(const u of g.meshes)u.indexArray.destroy(),u.vertexArray.destroy(),u.colorArray&&u.colorArray.destroy(),u.normalArray&&u.normalArray.destroy(),u.texcoordArray&&u.texcoordArray.destroy(),u.featureArray&&u.featureArray.destroy();if(g.children)for(const u of g.children)E7(u)}function F0t(g){g.pbrMetallicRoughness.baseColorTexture&&g.pbrMetallicRoughness.baseColorTexture.gfxTexture&&g.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),g.pbrMetallicRoughness.metallicRoughnessTexture&&g.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&g.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),g.normalTexture&&g.normalTexture.gfxTexture&&g.normalTexture.gfxTexture.destroy(),g.emissionTexture&&g.emissionTexture.gfxTexture&&g.emissionTexture.gfxTexture.destroy(),g.occlusionTexture&&g.occlusionTexture.gfxTexture&&g.occlusionTexture.gfxTexture.destroy()}function xye(g){if(g.meshes)for(const u of g.meshes)u.vertexBuffer&&(u.vertexBuffer.destroy(),u.indexBuffer.destroy(),u.normalBuffer&&u.normalBuffer.destroy(),u.texcoordBuffer&&u.texcoordBuffer.destroy(),u.colorBuffer&&u.colorBuffer.destroy(),u.pbrBuffer&&u.pbrBuffer.destroy(),u.segments.destroy(),u.material&&F0t(u.material));if(g.footprintDebugMesh&&(g.footprintDebugMesh.vertexBuffer.destroy(),g.footprintDebugMesh.indexBuffer.destroy(),g.footprintDebugMesh.segments.destroy()),g.children)for(const u of g.children)xye(u)}function uN(g,u){const f=g.json.bufferViews[u.bufferView],_=j7[u.componentType];return new _(g.buffers[f.buffer],(u.byteOffset||0)+(f.byteOffset||0),u.count*(f.byteStride&&f.byteStride!==d6[u.type]*_.BYTES_PER_ELEMENT?f.byteStride/_.BYTES_PER_ELEMENT:d6[u.type]))}function gye(g,u,f,_){const C=j7[u.componentType],M=function(ee){switch(ee){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(C),P=g.json.bufferViews[u.bufferView],B=P.byteStride?P.byteStride/C.BYTES_PER_ELEMENT:d6[u.type],U=f.float32,W=U.length/f.capacity;for(let ee=0,se=0;ee0){for(let Ee=0;Ee0){M.texcoordArray=new f1;const ae=u.json.accessors[C.TEXCOORD_0];M.texcoordArray.resize(ae.count);const me=uN(u,ae);gye(u,ae,M.texcoordArray,me)}if(C._FEATURE_ID_RGBA4444!==void 0){const ae=u.json.accessors[C._FEATURE_ID_RGBA4444];u.json.extensionsUsed&&u.json.extensionsUsed.includes("EXT_meshopt_compression")&&(M.featureData=uN(u,ae))}C._FEATURE_RGBA4444!==void 0&&(M.featureData=new Uint32Array(uN(u,u.json.accessors[C._FEATURE_RGBA4444]).buffer));const se=g.material;return M.material=function(ae,me){const{emissiveFactor:ge=[0,0,0],alphaMode:we="OPAQUE",alphaCutoff:Ee=.5,normalTexture:Fe,occlusionTexture:Qe,emissiveTexture:Ve,doubleSided:at,name:ut}=ae,{baseColorFactor:ft=[1,1,1,1],metallicFactor:Bt=1,roughnessFactor:Et=1,baseColorTexture:Ot,metallicRoughnessTexture:Lt}=ae.pbrMetallicRoughness||{},Pt=Qe?me[Qe.index]:void 0;if(Qe&&Qe.extensions&&Qe.extensions.KHR_texture_transform&&Pt){const hs=Qe.extensions.KHR_texture_transform;Pt.offsetScale=[hs.offset[0],hs.offset[1],hs.scale[0],hs.scale[1]]}return{name:ut,pbrMetallicRoughness:{baseColorFactor:new wr(...ft),metallicFactor:Bt,roughnessFactor:Et,baseColorTexture:Ot?me[Ot.index]:void 0,metallicRoughnessTexture:Lt?me[Lt.index]:void 0},doubleSided:at,emissiveFactor:new wr(...ge),alphaMode:we,alphaCutoff:Ee,normalTexture:Fe?me[Fe.index]:void 0,occlusionTexture:Pt,emissionTexture:Ve?me[Ve.index]:void 0,defined:ae.defined===void 0}}(se!==void 0?u.json.materials[se]:{defined:!1},f),M}function uIe(g,u,f){const{matrix:_,rotation:C,translation:M,scale:P,mesh:B,extras:U,children:W,name:ee}=g,se={};if(se.name=ee,se.localMatrix=_||function(ae,me,ge,we){var Ee=me[0],Fe=me[1],Qe=me[2],Ve=me[3],at=Ee+Ee,ut=Fe+Fe,ft=Qe+Qe,Bt=Ee*at,Et=Ee*ut,Ot=Ee*ft,Lt=Fe*ut,Pt=Fe*ft,hs=Qe*ft,bs=Ve*at,Ts=Ve*ut,Rs=Ve*ft,Es=we[0],Ws=we[1],ls=we[2];return ae[0]=(1-(Lt+hs))*Es,ae[1]=(Et+Rs)*Es,ae[2]=(Ot-Ts)*Es,ae[3]=0,ae[4]=(Et-Rs)*Ws,ae[5]=(1-(Bt+hs))*Ws,ae[6]=(Pt+bs)*Ws,ae[7]=0,ae[8]=(Ot+Ts)*ls,ae[9]=(Pt-bs)*ls,ae[10]=(1-(Bt+Lt))*ls,ae[11]=0,ae[12]=ge[0],ae[13]=ge[1],ae[14]=ge[2],ae[15]=1,ae}([],C||[0,0,0,1],M||[0,0,0],P||[1,1,1]),se.globalMatrix=w(se.localMatrix),B!==void 0){se.meshes=f[B];const ae=se.anchor=[0,0];for(const me of se.meshes){const{min:ge,max:we}=me.aabb;ae[0]+=ge[0]+we[0],ae[1]+=ge[1]+we[1]}ae[0]=Math.floor(ae[0]/se.meshes.length/2),ae[1]=Math.floor(ae[1]/se.meshes.length/2)}if(U&&(U.id&&(se.id=U.id),U.lights&&(se.lights=function(ae){if(!ae.length)return[];const me=function(Qe){const Ve=atob(Qe),at=new Uint8Array(Ve.length);for(let ut=0;ut1&&_[_.length-1].equals(_[0])&&_.pop();let C=0;for(let P=0;P<_.length;P++){const B=_[P],U=_[(P+1)%_.length],W=_[(P+2)%_.length];C+=(B.x-U.x)*(W.y-U.y)-(W.x-U.x)*(B.y-U.y)}C>0&&_.reverse();const M=pT(_.flatMap(P=>[P.x,P.y]),[]);return M.length===0?null:{vertices:_,indices:M}}function U0t(g,u){const f=[],_=[];let C=0;const M=[];for(const P of g){C=f.length;const B=P.vertexArray.float32,U=P.indexArray.uint16;for(let W=0;W0&&([_[P+1],_[P+2]]=[_[P+2],_[P+1]])}return{vertices:f,indices:_}}function yye(g){const u=function(U,W){const ee=[],se=WebGL2RenderingContext;if(U.json.textures)for(const ae of U.json.textures){const me={magFilter:se.LINEAR,minFilter:se.NEAREST,wrapS:se.REPEAT,wrapT:se.REPEAT};ae.sampler!==void 0&&Object.assign(me,U.json.samplers[ae.sampler]),ee.push({image:W[ae.source],sampler:me,uploaded:!1})}return ee}(g,g.images),f=function(U,W){const ee=[];for(const se of U.json.meshes){const ae=[];for(const me of se.primitives)ae.push(B0t(me,U,W));ee.push(ae)}return ee}(g,u),{scenes:_,scene:C,nodes:M}=g.json,P=_?_[C||0].nodes:[...M.keys()],B=[];for(const U of P)B.push(uIe(M[U],g,f));return function(U,W,ee){const se={},ae=new Set;for(let me=0;me0){const me=Array.from(ae.values()).sort((ge,we)=>ge-we);for(let ge=me.length-1;ge>=0;ge--)U.splice(me[ge],1)}}(B,P,g.json.nodes),B}function q0t(g){g.heightmap=new Float32Array(4096),g.heightmap.fill(-1);const u=g.vertexArray.float32,f=g.aabb.min[0]-1,_=g.aabb.min[1]-1,C=dN/(g.aabb.max[0]-f+2),M=dN/(g.aabb.max[1]-_+2);for(let P=0;Pg.heightmap[W*dN+U]&&(g.heightmap[W*dN+U]=B)}}function hIe(g,u,f,_,C){f.reserve(f.length+4*g.length),_.reserve(_.length+10*g.length),C.reserve(C.length+10*g.length);let M=_.length;for(const P of g){const B=Math.min(10,Math.max(4,1.3*P.height))*u,U=[-P.normal[1],P.normal[0],0],W=Math.min(.29,.1*P.width/P.depth),ee=P.width-2*P.depth*u*(W+.01),se=Ue([],P.pos,U,ee/2),ae=Ue([],P.pos,U,-ee/2),me=[se[0],se[1],se[2]+P.height],ge=[ae[0],ae[1],ae[2]+P.height],we=Ue([],P.normal,U,W);be(we,we,B);const Ee=Ue([],P.normal,U,-W);be(Ee,Ee,B),ne(we,se,we),ne(Ee,ae,Ee),se[2]+=.1,ae[2]+=.1,_.emplaceBack(we[0],we[1],we[2]),_.emplaceBack(Ee[0],Ee[1],Ee[2]),_.emplaceBack(se[0],se[1],se[2]),_.emplaceBack(ae[0],ae[1],ae[2]),_.emplaceBack(me[0],me[1],me[2]),_.emplaceBack(ge[0],ge[1],ge[2]),_.emplaceBack(se[0],se[1],se[2]),_.emplaceBack(ae[0],ae[1],ae[2]),_.emplaceBack(we[0],we[1],we[2]),_.emplaceBack(Ee[0],Ee[1],Ee[2]);const Fe=ee/B/2;C.emplaceBack(-Fe-W,-1,Fe,.8),C.emplaceBack(Fe+W,-1,Fe,.8),C.emplaceBack(-Fe,0,Fe,1.3),C.emplaceBack(Fe,0,Fe,1.3),C.emplaceBack(Fe+W,-.8,Fe,.7),C.emplaceBack(Fe+W,-.8,Fe,.7),C.emplaceBack(0,0,Fe,1.3),C.emplaceBack(0,0,Fe,1.3),C.emplaceBack(Fe+W,-1.2,Fe,.8),C.emplaceBack(Fe+W,-1.2,Fe,.8),f.emplaceBack(6+M,4+M,8+M),f.emplaceBack(7+M,9+M,5+M),f.emplaceBack(0+M,1+M,2+M),f.emplaceBack(1+M,3+M,2+M),M+=10}}function V0t(g,u){const f={};f.indexArray=new ll,f.vertexArray=new Tf,f.colorArray=new $g,hIe(g,u,f.indexArray,f.vertexArray,f.colorArray);const _={defined:!0};_.emissiveFactor=wr.black;const C={};return C.baseColorFactor=wr.white,_.pbrMetallicRoughness=C,f.material=_,f.aabb=new fi([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),f}const mIe=Ta([{name:"a_pos_3f",components:3,type:"Float32"}]),H0t=Ta([{name:"a_normal_3",components:3,type:"Int16"}]),G0t=Ta([{name:"a_centroid_3",components:3,type:"Int16"}]),fIe=Ta([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),W0t=Ta([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),K0t=Ta([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),Y0t=Ta([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Z0t=Ta([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),X0t=Ta([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),pIe=Dn.types,A7=32767;function Q0t(g,u){const f=fr+u;for(const _ of g)for(const C of _)if(C.x<-u||C.x>f||C.y<-u||C.y>f)return!1;return!0}function J0t(g){switch(g){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: ${g}`)}}class vye{constructor(){this.layoutVertexArray=new Tf,this.layoutAttenuationArray=new $g,this.layoutColorArray=new Ef,this.indexArray=new ll,this.indexArrayForConflation=new ll,this.segmentsBucket=new Bi}}class bye{constructor(u){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Bi,this.entranceBloom=new vye;const f=66560;this.layoutVertexArray=new Tf,this.layoutVertexArray.reserve(f),this.layoutNormalArray=new jx,this.layoutNormalArray.reserve(f),this.layoutCentroidArray=new jx,this.layoutCentroidArray.reserve(f),this.layoutColorArray=new Ef,this.layoutColorArray.reserve(f),this.layoutFloodLightDataArray=new cT,this.layoutFloodLightDataArray.reserve(f),this.layoutAOArray=new dT,this.layoutAOArray.reserve(f),this.indexArray=new ll,this.indexArray.reserve(66560),this.indexArrayForConflation=new ll,this.segmentsBucket=new Bi,this.entranceBloom=new vye,u&&(this.layoutFacadePaintArray=new Ef,this.layoutFacadeDataArray=new v_,this.layoutFacadeVerticalRangeArray=new Ef)}reserve(u,f,_){this.layoutVertexArray.reserveForAdditional(u),this.layoutCentroidArray.reserveForAdditional(u),this.layoutFloodLightDataArray.reserveForAdditional(u),this.layoutNormalArray.reserveForAdditional(u),this.layoutAOArray.reserveForAdditional(u),this.layoutColorArray.reserveForAdditional(u),this.indexArray.reserveForAdditional(f),_&&(this.layoutFacadePaintArray.reserveForAdditional(u),this.layoutFacadeDataArray.reserveForAdditional(u),this.layoutFacadeVerticalRangeArray.reserveForAdditional(u))}}class xIe{constructor(u){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new f1,this.footprintsIndices=new p1,this.footprintsMin=new ss(1/0,1/0),this.footprintsMax=new ss(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new bye(!1),this.buildingWithFacade=new bye(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=u.zoom,this.canonical=u.canonical,this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.index=u.index,this.hasPattern=!1,this.worldview=u.worldview,this.lut=u.lut,this.programConfigurations=new Me(u.layers,{zoom:u.zoom,lut:u.lut}),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.projection=u.projection,this.groundEffect=new iye(u),this.groundEffect.groundRadiusArray=new Bm,this.hasAppearances=null}updateFootprints(u,f){const _=new m7([],[],1),C={vertices:[],indices:new Uint32Array(0),grid:_,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};f.push({footprint:C,id:u})}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(w7!=null||GMe!=null)return null;if(vT!=null)return vT;const u=fetch(Ci());return vT=function(f){let _,C,M,P,B;function U(){_=new Uint8Array(B.buffer),C=new Int16Array(B.buffer),M=new Int32Array(B.buffer),P=new Float32Array(B.buffer)}function W(){throw new Error("Unexpected BuildingGen error.")}const ee=()=>{},se={a:{a:W,f:function(ae){const me=_.length,ge=Math.max(ae>>>0,Math.ceil(1.2*me)),we=Math.ceil((ge-me)/65536);try{return B.grow(we),U(),!0}catch{return!1}},g:W,b:ee,c:ee,d:ee,e:ee}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(f,se):f.then(ae=>ae.arrayBuffer()).then(ae=>WebAssembly.instantiate(ae,se))).then(ae=>{const me=ae.instance.exports;return(0,me.g)(),B=me.f,U(),new j0t({setStyle:me.h,setAOOptions:me.i,setMetricOptions:me.j,setStructuralOptions:me.k,setFacadeOptions:me.l,setFauxFacadeOptions:me.m,setFacadeClassifierOptions:me.n,addFeature:me.o,addFacade:me.p,generateMesh:me.q,getLastError:me.r,getOuterRingLength:me.s,getMeshCount:me.t,getPositionsPtr:me.u,getPositionsLength:me.v,getNormalsPtr:me.w,getNormalsLength:me.x,getAOPtr:me.y,getAOLength:me.z,getUVPtr:me.A,getUVLength:me.B,getFauxFacadePtr:me.C,getFauxFacadeLength:me.D,getIndicesPtr:me.E,getIndicesLength:me.F,getBuildingPart:me.G,getRingCount:me.H,getRingPtr:me.I,getRingLength:me.J,malloc:me.K,free:me.L,heapU8:_,heap16:C,heap32:M,heapF32:P})})}(u).then(f=>(vT=null,w7=f,w7)).catch(f=>{Rr("Could not load building-gen"),vT=null,GMe=f instanceof Error?f:new Error("Unknown error")}),vT}()}populate(u,f,_,C){const M=N0t();if(!M)return;const P=Us(_);this.tileToMeter=P,this.brightness=f.brightness,M.setStyle({normalScale:[1,-1,P],tileToMeters:P}),M.setAOOptions(!1,.3),M.setMetricOptions(!1,16),M.setStructuralOptions(!0),M.setFacadeClassifierOptions(3);const B=new Map,U=new Map;let W=0;for(const{feature:Fe}of u){if(pIe[Fe.type]!=="LineString"){B.set(Fe.id,Fe.properties.source_id);continue}const Qe=this.layers[0]._featureFilter.needGeometry;if(Qe&&!this.layers[0]._featureFilter.filter(new ui(this.zoom),Fe,_))continue;const Ve=la(Fe,Qe);if(!Qe&&!this.layers[0]._featureFilter.filter(new ui(this.zoom),Ve,_))continue;const at=Qe?Ve.geometry:pn(Fe,_,C),ut=[];for(const Ot of at)for(const Lt of Ot)ut.push(Lt.x),ut.push(Lt.y);const ft={coordinates:ut,crossPerc:Fe.properties.cross_perc,distanceToRoad:Fe.properties.distance_to_road,entrances:Fe.properties.entrances,sourceId:0},Bt=Fe.properties.source_id;let Et=U.get(Bt);Et||(Et=[],U.set(Bt,Et)),Et.push(ft),++W}this.maxHeight=0;const ee=new Array,se=new Set,ae=Fe=>{Fe!=null&&se.add(Fe)},me=(Fe,Qe)=>{Fe!=null&&ee.push({buildingId:Fe,footprintIndex:Qe})},ge=64*(u.length-W),we=ge/2;this.buildingWithFacade.reserve(ge,we,!0),this.buildingWithoutFacade.reserve(2*ge,2*we,!1),this.footprintsIndices.reserve(16*(u.length-W)),this.footprintsVertices.reserve(8*(u.length-W));for(const{feature:Fe,id:Qe,index:Ve,sourceLayerIndex:at}of u){if(pIe[Fe.type]==="LineString")continue;const ut=this.layers[0]._featureFilter.needGeometry;if(ut&&!this.layers[0]._featureFilter.filter(new ui(this.zoom),Fe,_))continue;let ft=null;if(Fe.properties&&Fe.properties.hasOwnProperty("building_id")&&(ft=Number(Fe.properties.building_id),se.has(ft)))continue;const Bt=la(Fe,ut);if(!ut&&!this.layers[0]._featureFilter.filter(new ui(this.zoom),Bt,_))continue;const Et=ut?Bt.geometry:pn(Fe,_,C),Ot=t6(Et,500);let Lt=!1;for(const ga of Ot)if(ga.length!==1){Lt=!0;break}if(Lt){ae(ft);continue}if(!Q0t(Et,163)){ae(ft);continue}const Pt=this.layers[0],hs=J0t(Pt.layout.get("building-roof-shape").evaluate(Fe,{},_)),bs=Pt.layout.get("building-base").evaluate(Fe,{},_),Ts=Pt.layout.get("building-height").evaluate(Fe,{},_),Rs=Pt.layout.get("building-flood-light-ground-radius").evaluate(Fe,{},_),Es=Pt.paint.get("building-ambient-occlusion-intensity"),Ws=Rs/this.tileToMeter;Fe.properties["building-part"]="roof";const ls=Pt.paint.get("building-color").evaluate(Fe,{},this.canonical).toPremultipliedRenderColor(this.lut),Ps=Pt.paint.get("building-emissive-strength").evaluate(Fe,{},this.canonical);Fe.properties["building-part"]="wall";const zs=Pt.paint.get("building-color").evaluate(Fe,{},this.canonical).toPremultipliedRenderColor(this.lut),Ks=Pt.paint.get("building-emissive-strength").evaluate(Fe,{},this.canonical);Fe.properties["building-part"]="window";const tr=Pt.paint.get("building-color").evaluate(Fe,{},this.canonical).toPremultipliedRenderColor(this.lut),Ar=Pt.paint.get("building-emissive-strength").evaluate(Fe,{},this.canonical);Fe.properties["building-part"]="door";const ur=Pt.paint.get("building-color").evaluate(Fe,{},this.canonical).toPremultipliedRenderColor(this.lut),dr=Pt.paint.get("building-emissive-strength").evaluate(Fe,{},this.canonical);let sr=Pt.layout.get("building-flood-light-wall-radius").evaluate(Fe,{},_);sr=ze(sr,0,2048);const Tr=sr/2048*A7,zr=B.get(Qe),mn=U.get(zr)||[],Gr=mn.length!==0&&Pt.layout.get("building-facade").evaluate(Fe,{},_);M.setFacadeOptions(4,!0),M.setFauxFacadeOptions(Gr,!1,1);let Vn=0,$a=0,Hn=0,Va=0,ca=0,Ho=0,hi=0,Za=0,Ui=0,Io=0,Lc=0;if(Gr){let ga=Math.round(Pt.layout.get("building-facade-floors").evaluate(Fe,{},_));if(bs===0){ga=Math.max(1,ga-(mn.length>0?1:0));let ul=4;if(Ts>100){const yc=[10,13,15];ul=yc[Fe.id?Fe.id%yc.length:0]}else Ts<=10&&(ul=3);M.setFacadeOptions(ul,!0),ca=(Ts<15?1.3:1.61803)*ul/P}else ca=bs/P;Ho=Ts/P,ca=Math.min(ca,Ho),Hn=Pt.layout.get("building-facade-unit-width").evaluate(Fe,{},_)/P,Va=(Ho-ca)/ga,M.setFauxFacadeOptions(!0,!0,Hn);const Jc=Pt.layout.get("building-facade-window").evaluate(Fe,{},_);Vn=Jc[0],$a=Jc[1],hi=Math.floor(65535*Math.min(1,ca/fr)),Za=Math.floor(65535*Math.min(1,Ho/fr)),Ui=Math.floor(255*Vn)<<8|Math.floor(255*$a),Io=Math.floor(65535*Math.min(1,Hn/fr)),Lc=Math.floor(65535*Math.min(1,Va/fr))}const Lo=Array(Ot.length),cl={x:1/0,y:1/0},Pl={x:-1/0,y:-1/0},dl={x:0,y:0};let qd=0;for(let ga=0;ga0){const ul=[],yc=Array(Jc.length+1);yc[0]=0;for(let gp=0;gpfr||cl.y<0||Pl.y>fr)&&this.featuresOnBorder.push({featureId:Fe.id,footprintIndex:this.footprints.length});{const ga=pT(k1,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+ga.length),this.footprintsIndices.uint16.set(ga,LT),this.buildingIds.add(ft??Fe.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,pp.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,pp.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,xp.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,xp.y);const Jc={footprintVertexOffset:N1,footprintVertexLength:this.footprintsVertices.length-N1,footprintIndexOffset:LT,footprintIndexLength:this.footprintsIndices.length-LT,min:pp,max:xp,hiddenFlags:0,indicesOffset:a9,indicesLength:d0e,bloomIndicesOffset:Vd,bloomIndicesLength:Go,groundEffectVertexOffset:yN,groundEffectVertexLength:PT,hasFauxFacade:Gr,height:IT,promoteId:Qe,feature:Bt,parts:Xc,buildingBloom:ih},ul=this.footprints.length;Fe.id!==void 0&&this.featureFootprintLookup.set(Fe.id,ul),me(ft,ul),this.footprints.push(Jc)}this.programConfigurations.populatePaintArrays(ha.layoutVertexArray.length,Fe,Ve,{},f.availableImages,_,f.brightness),this.groundEffect.addPaintPropertiesData(Fe,Ve,{},f.availableImages,_,f.brightness),f.featureIndex.insert(Fe,Et,Ve,at,this.index,Eu)}ee.forEach(({buildingId:Fe,footprintIndex:Qe})=>{se.has(Fe)&&(this.footprints[Qe].hiddenFlags|=4)});const Ee=new Set;this.buildingIds.forEach((Fe,Qe,Ve)=>{se.has(Fe)||Ee.add(Fe)}),this.buildingIds=Ee,this.groundEffect.prepareBorderSegments()}update(u,f,_,C,M,P,B){this.programConfigurations.updatePaintArrays(u,f,M,_,C,P,B),this.groundEffect.update(u,f,M,_,C,P,B),this.evaluate(this.layers[0],u),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(u){const f=_=>{_.layoutVertexBuffer=u.createVertexBuffer(_.layoutVertexArray,mIe.members),_.layoutNormalBuffer=u.createVertexBuffer(_.layoutNormalArray,H0t.members),_.layoutCentroidBuffer=u.createVertexBuffer(_.layoutCentroidArray,G0t.members),_.layoutFloodLightDataBuffer=u.createVertexBuffer(_.layoutFloodLightDataArray,X0t.members),_.layoutFacadeDataArray&&_.layoutFacadeDataArray.length&&(_.layoutFacadeDataBuffer=u.createVertexBuffer(_.layoutFacadeDataArray,K0t.members)),_.layoutFacadeVerticalRangeArray&&_.layoutFacadeVerticalRangeArray.length&&(_.layoutFacadeVerticalRangeBuffer=u.createVertexBuffer(_.layoutFacadeVerticalRangeArray,Y0t.members)),_.entranceBloom.layoutVertexArray.length&&(_.entranceBloom.layoutVertexBuffer=u.createVertexBuffer(_.entranceBloom.layoutVertexArray,mIe.members),_.entranceBloom.layoutAttenuationBuffer=u.createVertexBuffer(_.entranceBloom.layoutAttenuationArray,Z0t.members)),this.uploadUpdatedColorBuffer(u),this.uploadUpdatedIndexBuffer(u)};this.uploaded||(f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.groundEffect.upload(u)),this.groundEffect.uploadPaintProperties(u),this.programConfigurations.upload(u),this.uploaded=!0}destroy(){const u=f=>{f.layoutVertexBuffer&&(f.layoutVertexBuffer.destroy(),f.layoutNormalBuffer.destroy(),f.layoutColorBuffer.destroy(),f.segmentsBucket.destroy(),f.indexBuffer&&f.indexBuffer.destroy(),f.entranceBloom.layoutVertexBuffer&&(f.entranceBloom.layoutVertexBuffer.destroy(),f.entranceBloom.layoutColorBuffer.destroy(),f.entranceBloom.layoutAttenuationBuffer.destroy(),f.entranceBloom.indexBuffer.destroy(),f.entranceBloom.segmentsBucket.destroy()))};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(u,f,_=!0){let C=!1;const M=_?f:0,P=0|(_?-1:~f);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const B of u){const U=this.footprints[B],W=U.hiddenFlags&P|M;U.hiddenFlags!==W&&(U.hiddenFlags=W,C=!0,this.groundEffect.updateHiddenByLandmarkRange(U.groundEffectVertexOffset,U.groundEffectVertexLength,U.hiddenFlags!==0))}return C&&(this.indexArrayForConflationUploaded=!1),C}uploadUpdatedIndexBuffer(u){if(this.groundEffect.uploadHiddenByLandmark(u),this.indexArrayForConflationUploaded)return;const f=C=>{C.indexArray.length!==0&&(C.indexArrayForConflation.resize(C.indexArray.length),C.indexArrayForConflation.uint16.set(C.indexArray.uint16),C.entranceBloom.indexArrayForConflation.resize(C.entranceBloom.indexArray.length),C.entranceBloom.indexArrayForConflation.uint16.set(C.entranceBloom.indexArray.uint16))};f(this.buildingWithoutFacade),f(this.buildingWithFacade);for(const C of this.footprints){const M=C.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,P=C.indicesOffset+C.indicesLength;if(C.hiddenFlags!==0){for(let U=C.indicesOffset;U{C.indexArray.length!==0&&(C.indexBuffer?C.indexBuffer.updateData(C.indexArrayForConflation):C.indexBuffer=u.createIndexBuffer(C.indexArrayForConflation,!0),C.entranceBloom.indexBuffer?C.entranceBloom.indexBuffer.updateData(C.entranceBloom.indexArrayForConflation):C.entranceBloom.indexBuffer=u.createIndexBuffer(C.entranceBloom.indexArrayForConflation,!0))};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(u){const f=_=>{_.layoutColorBuffer?_.layoutColorBuffer.updateData(_.layoutColorArray):_.layoutColorBuffer=u.createVertexBuffer(_.layoutColorArray,fIe.members,!0),_.layoutFacadePaintArray&&(_.layoutFacadePaintBuffer?_.layoutFacadePaintBuffer.updateData(_.layoutFacadePaintArray):_.layoutFacadePaintBuffer=u.createVertexBuffer(_.layoutFacadePaintArray,W0t.members,!0)),_.entranceBloom.layoutColorBuffer?_.entranceBloom.layoutColorBuffer.updateData(_.entranceBloom.layoutColorArray):_.entranceBloom.layoutColorBuffer=u.createVertexBuffer(_.entranceBloom.layoutColorArray,fIe.members,!0)};f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(u,f){const _=u.paint.get("building-ambient-occlusion-intensity");for(const C of this.footprints){if(4&C.hiddenFlags)continue;const M=f[C.promoteId],P=C.feature;P.properties["building-part"]="roof";const B=u.paint.get("building-color").evaluate(P,M,this.canonical).toPremultipliedRenderColor(this.lut),U=u.paint.get("building-emissive-strength").evaluate(P,M,this.canonical);P.properties["building-part"]="wall";const W=u.paint.get("building-color").evaluate(P,M,this.canonical).toPremultipliedRenderColor(this.lut),ee=u.paint.get("building-emissive-strength").evaluate(P,M,this.canonical);P.properties["building-part"]="window";const se=u.paint.get("building-color").evaluate(P,M,this.canonical).toPremultipliedRenderColor(this.lut),ae=u.paint.get("building-emissive-strength").evaluate(P,M,this.canonical);P.properties["building-part"]="door";const me=u.paint.get("building-color").evaluate(P,M,this.canonical).toPremultipliedRenderColor(this.lut),ge=u.paint.get("building-emissive-strength").evaluate(P,M,this.canonical),we=C.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const Fe of C.parts){let Qe,Ve=B;Fe.part===1?(Ve=B,Qe=U):Fe.part===0?(Ve=W,Qe=ee):Fe.part===2?(Ve=se,Qe=ae):Fe.part===3&&(Ve=me,Qe=ge),Qe=ze(Qe,0,1);for(let at=0;atP.max.x||U.max.xP.max.y||U.max.yB.max.x||B.min.x>u||f>B.max.y||B.min.y>f||B.height<=_||evt(P,this.footprintsVertices.float32.subarray(2*B.footprintVertexOffset,2*(B.footprintVertexOffset+B.footprintVertexLength)),this.footprintsIndices.uint16.subarray(B.footprintIndexOffset,B.footprintIndexOffset+B.footprintIndexLength))&&(_=B.height,this.footprintLookup[M]=B,C=B.hiddenFlags!==0);if(_!==Number.NEGATIVE_INFINITY)return{height:_,hidden:C};this.footprintLookup[M]=void 0}}function evt(g,u,f){for(let _=0;_1&&(U=u[++B]);const ee=Math.abs(W-U.left),se=Math.abs(W-U.right),ae=Math.min(ee,se);let me;const ge=M/_*(C+1);if(U.isDash){const we=C-Math.abs(ge);me=Math.sqrt(ae*ae+we*we)}else me=C-Math.sqrt(ae*ae+ge*ge);this.image.data[P+W]=Math.max(0,Math.min(255,me+128))}}}addRegularDash(u,f){for(let U=u.length-1;U>=0;--U){const W=u[U],ee=u[U+1];W.zeroLength?u.splice(U,1):ee&&ee.isDash===W.isDash&&(ee.left=W.left,u.splice(U,1))}const _=u[0],C=u[u.length-1];_.isDash===C.isDash&&(_.left=C.left-this.width,C.right=_.right+this.width);const M=this.width*this.nextRow;let P=0,B=u[P];for(let U=0;U1&&(B=u[++P]);const W=Math.abs(U-B.left),ee=Math.abs(U-B.right),se=Math.min(W,ee);this.image.data[M+U]=Math.max(0,Math.min(255,(B.isDash?se:-se)+f+128))}}addDash(u,f){const _=this.getKey(u,f);if(this.positions[_])return this.positions[_];const C=f==="round",M=C?7:0,P=2*M+1;if(this.nextRow+P>this.height)return Rr("LineAtlas out of space"),null;u.length===0&&u.push(1);let B=0;for(let se=0;sef.fqid),this.index=u.index,this.projection=u.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(f=>{this.gradients[f.id]={}}),this.layoutVertexArray=new Z2,this.layoutVertexArray2=new Tf,this.patternVertexArray=new Tf,this.indexArray=new ll,this.programConfigurations=new Me(u.layers,{zoom:u.zoom,lut:u.lut}),this.segments=new Bi,this.maxLineLength=0,this.zOffsetVertexArray=new Tf,this.elevationGroundScaleVertexArray=new Bm,this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.id),this.tessellationStep=u.tessellationStep?u.tessellationStep:128,this.worldview=u.worldview,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,_,C){this.hasPattern=qge("line",this.layers,this.pixelRatio,f);const M=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Us(_);const P=this.layers[0].layout.get("line-elevation-reference");if(P==="hd-road-markup")this.elevationType="road";else{const ae=this.layers[0].layout.get("line-z-offset"),me=ae.isConstant()&&!ae.constantOr(0);this.elevationType=P!=="sea"&&P!=="ground"&&me?"none":"offset",this.elevationType==="offset"&&P==="none"&&Rr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=P==="sea"}const B=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&B!==void 0;const U=[];for(const{feature:ae,id:me,index:ge,sourceLayerIndex:we}of u){const Ee=this.layers[0]._featureFilter.needGeometry,Fe=la(ae,Ee);if(!this.layers[0]._featureFilter.filter(new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),Fe,_))continue;const Qe=M?M.evaluate(Fe,{},_):void 0,Ve={id:me,properties:ae.properties,type:ae.type,sourceLayerIndex:we,index:ge,geometry:Ee?Fe.geometry:pn(ae,_,C),patterns:{},sortKey:Qe};U.push(Ve)}M&&U.sort((ae,me)=>ae.sortKey-me.sortKey);const{lineAtlas:W,featureIndex:ee}=f,se=this.addConstantDashes(W);for(const ae of U){const{geometry:me,index:ge,sourceLayerIndex:we}=ae;if(se&&this.addFeatureDashes(ae,W),this.hasPattern){const Ee=Vge("line",this.layers,ae,this.zoom,this.pixelRatio,f);this.patternFeatures.push(Ee)}else this.addFeature(ae,me,ge,_,W.positions,f.availableImages,f.brightness,f.elevationFeatures);ee.insert(u[ge].feature,me,ge,we,this.index)}}addConstantDashes(u){let f=!1;for(const _ of this.layers){const C=_.paint.get("line-dasharray").value,M=_.layout.get("line-cap").value;if(C.kind!=="constant"||M.kind!=="constant")f=!0;else{const P=M.value,B=C.value;if(!B)continue;u.addDash(B,P)}}return f}addFeatureDashes(u,f){const _=this.zoom;for(const C of this.layers){const M=C.paint.get("line-dasharray").value,P=C.layout.get("line-cap").value;if(M.kind==="constant"&&P.kind==="constant")continue;let B,U;if(M.kind==="constant"){if(B=M.value,!B)continue}else B=M.evaluate({zoom:_},u);U=P.kind==="constant"?P.value:P.evaluate({zoom:_},u),f.addDash(B,U),u.patterns[C.id]=[f.getKey(B,U)]}}update(u,f,_,C,M,P,B,U,W){this.programConfigurations.updatePaintArrays(u,f,M,_,C,P,B,W)}addFeatures(u,f,_,C,M,P){for(const B of this.patternFeatures)this.addFeature(B,B.geometry,B.index,f,_,C,P,u.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(u){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=u.createVertexBuffer(this.layoutVertexArray2,ovt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=u.createVertexBuffer(this.patternVertexArray,cvt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=u.createVertexBuffer(this.zOffsetVertexArray,rvt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=u.createVertexBuffer(this.elevationGroundScaleVertexArray,nvt.members,!0)),this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,avt),this.indexBuffer=u.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(u),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(u,f){let _,C;if(f&&f>0?(_=`mapbox_clip_start_${f}`,C=`mapbox_clip_end_${f}`):(_="mapbox_clip_start",C="mapbox_clip_end"),u.properties&&u.properties.hasOwnProperty(_)&&u.properties.hasOwnProperty(C))return{start:+u.properties[_],end:+u.properties[C]}}addFeature(u,f,_,C,M,P,B,U){const W=this.layers[0].layout,ee=W.get("line-join").evaluate(u,{}),se=W.get("line-cap").evaluate(u,{}),ae=W.get("line-miter-limit"),me=W.get("line-round-limit");this.lineClips=this.lineFeatureClips(u),this.lineFeature=u;const ge=!(!u.properties||!u.properties.hasOwnProperty("mapbox_line_metrics"))&&u.properties.mapbox_line_metrics;this.zOffsetValue=W.get("line-z-offset").value;const we=this.layers[0].paint.get("line-width").value;if(we.kind!=="constant"&&we.isLineProgressConstant===!1&&(this.variableWidthValue=we),this.isSeaLevelReference){const Ee=W.get("line-elevation-ground-scale").value;Ee.kind==="constant"&&Ee.value===0||(this.elevationGroundScaleValue=Ee)}if(this.elevationType==="road"){const Ee=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(u,f,C,U,ee,se,ae,me)){const[Fe,Qe]=this.clipRuntimeLinesToTile(f,1);for(let Ve=0;Ve0?ut.parentIndex:null)}this.fillNonElevatedRoadSegment(Ee)}}else for(let Ee=0;Ee0?Ee:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,u,_,M,P,C,B,void 0,this.worldview)}computeSegNextDir(u,f){return u.nextPoint.sub(f.at(-2)).unit()}computeSegPrevDir(u,f){return f[1].sub(u.prevPoint).unit()}clipLinesToTile(u,f){return _7(u,-f,-f,fr+f,fr+f)}clipRuntimeLinesToTile(u,f){const _=[];return[_7(u,-f,-f,fr+f,fr+f,_),_]}addElevatedRoadFeature(u,f,_,C,M,P,B,U){const W=[],ee=qi.getElevationFeature(u,C);if(ee){const se=this.clipLinesToTile(f,1),ae=this.prepareElevatedLines(se,ee,_);for(const me of ae)W.push({geometry:me,elevation:ee,elevationTileID:_,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(W.length===0)return!1;for(const se of W){const ae=this.layoutVertexArray.length;this.addLine(se.geometry,u,_,M,P,B,U);const me=new Yi(_,se.elevationTileID);if(se.elevation)for(let ge=ae;ge>1,this.layoutVertexArray.int16[6*ge+1]>>1),Ee=me.pointElevation(we,se.elevation,.05);this.updateHeightRange(Ee),this.zOffsetVertexArray.emplaceBack(Ee,0,0)}else this.fillNonElevatedRoadSegment(ae)}return!0}prepareElevatedLines(u,f,_){if(f.constantHeight!=null)return u;const C=[],M=1/Us(_);for(const P of u)w0t(P,new $m(f,M),0,C);return C}fillNonElevatedRoadSegment(u){for(let f=u;f0,ae=U&&U.progress.max<1;if(this.lineClips){let Ot={min:this.lineClips.start,max:this.lineClips.end},Lt=1;if(U){const bs=this.lineClips.end-this.lineClips.start;Ot=function(Ts,Rs,Es){return{min:no(Ts.min,Rs,Es),max:no(Ts.max,Rs,Es)}}(U.progress,{min:0,max:1},Ot),bs>0&&(Lt=(Ot.max-Ot.min)/bs)}const Pt=+f.properties.mapbox_clip_feature_len,hs=+f.properties.mapbox_clip_seg_len;if(Number.isNaN(Pt)||Number.isNaN(hs)){for(let Ts=0;Ts=2&&u[ge-1].equals(u[ge-2]);)ge--;let we=0;for(;we0,Ps=this.overscaling<=16?122880/(512*this.overscaling):0;if(Lt&&Pt==="round"){if(RsP&&(Pt="bevel"),Pt==="bevel"&&(Rs>2&&(Pt="flipbevel"),Rs2*Ps){const tr=Fe.sub(Fe.sub(Qe)._mult(Ps/zs)._round());this.updateDistance(Qe,tr),this.addCurrentVertex(tr,at,0,0,Ee,Et),Qe=tr}this.updateDistance(Qe,Fe),bs._mult(Rs),this.addCurrentVertex(Fe,bs,0,0,Ee,Et);const Ks=Fe.dist(Ve);if(Ks>2*Ps){const tr=Fe.add(Ve.sub(Fe)._mult(Ps/Ks)._round());this.updateDistance(Fe,tr),this.addCurrentVertex(tr,ut,0,0,Ee,Et),Fe=tr}}else bs._mult(Rs),this.addCurrentVertex(Fe,bs,0,0,Ee,Et);else if(Pt==="flipbevel"){if(Rs>100)bs=ut.mult(-1);else{const zs=Rs*at.add(ut).mag()/at.sub(ut).mag();bs._perp()._mult(zs*(ls?-1:1))}this.addCurrentVertex(Fe,bs,0,0,Ee,Et),this.addCurrentVertex(Fe,bs.mult(-1),0,0,Ee,Et)}else if(Pt==="bevel"||Pt==="fakeround"){const zs=Fe.dist(Qe);let Ks=1;if(this.elevationType==="offset"&&Pt==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Et!=null&&Qe&&Ve){const Tr=4*Ps;zs1){this.lineSoFar=u.w;const we=(f.x-u.x)/se,Ee=(f.y-u.y)/se,Fe=(f.z-u.z)/se,Qe=(f.w-u.w)/se,Ve=f.x-u.x,at=f.y-u.y,ut=Math.sqrt(Ve*Ve+at*at);if(ut===0)return;const ft=-at/ut,Bt=Ve/ut,Et=ft,Ot=Bt,Lt=-ft,Pt=-Bt;for(let hs=1;hs=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,ee),U.primitiveLength++),P?this.e2=ee:this.e1=ee,W!=null&&this.zOffsetVertexArray.emplaceBack(W.zOffset,W.variableWidth,W.variableWidth),this.elevationGroundScaleValue){const se=W?W.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(se)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(u,f){this.prevDistance=this.distance,this.distance+=u.dist(f),this.updateScaledDistance()}}function _ye(g,u,f){return g.xf||g.yf}let bIe,_Ie;function wIe(g,u,f){return u*(fr/(g.tileSize*Math.pow(2,f-g.tileID.overscaledZ)))}Dr(M7,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const jIe=(g,u,f)=>(1-f)*g+f*u;function NIe(g,u){return 1/wIe(g,1,u.tileZoom)}function kIe(g,u,f,_){return g.translatePosMatrix(_||u.tileID.projMatrix,u,f.paint.get("line-translate"),f.paint.get("line-translate-anchor"))}const SIe=g=>{const u=[];CIe(g)&&u.push("RENDER_LINE_DASH"),g.paint.get("line-gradient")&&u.push("RENDER_LINE_GRADIENT"),g.paint.get("line-blend-mode")==="multiply"&&u.push("LINE_BLEND_MULTIPLY");const f=g.paint.get("line-trim-offset");f[0]===0&&f[1]===0||u.push("RENDER_LINE_TRIM_OFFSET"),g.paint.get("line-border-width").constantOr(1)!==0&&u.push("RENDER_LINE_BORDER");const _=g.layout.get("line-join").constantOr("miter")==="none",C=!!g.paint.get("line-pattern").constantOr(1);return _&&C&&u.push("LINE_JOIN_NONE"),u};function CIe(g){const u=g.paint.get("line-dasharray").value;return u.kind!=="constant"||u.value}let wye;const TIe=()=>wye||(wye={layout:bIe||(bIe=new jo({"line-cap":new Qs(Yt.layout_line["line-cap"]),"line-join":new Qs(Yt.layout_line["line-join"]),"line-miter-limit":new nr(Yt.layout_line["line-miter-limit"]),"line-round-limit":new nr(Yt.layout_line["line-round-limit"]),"line-sort-key":new Qs(Yt.layout_line["line-sort-key"]),"line-z-offset":new Qs(Yt.layout_line["line-z-offset"]),"line-elevation-reference":new nr(Yt.layout_line["line-elevation-reference"]),"line-cross-slope":new nr(Yt.layout_line["line-cross-slope"]),visibility:new nr(Yt.layout_line.visibility),"line-width-unit":new nr(Yt.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Qs(Yt.layout_line["line-elevation-ground-scale"])})),paint:_Ie||(_Ie=new jo({"line-opacity":new Qs(Yt.paint_line["line-opacity"]),"line-color":new Qs(Yt.paint_line["line-color"]),"line-translate":new nr(Yt.paint_line["line-translate"]),"line-translate-anchor":new nr(Yt.paint_line["line-translate-anchor"]),"line-width":new Qs(Yt.paint_line["line-width"]),"line-gap-width":new Qs(Yt.paint_line["line-gap-width"]),"line-offset":new Qs(Yt.paint_line["line-offset"]),"line-blur":new Qs(Yt.paint_line["line-blur"]),"line-dasharray":new Qs(Yt.paint_line["line-dasharray"]),"line-pattern":new Qs(Yt.paint_line["line-pattern"]),"line-pattern-cross-fade":new nr(Yt.paint_line["line-pattern-cross-fade"]),"line-gradient":new g_(Yt.paint_line["line-gradient"]),"line-trim-offset":new nr(Yt.paint_line["line-trim-offset"]),"line-trim-fade-range":new nr(Yt.paint_line["line-trim-fade-range"]),"line-trim-color":new nr(Yt.paint_line["line-trim-color"]),"line-emissive-strength":new Qs(Yt.paint_line["line-emissive-strength"]),"line-border-width":new Qs(Yt.paint_line["line-border-width"]),"line-border-color":new Qs(Yt.paint_line["line-border-color"]),"line-occlusion-opacity":new nr(Yt.paint_line["line-occlusion-opacity"]),"line-blend-mode":new nr(Yt.paint_line["line-blend-mode"]),"line-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"})}))},wye);class mvt extends Qs{possiblyEvaluate(u,f){return f=new ui(Math.floor(f.zoom),{now:f.now,fadeDuration:f.fadeDuration,transition:f.transition,worldview:f.worldview}),super.possiblyEvaluate(u,f)}evaluate(u,f,_,C){return f=Object.assign({},f,{zoom:Math.floor(f.zoom)}),super.evaluate(u,f,_,C)}}let m6;function EIe(g,u){return u>0?u+2*g:g}const fvt=Ta([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),pvt=Ta([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),xvt=Ta([{name:"a_projected_pos",components:4,type:"Float32"}],4);Ta([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const gvt=Ta([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),yvt=Ta([{name:"a_feature_index",components:1,type:"Float32"}],4),vvt=Ta([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),bvt=Ta([{name:"a_texb",components:2,type:"Uint16"}]),_vt=Ta([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),wvt=Ta([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Ta([{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 AIe=Ta([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),jvt=Ta([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Ta([{name:"triangle",components:3,type:"Uint16"}]),Ta([{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"}]),Ta([{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"}]),Ta([{type:"Float32",name:"offsetX"}]),Ta([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const jye=class rce{constructor(u=null,f=0,_=4096){this.batchIndex=f,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=u||null,this.propsDwords=_,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(rce.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let C=0;Cu.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${u.maxUniformBlockSize}`);if(this.headerBuffer=f.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(f.bindBuffer(f.UNIFORM_BUFFER,this.headerBuffer),f.bufferData(f.UNIFORM_BUFFER,rce.HEADER_BYTES,f.DYNAMIC_DRAW),this.propertiesBuffer=f.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(f.bindBuffer(f.UNIFORM_BUFFER,this.propertiesBuffer),f.bufferData(f.UNIFORM_BUFFER,this.totalBytes,f.DYNAMIC_DRAW),this.blockIndicesBuffer=f.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");f.bindBuffer(f.UNIFORM_BUFFER,this.blockIndicesBuffer),f.bufferData(f.UNIFORM_BUFFER,this.totalBytes,f.DYNAMIC_DRAW),f.bindBuffer(f.UNIFORM_BUFFER,null)}writeHeader(u){const f=this.headerData;f[0]=u.dataDrivenMask,f[1]=u.zoomDependentMask,f[2]=u.dataDrivenBlockSizeVec4,f[3]=u.offsets[0],f[4]=u.offsets[1],f[5]=u.offsets[2],f[6]=u.offsets[3],f[7]=u.offsets[4],f[8]=u.offsets[5],f[9]=u.offsets[6],f[10]=u.offsets[7],f[11]=u.offsets[8]}writeDataDrivenBlock(u,f,_){const C=4*_.dataDrivenBlockSizeVec4;if(C===0)return;const M=f*C;if(M+C>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${f} exceeds propertiesData capacity`);for(let P=0;P<9;P++)_.dataDrivenMask&1<{if(!B)return;const W=_.getUniformBlockIndex(f,P);W!==_.INVALID_INDEX&&(_.uniformBlockBinding(f,W,U),_.bindBufferBase(_.UNIFORM_BUFFER,U,B))},M=3*this.batchIndex;C("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,M),C("SymbolPaintPropertiesUniform",this.propertiesBuffer,M+1),C("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,M+2)}destroy(){if(this.context){const u=this.context.gl;this.headerBuffer&&(u.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(u.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(u.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};jye.HEADER_DWORDS=12,jye.HEADER_BYTES=48;let Nye=jye;function kye(g,u,f,_){return[uT(255*g,255*u),uT(255*f,255*_)]}function MIe(g,u,f,_,C,M,P,B){return!!g&&(g.kind==="constant"?g.value==="none":g.kind==="composite"||g.kind==="source"?g.evaluate({zoom:0,brightness:M,worldview:B},u,f,C,_,P)==="none":typeof g=="string"&&g==="none")}Dr(Nye,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class Sye{constructor(u,f,_,C,M="",P,B){this.layer=u,this.zoom=f,this.lut=_,this.isText=C,this.propDefs=this._getPropDefs(),this.worldview=M,this.maxUniformBufferBindings=P||24,this.uboSizeDwords=B||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(u,C),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 u=this.isText?"text":"icon";return[{name:`${u}-color`,useThemeName:`${u}-color-use-theme`,isColor:!0},{name:`${u}-halo-color`,useThemeName:`${u}-halo-color-use-theme`,isColor:!0},{name:`${u}-opacity`,useThemeName:null,isColor:!1},{name:`${u}-halo-width`,useThemeName:null,isColor:!1},{name:`${u}-halo-blur`,useThemeName:null,isColor:!1},{name:`${u}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${u}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${u}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const u=this.layer.paint,f=this.propDefs;let _=0,C=0,M=0,P=0;const B=[0,0,0,0,0,0,0,0,0];for(let U=0;U<9;U++){const{name:W,isColor:ee,isVec2:se}=f[U],ae=u.get(W),me=!(!ae||typeof ae.isConstant!="function"||ae.isConstant()),ge=this._appearancesHavePaintProperties(W),we=me||ge,Ee=!(!ae||!ae.value||ae.value.kind!=="composite"),Fe=this.layer._transitionablePaint._values[W],Qe=!we&&(Fe&&Fe.value&&Fe.value.expression&&Fe.value.expression.kind)==="camera";we?(_|=1<f.hasPaintProperty(u):this.isText?f=>f.hasTextPaintProperties():f=>f.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(u,f){const _=u.paint,C=f?"text":"icon",M=[`${C}-color`,`${C}-halo-color`,`${C}-opacity`,`${C}-halo-width`,`${C}-halo-blur`,`${C}-emissive-strength`,`${C}-occlusion-opacity`,"symbol-z-offset",`${C}-translate`];for(const P of M){const B=_.get(P);if(B&&typeof B=="object"&&"isConstant"in B&&!B.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(u,f){if(f.dataDrivenMask===0)return"";const _=[];for(let C=0;C<9;C++){if(!(f.dataDrivenMask&1<=ge){Rr(`Too many symbol features: batch ${ae} requires binding points up to ${3*ae+2}, device limit ${ge}. Some features will render incorrectly.`);const Ee={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:f,featureId:U};return this.allFeatures.push(Ee),U!=null&&(this.featureVertexRangesFromId.has(U)||this.featureVertexRangesFromId.set(U,[]),this.featureVertexRangesFromId.get(U).push(Ee)),0}this.ubos[ae]||(this.ubos[ae]=new Nye(B,ae,this.uboSizeDwords),this.ubos[ae].writeHeader(W)),this.ubos[ae].writeDataDrivenBlock(ee,me,W);const we={batchIndex:ae,localFeatureIndex:me,vtFeatureIndex:f,featureId:U};return this.allFeatures.push(we),U!=null&&(this.featureVertexRangesFromId.has(U)||this.featureVertexRangesFromId.set(U,[]),this.featureVertexRangesFromId.get(U).push(we)),me}updateFeatures(u,f,_,C,M,P,B){if(this.layer=f,this.cachedConstantUniforms=null,!this.cachedHeader)return;const U=this.cachedHeader;for(const W of u){const ee=this.featureVertexRangesFromId.get(W);if(!ee)continue;const se=P[W]||{};for(const ae of ee){if(!_)continue;const me=_.feature(ae.vtFeatureIndex);if(!me)continue;const ge={type:me.type,id:W,properties:me.properties||{},geometry:[]},we=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(ae.vtFeatureIndex):void 0,Ee=this.evaluateAllProperties(ge,se,C,M,B,void 0,we);this.ubos[ae.batchIndex]&&this.ubos[ae.batchIndex].writeDataDrivenBlock(Ee,ae.localFeatureIndex,U)}}}updateDynamicExpressions(u,f,_,C,M,P){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader)return;const B=this.cachedHeader;for(const U of this.allFeatures){if(!f)continue;const W=f.feature(U.vtFeatureIndex);if(!W)continue;const ee=U.featureId!=null&&M[U.featureId]||{},se={type:W.type,id:U.featureId,properties:W.properties||{},geometry:[]},ae=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(U.vtFeatureIndex):void 0,me=this.evaluateAllProperties(se,ee,_,C,P,void 0,ae);this.ubos[U.batchIndex]&&this.ubos[U.batchIndex].writeDataDrivenBlock(me,U.localFeatureIndex,B)}}updateFeaturePaintForAppearance(u,f,_,C,M,P,B){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(u,B||null),!this.cachedHeader))return!1;const U=this.cachedHeader;if(U.dataDrivenMask===0)return!1;let W=!1;for(const ee of this.allFeatures){if(ee.vtFeatureIndex!==u)continue;const se=this.evaluateAllProperties(f,_,C,M,P,void 0,B);this.ubos[ee.batchIndex]&&(this.ubos[ee.batchIndex].writeDataDrivenBlock(se,ee.localFeatureIndex,U),W=!0)}return W}getConstantUniformValues(u,f){const _=this.cachedHeader,C=!(!_||!_.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===f&&(!C||this.cachedConstantRenderZoom===u))return this.cachedConstantUniforms;const M=this.layer.paint,P=this.propDefs,B=C?new ui(u,{brightness:f,worldview:this.worldview}):null,U={type:1,id:void 0,properties:{},geometry:[]},W=ae=>{const me=P[ae],ge=M.get(me.name);if(!ge)return[0,0,0,1];const we=me.useThemeName?M.get(me.useThemeName):void 0,Ee=MIe(we&&typeof we!="string"?we.value:void 0,U,{},[],void 0,f,void 0,this.worldview)?null:this.lut;let Fe;Fe=_&&_.cameraMask&1<{const ge=M.get(P[ae].name);if(!ge)return me;if(_&&_.cameraMask&1<{_.text=function(C,M,P){const B=M.layout.get("text-transform").evaluate(P,{});return B==="uppercase"?C=C.toLocaleUpperCase():B==="lowercase"&&(C=C.toLocaleLowerCase()),Fg.applyArabicShaping&&(C=Fg.applyArabicShaping(C)),C}(_.text,u,f)}),g}const f6={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function kvt(g){return g==="︶"||g==="﹈"||g==="︸"||g==="﹄"||g==="﹂"||g==="︾"||g==="︼"||g==="︺"||g==="︘"||g==="﹀"||g==="︐"||g==="︓"||g==="︔"||g==="`"||g===" ̄"||g==="︑"||g==="︒"}function Svt(g){return g==="︵"||g==="﹇"||g==="︷"||g==="﹃"||g==="﹁"||g==="︽"||g==="︻"||g==="︹"||g==="︗"||g==="︿"}const Cye=4294967296,IIe=1/Cye,LIe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let I7=class{constructor(g=new Uint8Array(16)){this.buf=ArrayBuffer.isView(g)?g:new Uint8Array(g),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(g,u,f=this.length){for(;this.pos>3,M=this.pos;this.type=7&_,g(C,u,this),this.pos===M&&this.skip(_)}return u}readMessage(g,u){return this.readFields(g,u,this.readVarint()+this.pos)}readFixed32(){const g=this.dataView.getUint32(this.pos,!0);return this.pos+=4,g}readSFixed32(){const g=this.dataView.getInt32(this.pos,!0);return this.pos+=4,g}readFixed64(){const g=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*Cye;return this.pos+=8,g}readSFixed64(){const g=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*Cye;return this.pos+=8,g}readFloat(){const g=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,g}readDouble(){const g=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,g}readVarint(g){const u=this.buf;let f,_;return _=u[this.pos++],f=127&_,_<128?f:(_=u[this.pos++],f|=(127&_)<<7,_<128?f:(_=u[this.pos++],f|=(127&_)<<14,_<128?f:(_=u[this.pos++],f|=(127&_)<<21,_<128?f:(_=u[this.pos],f|=(15&_)<<28,function(C,M,P){const B=P.buf;let U,W;if(W=B[P.pos++],U=(112&W)>>4,W<128||(W=B[P.pos++],U|=(127&W)<<3,W<128)||(W=B[P.pos++],U|=(127&W)<<10,W<128)||(W=B[P.pos++],U|=(127&W)<<17,W<128)||(W=B[P.pos++],U|=(127&W)<<24,W<128)||(W=B[P.pos++],U|=(1&W)<<31,W<128))return _T(C,U,M);throw new Error("Expected varint not more than 10 bytes")}(f,g,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const g=this.readVarint();return g%2==1?(g+1)/-2:g/2}readBoolean(){return!!this.readVarint()}readString(){const g=this.readVarint()+this.pos,u=this.pos;return this.pos=g,g-u>=12&&LIe?LIe.decode(this.buf.subarray(u,g)):function(f,_,C){let M="",P=_;for(;P239?4:B>223?3:B>191?2:1;if(P+ae>C)break;ae===1?B<128&&(se=B):ae===2?(U=f[P+1],(192&U)==128&&(se=(31&B)<<6|63&U,se<=127&&(se=null))):ae===3?(U=f[P+1],W=f[P+2],(192&U)==128&&(192&W)==128&&(se=(15&B)<<12|(63&U)<<6|63&W,(se<=2047||se>=55296&&se<=57343)&&(se=null))):ae===4&&(U=f[P+1],W=f[P+2],ee=f[P+3],(192&U)==128&&(192&W)==128&&(192&ee)==128&&(se=(15&B)<<18|(63&U)<<12|(63&W)<<6|63&ee,(se<=65535||se>=1114112)&&(se=null))),se===null?(se=65533,ae=1):se>65535&&(se-=65536,M+=String.fromCharCode(se>>>10&1023|55296),se=56320|1023&se),M+=String.fromCharCode(se),P+=ae}return M}(this.buf,u,g)}readBytes(){const g=this.readVarint()+this.pos,u=this.buf.subarray(this.pos,g);return this.pos=g,u}readPackedVarint(g=[],u){const f=this.readPackedEnd();for(;this.pos127;);else if(u===2)this.pos=this.readVarint()+this.pos;else if(u===5)this.pos+=4;else{if(u!==1)throw new Error(`Unimplemented type: ${u}`);this.pos+=8}}writeTag(g,u){this.writeVarint(g<<3|u)}realloc(g){let u=this.length||16;for(;u268435455||g<0?function(u,f){let _,C;if(u>=0?(_=u%4294967296|0,C=u/4294967296|0):(_=~(-u%4294967296),C=~(-u/4294967296),4294967295^_?_=_+1|0:(_=0,C=C+1|0)),u>=18446744073709552e3||u<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");f.realloc(10),function(M,P,B){B.buf[B.pos++]=127&M|128,M>>>=7,B.buf[B.pos++]=127&M|128,M>>>=7,B.buf[B.pos++]=127&M|128,M>>>=7,B.buf[B.pos++]=127&M|128,B.buf[B.pos]=127&(M>>>=7)}(_,0,f),function(M,P){const B=(7&M)<<4;P.buf[P.pos++]|=B|((M>>>=3)?128:0),M&&(P.buf[P.pos++]=127&M|((M>>>=7)?128:0),M&&(P.buf[P.pos++]=127&M|((M>>>=7)?128:0),M&&(P.buf[P.pos++]=127&M|((M>>>=7)?128:0),M&&(P.buf[P.pos++]=127&M|((M>>>=7)?128:0),M&&(P.buf[P.pos++]=127&M)))))}(C,f)}(g,this):(this.realloc(4),this.buf[this.pos++]=127&g|(g>127?128:0),g<=127||(this.buf[this.pos++]=127&(g>>>=7)|(g>127?128:0),g<=127||(this.buf[this.pos++]=127&(g>>>=7)|(g>127?128:0),g<=127||(this.buf[this.pos++]=g>>>7&127))))}writeSVarint(g){this.writeVarint(g<0?2*-g-1:2*g)}writeBoolean(g){this.writeVarint(+g)}writeString(g){g=String(g),this.realloc(4*g.length),this.pos++;const u=this.pos;this.pos=function(_,C,M){for(let P,B,U=0;U55295&&P<57344){if(!B){P>56319||U+1===C.length?(_[M++]=239,_[M++]=191,_[M++]=189):B=P;continue}if(P<56320){_[M++]=239,_[M++]=191,_[M++]=189,B=P;continue}P=B-55296<<10|P-56320|65536,B=null}else B&&(_[M++]=239,_[M++]=191,_[M++]=189,B=null);P<128?_[M++]=P:(P<2048?_[M++]=P>>6|192:(P<65536?_[M++]=P>>12|224:(_[M++]=P>>18|240,_[M++]=P>>12&63|128),_[M++]=P>>6&63|128),_[M++]=63&P|128)}return M}(this.buf,g,this.pos);const f=this.pos-u;f>=128&&PIe(u,f,this),this.pos=u-1,this.writeVarint(f),this.pos+=f}writeFloat(g){this.realloc(4),this.dataView.setFloat32(this.pos,g,!0),this.pos+=4}writeDouble(g){this.realloc(8),this.dataView.setFloat64(this.pos,g,!0),this.pos+=8}writeBytes(g){const u=g.length;this.writeVarint(u),this.realloc(u);for(let f=0;f=128&&PIe(f,_,this),this.pos=f-1,this.writeVarint(_),this.pos+=_}writeMessage(g,u,f){this.writeTag(g,2),this.writeRawMessage(u,f)}writePackedVarint(g,u){u.length&&this.writeMessage(g,Cvt,u)}writePackedSVarint(g,u){u.length&&this.writeMessage(g,Tvt,u)}writePackedBoolean(g,u){u.length&&this.writeMessage(g,Mvt,u)}writePackedFloat(g,u){u.length&&this.writeMessage(g,Evt,u)}writePackedDouble(g,u){u.length&&this.writeMessage(g,Avt,u)}writePackedFixed32(g,u){u.length&&this.writeMessage(g,Ivt,u)}writePackedSFixed32(g,u){u.length&&this.writeMessage(g,Lvt,u)}writePackedFixed64(g,u){u.length&&this.writeMessage(g,Pvt,u)}writePackedSFixed64(g,u){u.length&&this.writeMessage(g,Dvt,u)}writeBytesField(g,u){this.writeTag(g,2),this.writeBytes(u)}writeFixed32Field(g,u){this.writeTag(g,5),this.writeFixed32(u)}writeSFixed32Field(g,u){this.writeTag(g,5),this.writeSFixed32(u)}writeFixed64Field(g,u){this.writeTag(g,1),this.writeFixed64(u)}writeSFixed64Field(g,u){this.writeTag(g,1),this.writeSFixed64(u)}writeVarintField(g,u){this.writeTag(g,0),this.writeVarint(u)}writeSVarintField(g,u){this.writeTag(g,0),this.writeSVarint(u)}writeStringField(g,u){this.writeTag(g,2),this.writeString(u)}writeFloatField(g,u){this.writeTag(g,5),this.writeFloat(u)}writeDoubleField(g,u){this.writeTag(g,1),this.writeDouble(u)}writeBooleanField(g,u){this.writeVarintField(g,+u)}};function _T(g,u,f){return f?4294967296*u+(g>>>0):4294967296*(u>>>0)+(g>>>0)}function PIe(g,u,f){const _=u<=16383?1:u<=2097151?2:u<=268435455?3:Math.floor(Math.log(u)/(7*Math.LN2));f.realloc(_);for(let C=f.pos-1;C>=g;C--)f.buf[C+_]=f.buf[C]}function Cvt(g,u){for(let f=0;f=0&&_>=u&&L7[this.text.charCodeAt(_)];_--)f--;this.text=this.text.substring(u,f),this.sectionIndex=this.sectionIndex.slice(u,f)}substring(u,f){const _=new wT;return _.text=this.text.substring(u,f),_.sectionIndex=this.sectionIndex.slice(u,f),_.sections=this.sections,_}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((u,f)=>Math.max(u,this.sections[f].scale),0)}addTextSection(u,f){this.text+=u.text,this.sections.push(p6.forText(u.scale,u.fontStack||f));const _=this.sections.length-1;for(let C=0;C=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Tye(g,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we=1,Ee=1){const Fe=wT.fromFeature(g,C,we,Ee);se===Hm.vertical&&Fe.verticalizePunctuation(ae);let Qe=[];const Ve=function(Et,Ot,Lt,Pt,hs,bs,Ts=1){if(!Et)return[];const Rs=[],Es=function(Ps,zs,Ks,tr,Ar,ur,dr=1){let sr=0;for(let Tr=0;Tr=0;let ls=0;for(let Ps=0;Ps0&&Eu>ca&&(ca=Eu)}else{const Xc=Lt[Io.fontStack];if(!Xc)continue;Xc[Lo]&&(dl=Xc[Lo]);const ih=Ot[Io.fontStack];if(!ih)continue;const Vd=ih.glyphs[Lo];if(!Vd)continue;if(Pl=Vd.metrics,Pc=Lo!==8203?Ic:0,dr){const Go=ih.ascender!==void 0?Math.abs(ih.ascender):0,Eu=ih.descender!==void 0?Math.abs(ih.descender):0,Qc=(Go+Eu)*cl;Ho-f/2;){if(P--,P<0)return!1;B-=g[P].dist(M),M=g[P]}B+=g[P].dist(g[P+1]),P++;const U=[];let W=0;for(;B_;)W-=U.shift().angleDelta;if(W>C)return!1;P++,B+=ee.dist(se)}return!0}function VIe(g){let u=0;for(let f=0;fW){const ge=(W-U)/me,we=hn(se.x,ae.x,ge),Ee=hn(se.y,ae.y,ge),Fe=new j1(we,Ee,0,ae.angleTo(se),ee);return!P||qIe(g,Fe,B,P,u)?Fe:void 0}U+=me}}function Uvt(g,u,f,_,C,M,P,B,U){const W=HIe(_,M,P),ee=GIe(_,C),se=ee*P,ae=g[0].x===0||g[0].x===U||g[0].y===0||g[0].y===U;return u-se=0&&at=0&&ut=0&&ae+W<=ee){const ft=new j1(at,ut,0,Qe,ge);_&&!qIe(g,ft,M,_,C)||me.push(ft)}}se+=Fe}return B||me.length||P||(me=WIe(g,se/2,f,_,C,M,P,!0,U)),me}function KIe(g){let u=0,f=0;for(const P of g)u+=P.w*P.h,f=Math.max(f,P.w);g.sort((P,B)=>B.h-P.h);const _=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(u/.95)),f),h:1/0}];let C=0,M=0;for(const P of g)for(let B=_.length-1;B>=0;B--){const U=_[B];if(!(P.w>U.w||P.h>U.h)){if(P.x=U.x,P.y=U.y,M=Math.max(M,P.y+P.h),C=Math.max(C,P.x+P.w),P.w===U.w&&P.h===U.h){const W=_.pop();W&&B<_.length&&(_[B]=W)}else P.h===U.h?(U.x+=P.w,U.w-=P.w):P.w===U.w?(U.y+=P.h,U.h-=P.h):(_.push({x:U.x+P.w,y:U.y,w:U.w-P.w,h:P.h}),U.y+=P.h,U.h-=P.h);break}}return{w:C,h:M,fill:u/(C*M)||0}}function D7(g,u){return g.idu.id?1:g.versionu.version?1:g.sxu.sx?1:g.syu.sy?1:0}function Lye(g){let u=0;for(let f=0;f0,YIe(u,_,this.iconDescriptors,M),YIe(f,_,this.patternDescriptors,M),this.iconDescriptors.sort(D7),this.patternDescriptors.sort(D7);let P=0;const B=C?C.data:"";B&&(P=Vg(P,Lye(B))),P=Vg(P,1);for(const U of this.iconDescriptors)P=Vg(P,Lye(U.id)),P=Vg(P,U.version),P=Vg(P,U.sx),P=Vg(P,U.sy);P=Vg(P,1);for(const U of this.patternDescriptors)P=Vg(P,Lye(U.id)),P=Vg(P,U.version),P=Vg(P,U.sx),P=Vg(P,U.sy);this.hash=P}subsetOf(u){return this.isSubsetArray(this.iconDescriptors,u.iconDescriptors,D7)&&this.isSubsetArray(this.patternDescriptors,u.patternDescriptors,D7)}isSubsetArray(u,f,_){let C=0,M=0;if(u.length>f.length)return!1;for(;C{const P=C.variant.id.toString().localeCompare(M.variant.id.toString());return P!==0?P:C.variant.sx!==M.variant.sx?C.variant.sx-M.variant.sx:C.variant.sy!==M.variant.sy?C.variant.sy-M.variant.sy:0});const _=new Map;for(const C of f)_.set(C.key,C.value);return _}class ZIe{constructor(u){this.sourceAtlasHash=u}}class XIe{constructor(u,f,_,C){const M=new Map,P=new Map;this.haveRenderCallbacks=[];const B=[],U=C!==void 0,W=U?new Map:void 0,ee=U?Rye(u,W):u,se=U?Rye(f,W):f;this.addImages(ee,M,1,B),this.addImages(se,P,2,B);const{w:ae,h:me}=KIe(B),ge=new cu({width:ae||1,height:me||1});for(const[we,Ee]of ee.entries()){const Fe=M.get(we).paddedRect;cu.copy(Ee.data,ge,{x:0,y:0},{x:Fe.x+1,y:Fe.y+1},Ee.data,null,Ee.sdf)}for(const[we,Ee]of se.entries()){const Fe=P.get(we),Qe=Fe.paddedRect;let Ve=Fe.padding;const at=Qe.x+Ve,ut=Qe.y+Ve,ft=Ee.data.width,Bt=Ee.data.height;Ve=Ve>1?Ve-1:Ve,cu.copy(Ee.data,ge,{x:0,y:0},{x:at,y:ut},Ee.data,_),cu.copy(Ee.data,ge,{x:0,y:Bt-Ve},{x:at,y:ut-Ve},{width:ft,height:Ve},_),cu.copy(Ee.data,ge,{x:0,y:0},{x:at,y:ut+Bt},{width:ft,height:Ve},_),cu.copy(Ee.data,ge,{x:ft-Ve,y:0},{x:at-Ve,y:ut},{width:Ve,height:Bt},_),cu.copy(Ee.data,ge,{x:0,y:0},{x:at+ft,y:ut},{width:Ve,height:Bt},_),cu.copy(Ee.data,ge,{x:ft-Ve,y:Bt-Ve},{x:at-Ve,y:ut-Ve},{width:Ve,height:Ve},_),cu.copy(Ee.data,ge,{x:0,y:Bt-Ve},{x:at+ft,y:ut-Ve},{width:Ve,height:Ve},_),cu.copy(Ee.data,ge,{x:0,y:0},{x:at+ft,y:ut+Bt},{width:Ve,height:Ve},_),cu.copy(Ee.data,ge,{x:ft-Ve,y:0},{x:at-Ve,y:ut+Bt},{width:Ve,height:Ve},_)}this.lut=_,this.image=ge,this.iconPositions=M,this.patternPositions=P,U&&(this.contentDescriptor=new Pye(ee,se,C,_,W))}addImages(u,f,_,C){for(const[M,P]of u.entries()){const{bin:B,imagePosition:U,imageVariant:W}=Dye(M,P,_);f.set(M,U),C.push(B),P.hasRenderCallback&&this.haveRenderCallbacks.push(W.id)}}patchUpdatedImages(u,f,_,C){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(M=>u.hasImage(M,_)),u.dispatchRenderCallbacks(this.haveRenderCallbacks,_);for(const M of u.getUpdatedImages(_)){for(const P of this.iconPositions.keys()){const B=Sf.parse(P);if(kt.isEqual(B.id,M)){const U=u.getImage(M,_);this.patchUpdatedImage(this.iconPositions.get(P),U,f,null)}}for(const P of this.patternPositions.keys()){const B=Sf.parse(P);if(kt.isEqual(B.id,M)){const U=u.getImage(M,_);this.patchUpdatedImage(this.patternPositions.get(P),U,f,C||this.lut)}}}}patchUpdatedImage(u,f,_,C=null){if(!u||!f||u.version===f.version)return;u.version=f.version;const[M,P]=u.tl,B=u.sdf;if(this.lut||B){const U={width:f.data.width,height:f.data.height},W=new cu(U);cu.copy(f.data,W,{x:0,y:0},{x:0,y:0},U,C,B),_.update(W,{position:{x:M,y:P},recreateWhenResize:!1})}else _.update(f.data,{position:{x:M,y:P},recreateWhenResize:!1})}}Dr(x6,"ImagePosition"),Dr(XIe,"ImageAtlas",{omit:["lut"]}),Dr(ZIe,"ImageAtlasReference");class g6{constructor(u){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!u||u.useServerFontComposition===void 0||u.useServerFontComposition}loadGlyphRange(u,f,_,C,M){if(this.useServerFontComposition)return void g6.loadGlyphRange(u,f,_,C,M);const P=u.split(",").map(B=>B.trim()).filter(B=>B.length>0);P.length!==0?P.length!==1?this._loadMultipleFonts(P,f,_,C,M):this._loadFont(P[0],f,_,C,M):M(new Error("Empty fontstack"))}_loadMultipleFonts(u,f,_,C,M){const P=u.map(()=>null),B={completed:0,firstError:null,callbackCalled:!1},U=(W,ee,se)=>{if(!B.callbackCalled&&(ee&&!B.firstError&&(B.firstError=ee),se&&(P[W]=se),B.completed++,B.completed===u.length)){B.callbackCalled=!0;const ae=P.filter(ge=>ge!==null);if(ae.length===0)return void M(B.firstError||new Error("All fonts failed to load"));const me=this._composeGlyphs(ae);M(null,me)}};for(let W=0;W{U(W,ee,se)})}_loadFont(u,f,_,C,M){const P=`${u}:${f}`;if(this.cachedRanges.has(P)){const U=this.cachedRanges.get(P);return void ju.frame(()=>M(null,U))}const B=this.pendingRequests.get(P);B?B.push(M):(this.pendingRequests.set(P,[M]),g6.loadGlyphRange(u,f,_,C,(U,W)=>{U||this.cachedRanges.set(P,W||null);const ee=this.pendingRequests.get(P);if(this.pendingRequests.delete(P),ee)for(const se of ee)se(U,W)}))}_composeGlyphs(u){const f={};let _,C;for(const M of u)if(_===void 0&&M.ascender!==void 0&&(_=M.ascender),C===void 0&&M.descender!==void 0&&(C=M.descender),M.glyphs)for(const P in M.glyphs)f[P]===void 0&&(f[P]=M.glyphs[P]);return{glyphs:f,ascender:_,descender:C}}}g6.loadGlyphRange=function(g,u,f,_,C){const M=256*u,P=M+255,B=_.transformRequest(_.normalizeGlyphsURL(f).replace("{fontstack}",g).replace("{range}",`${M}-${P}`),Zv.Glyphs);Yy(B,(U,W)=>{if(U)C(U);else if(W){const ee={},se=function(ae){return new I7(ae).readFields(Rvt,{})}(W);for(const ae of se.glyphs)ee[ae.id]=ae;C(null,{glyphs:ee,ascender:se.ascender,descender:se.descender})}})};const y6=1e20;function QIe(g,u,f,_,C,M,P,B,U){for(let W=u;W-1);U++,M[U]=B,P[U]=W,P[U+1]=y6}for(let B=0,U=0;B<_;B++){for(;P[U+1]{if(P){C.ascender=P.ascender,C.descender=P.descender;for(const B in P.glyphs)this._doesCharSupportLocalGlyph(+B)||(C.glyphs[+B]=P.glyphs[+B]);C.ranges[f]=!0}for(const B of C.requests[f]||[])B(M,P);delete C.requests[f]}))}getGlyphs(u,f){const _=[],C=this.url||ba.GLYPHS_URL;for(const M in u)for(const P of u[M])_.push({stack:M,id:P});At(_,({stack:M,id:P},B)=>{let U=this.entries[M];U||(U=this.entries[M]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let W=U.glyphs[P];if(W!==void 0)return void B(null,{stack:M,id:P,glyph:W});if(W=this._tinySDF(U,M,P),W)return U.glyphs[P]=W,void B(null,{stack:M,id:P,glyph:W});const ee=Math.floor(P/256);if(256*ee>65535)return Rr("glyphs > 65535 not supported"),void B(null,{stack:M,id:P,glyph:W});if(U.ranges[ee])return void B(null,{stack:M,id:P,glyph:W});let se=U.requests[ee];se||(se=U.requests[ee]=[],this.glyphLoader.loadGlyphRange(M,ee,C,this.requestManager,(ae,me)=>{if(me){U.ascender=me.ascender,U.descender=me.descender;for(const ge in me.glyphs)this._doesCharSupportLocalGlyph(+ge)||(U.glyphs[+ge]=me.glyphs[+ge]);U.ranges[ee]=!0}for(const ge of se)ge(ae,me);delete U.requests[ee]})),se.push((ae,me)=>{ae?B(ae):me&&B(null,{stack:M,id:P,glyph:me.glyphs[P]||null})})},(M,P)=>{if(M)f(M);else if(P){const B={};for(const{stack:U,id:W,glyph:ee}of P)B[U]===void 0&&(B[U]={}),B[U].glyphs===void 0&&(B[U].glyphs={}),B[U].glyphs[W]=ee&&{id:ee.id,bitmap:ee.bitmap.clone(),metrics:ee.metrics},B[U].ascender=this.entries[U].ascender,B[U].descender=this.entries[U].descender;f(null,B)}})}_doesCharSupportLocalGlyph(u){return this.localGlyphMode!==Oye.none&&(this.localGlyphMode===Oye.all?!!this.localFontFamily:!!this.localFontFamily&&(K5(u)||uP(u)||H2(u)||c1(u)||V2(u)||cP(u)||(f=u)>=131072&&f<=173791||(_=>_>=66736&&_<=66815)(u)));var f}_tinySDF(u,f,_){const C=this.localFontFamily;if(!C||!this._doesCharSupportLocalGlyph(_))return;let M=u.tinySDF;if(!M){let Ee="400";/bold/i.test(f)?Ee="900":/medium/i.test(f)?Ee="500":/light/i.test(f)&&(Ee="200"),M=u.tinySDF=new R7.TinySDF({fontFamily:C,fontWeight:Ee,fontSize:48,buffer:6,radius:16}),M.fontWeight=Ee}const P=M.fontWeight;if(this.localGlyphs[P][_])return this.localGlyphs[P][_];const B=String.fromCodePoint(_),{data:U,width:W,height:ee,glyphWidth:se,glyphHeight:ae,glyphLeft:me,glyphTop:ge,glyphAdvance:we}=M.draw(B);return this.localGlyphs[P][_]={id:_,bitmap:new j_({width:W,height:ee},U),metrics:{width:se/2,height:ae/2,left:me/2,top:ge/2-27,advance:we/2,localGlyph:!0}}}}function eLe(g,u){return g+u[1]-u[0]}function Fye(g,u,f,_,C=1){const M=[],P=g.imagePrimary,B=P.pixelRatio,U=P.paddedRect.w-2,W=P.paddedRect.h-2,ee=(g.right-g.left)*C,se=(g.bottom-g.top)*C,ae=P.stretchX||[[0,U]],me=P.stretchY||[[0,W]],ge=ae.reduce(eLe,0),we=me.reduce(eLe,0),Ee=U-ge,Fe=W-we;let Qe=0,Ve=ge,at=0,ut=we,ft=0,Bt=Ee,Et=0,Ot=Fe;if(P.content&&_){const Pt=P.content;Qe=O7(ae,0,Pt[0]),at=O7(me,0,Pt[1]),Ve=O7(ae,Pt[0],Pt[2]),ut=O7(me,Pt[1],Pt[3]),ft=Pt[0]-Qe,Et=Pt[1]-at,Bt=Pt[2]-Pt[0]-Ve,Ot=Pt[3]-Pt[1]-ut}const Lt=(Pt,hs,bs,Ts)=>{const Rs=F7(Pt.stretch-Qe,Ve,ee,g.left*C),Es=B7(Pt.fixed-ft,Bt,Pt.stretch,ge),Ws=F7(hs.stretch-at,ut,se,g.top*C),ls=B7(hs.fixed-Et,Ot,hs.stretch,we),Ps=F7(bs.stretch-Qe,Ve,ee,g.left*C),zs=B7(bs.fixed-ft,Bt,bs.stretch,ge),Ks=F7(Ts.stretch-at,ut,se,g.top*C),tr=B7(Ts.fixed-Et,Ot,Ts.stretch,we),Ar=new ss(Rs,Ws),ur=new ss(Ps,Ws),dr=new ss(Ps,Ks),sr=new ss(Rs,Ks),Tr=new ss(Es/B,ls/B),zr=new ss(zs/B,tr/B),mn=u*Math.PI/180;if(mn){const ca=Math.sin(mn),Ho=Math.cos(mn),hi=[Ho,-ca,ca,Ho];Ar._matMult(hi),ur._matMult(hi),sr._matMult(hi),dr._matMult(hi)}const Gr=Pt.stretch+Pt.fixed,Vn=bs.stretch+bs.fixed,$a=hs.stretch+hs.fixed,Hn=Ts.stretch+Ts.fixed,Va=g.imageSecondary;return{tl:Ar,tr:ur,bl:sr,br:dr,texPrimary:{x:P.paddedRect.x+1+Gr,y:P.paddedRect.y+1+$a,w:Vn-Gr,h:Hn-$a},texSecondary:Va?{x:Va.paddedRect.x+1+Gr,y:Va.paddedRect.y+1+$a,w:Vn-Gr,h:Hn-$a}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Tr,pixelOffsetBR:zr,minFontScaleX:Bt/B/ee,minFontScaleY:Ot/B/se,isSDF:f}};if(P.stretchX||P.stretchY){const Pt=tLe(ae,Ee,ge),hs=tLe(me,Fe,we);for(let bs=0;bs0?[Qe,-Ve]:at<0?[-Qe,Ve]:Qe===0?[Ve,Qe]:[Ve,-Qe]}(f);let me=Math.abs(u.top-u.bottom);for(const Fe of u.positionedLines)me-=Fe.lineOffset;const ge=u.positionedLines.length,we=me/ge;let Ee=u.top-f[1];for(let Fe=0;FeM)&&(M=ge.x),(!me||ge.y>P)&&(P=ge.y)}const U=Math.min(M-_,P-C);let W=U/2;const ee=new E2([],Gvt);if(U===0)return new ss(_,C);for(let me=_;mese.d||!se.d)&&(se=me,f&&console.log("found best %d after %d probes",Math.round(1e4*me.d)/1e4,ae)),me.max-se.d<=u||(W=me.h/2,ee.push(new NT(me.p.x-W,me.p.y-W,W,g)),ee.push(new NT(me.p.x+W,me.p.y-W,W,g)),ee.push(new NT(me.p.x-W,me.p.y+W,W,g)),ee.push(new NT(me.p.x+W,me.p.y+W,W,g)),ae+=4)}return f&&(console.log(`num probes: ${ae}`),console.log(`best distance: ${se.d}`)),se.p}function Gvt(g,u){return u.max-g.max}R7.TinySDF=class{constructor({fontSize:g=24,buffer:u=3,radius:f=8,cutoff:_=.25,fontFamily:C="sans-serif",fontWeight:M="normal",fontStyle:P="normal",lang:B=null}={}){this.buffer=u,this.cutoff=_,this.radius=f,this.lang=B;const U=this.size=g+4*u,W=this._createCanvas(U),ee=this.ctx=W.getContext("2d",{willReadFrequently:!0});ee.font=`${P} ${M} ${g}px ${C}`,ee.textBaseline="alphabetic",ee.textAlign="left",ee.fillStyle="black",this.gridOuter=new Float64Array(U*U),this.gridInner=new Float64Array(U*U),this.f=new Float64Array(U),this.z=new Float64Array(U+1),this.v=new Uint16Array(U)}_createCanvas(g){const u=document.createElement("canvas");return u.width=u.height=g,u}draw(g){const{width:u,actualBoundingBoxAscent:f,actualBoundingBoxDescent:_,actualBoundingBoxLeft:C,actualBoundingBoxRight:M}=this.ctx.measureText(g),P=Math.ceil(f),B=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(M-C))),U=Math.min(this.size-this.buffer,P+Math.ceil(_)),W=B+2*this.buffer,ee=U+2*this.buffer,se=Math.max(W*ee,0),ae=new Uint8ClampedArray(se),me={data:ae,width:W,height:ee,glyphWidth:B,glyphHeight:U,glyphTop:P,glyphLeft:0,glyphAdvance:u};if(B===0||U===0)return me;const{ctx:ge,buffer:we,gridInner:Ee,gridOuter:Fe}=this;this.lang&&(ge.lang=this.lang),ge.clearRect(we,we,B,U),ge.fillText(g,we,we+P);const Qe=ge.getImageData(we,we,B,U);Fe.fill(y6,0,se),Ee.fill(0,0,se);for(let Ve=0;Ve0?Bt*Bt:0,Ee[ft]=Bt<0?Bt*Bt:0}}QIe(Fe,0,0,W,ee,W,this.f,this.v,this.z),QIe(Ee,we,we,B,U,W,this.f,this.v,this.z);for(let Ve=0;VeM.y!=we.y>M.y&&M.x<(we.x-ge.x)*(M.y-ge.y)/(we.y-ge.y)+ge.x&&(B=!B),U=Math.min(U,kx(M,ge,we))}}return(B?1:-1)*Math.sqrt(U)}(this.p,C),this.max=this.d+this.h*Math.SQRT2}}const Wvt=Object.keys,Bye=Number.POSITIVE_INFINITY,Kvt=Math.sqrt(2);function C_(g,u,f,_,C,M){const P=Aye(g)&&g.collisionPadding?g.collisionPadding:[0,0,0,0],B={top:g.top-P[1],bottom:g.bottom+P[3],left:g.left-P[0],right:g.right+P[2],scaled:!1};return _!==void 0&&function(U,W){U.top*=W,U.bottom*=W,U.left*=W,U.right*=W,U.scaled=!0}(B,_),M&&(B.left+=M[0],B.right+=M[0],B.top+=M[1],B.bottom+=M[1]),f&&function(U,W,ee){if(!W)return;const se=Pr(W),ae=new ss(ee?ee[0]:0,ee?ee[1]:0),me=new ss(U.left,U.top),ge=new ss(U.right,U.top),we=new ss(U.left,U.bottom),Ee=new ss(U.right,U.bottom);me._rotateAround(se,ae),ge._rotateAround(se,ae),we._rotateAround(se,ae),Ee._rotateAround(se,ae),U.left=Math.min(me.x,ge.x,we.x,Ee.x),U.right=Math.max(me.x,ge.x,we.x,Ee.x),U.top=Math.min(me.y,ge.y,we.y,Ee.y),U.bottom=Math.max(me.y,ge.y,we.y,Ee.y)}(B,f,C),u?{top:Math.min(u.top,B.top),bottom:Math.max(u.bottom,B.bottom),left:Math.min(u.left,B.left),right:Math.max(u.right,B.right),scaled:u.scaled||B.scaled}:B}function nLe(g,[u,f]){let _=0,C=0;if(f===Bye){u<0&&(u=0);const M=u/Kvt;switch(g){case"top-right":case"top-left":C=M-7;break;case"bottom-right":case"bottom-left":C=7-M;break;case"bottom":C=7-u;break;case"top":C=u-7}switch(g){case"top-right":case"bottom-right":_=-M;break;case"top-left":case"bottom-left":_=M;break;case"left":_=u;break;case"right":_=-u}}else{switch(u=Math.abs(u),f=Math.abs(f),g){case"top-right":case"top-left":case"top":C=f-7;break;case"bottom-right":case"bottom-left":case"bottom":C=7-f}switch(g){case"top-right":case"bottom-right":case"right":_=-u;break;case"top-left":case"bottom-left":case"left":_=u}}return[_,C]}function Yvt(g,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge){const we=g.layers[0],Ee=we.appearances;if(Ee.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const Fe={iconBBox:null,iconVerticalBBox:null},Qe={textBBox:null,textVerticalBBox:null},{baseIconRotate:Ve,baseTextRotate:at,iconScaleFactor:ut}=function(Bt,Et,Ot){const Lt=Bt.get("icon-rotate").evaluate(Et,{},Ot),Pt=Bt.get("text-rotate").evaluate(Et,{},Ot),[hs,bs]=Bt.get("icon-size-scale-range");return{baseIconRotate:Lt,baseTextRotate:Pt,iconScaleFactor:ze(1,hs,bs)}}(_,C,M);u&&(Fe.iconBBox=C_(u,Fe.iconBBox,Ve),f)&&(Fe.iconVerticalBBox=C_(f,Fe.iconVerticalBBox,Ve+90));const ft=$7(se.horizontal);ft&&(Qe.textBBox=C_(ft,Qe.textBBox,at,1,me)),se.vertical&&(Qe.textVerticalBBox=C_(se.vertical,Qe.textVerticalBBox,at+90,1,me));for(const Bt of Ee)Bt.hasIconLayoutProperties()&&Zvt(Fe,g,we,Bt,C,M,B,Ve,P,U,u,W,ut,ee,ge),Bt.hasTextLayoutProperties()&&Xvt(Qe,we,Bt,C,M,me,at,ae,ft,se.vertical);return{iconBBox:Fe.iconBBox,iconVerticalBBox:Fe.iconVerticalBBox,textBBox:Qe.textBBox,textVerticalBBox:Qe.textVerticalBBox}}function Zvt(g,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge){const{appearanceIconOffset:we,appearanceIconRotate:Ee,appearanceIconSize:Fe}=aLe(_,f,C,M,P,B,U,W.iconScaleFactor);let Qe=null,Ve=null,at=null;_.hasLayoutProperty("icon-image")?at=function(ft,Bt,Et,Ot,Lt,Pt,hs,bs){let Ts=null;const Rs=Bt.getAppearanceValueAndResolveTokens(Et,"icon-image",Ot,Lt,bs);if(Rs){const Es=ft.getResolvedImageFromTokens(Rs),Ws=Et.hasLayoutProperty("icon-size")?Et.getUnevaluatedLayoutProperty("icon-size"):Bt._unevaluatedLayout._values["icon-size"],ls=v6(Es,hN(ft.zoom,Ws,ft.worldview,bs),Ws,Lt,ft.zoom,Ot,ft.pixelRatio,hs,ft.worldview,bs);Ts=Pt.get(ls.iconPrimary.toString())}return Ts}(u,f,_,C,M,se,ae,ge):ee&&(at=ee.imagePrimary),at&&(Qe=P7(at,null,we,me),u.allowVerticalPlacement&&(Ve=P7(at,null,we,me)));const ut=U>0?Fe/U:1;Qe&&(g.iconBBox=C_(Qe,g.iconBBox,Ee,ut!==1?ut:void 0)),Ve&&(g.iconVerticalBBox=C_(Ve,g.iconVerticalBBox,Ee+90,ut!==1?ut:void 0))}function aLe(g,u,f,_,C,M,P,B){const U=g.hasLayoutProperty("icon-offset")?u.getAppearanceValueAndResolveTokens(g,"icon-offset",f,_,[]):null,W=U&&Array.isArray(U)?U:C,ee=g.hasLayoutProperty("icon-rotate")?u.getAppearanceValueAndResolveTokens(g,"icon-rotate",f,_,[]):null,se=typeof ee=="number"?ee:M,ae=g.hasLayoutProperty("icon-size")?u.getAppearanceValueAndResolveTokens(g,"icon-size",f,_,[]):null;return{appearanceIconOffset:W,appearanceIconRotate:se,appearanceIconSize:typeof ae=="number"?ae*B:P}}function Xvt(g,u,f,_,C,M,P,B,U,W){const{appearanceTextOffset:ee,appearanceTextRotate:se,appearanceTextSize:ae}=iLe(f,u,_,C,M,P,B),me=ae/B,ge=[(ee[0]-M[0])*me,(ee[1]-M[1])*me],we=ge[0]!==0||ge[1]!==0;U&&(g.textBBox=C_(U,g.textBBox,se,me,ee,we?ge:void 0)),W&&(g.textVerticalBBox=C_(W,g.textVerticalBBox,se+90,me,ee,we?ge:void 0))}function iLe(g,u,f,_,C,M,P){const B=g.hasLayoutProperty("text-offset")?u.getAppearanceValueAndResolveTokens(g,"text-offset",f,_,[]):null,U=B&&Array.isArray(B)?[B[0]*Ic,B[1]*Ic]:C,W=g.hasLayoutProperty("text-rotate")?u.getAppearanceValueAndResolveTokens(g,"text-rotate",f,_,[]):null,ee=typeof W=="number"?W:M,se=g.hasLayoutProperty("text-size")?u.getAppearanceValueAndResolveTokens(g,"text-size",f,_,[]):null;return{appearanceTextOffset:U,appearanceTextRotate:ee,appearanceTextSize:typeof se=="number"?se:P}}function z7(g,u,f,_,C,M,P,B,U){if(!u||!u.usvg)return;const W=UIe(_),ee=UIe(C),se=M!=="both"&&M!=="width"||!zIe(_)?1:ee.width/W.width,ae=M!=="both"&&M!=="height"||!$Ie(_)?1:ee.height/W.height;f.scaleSelf(se,ae);const me=f.toString();P.set(me,f),B.set(me,u);const{imagePosition:ge}=Dye(me,u,1);U.set(me,ge)}function oLe(g,u,f,_,C,M,P,B,U,W){if(!g)return;const ee=function(se,ae,me,ge,we,Ee,Fe){if(se.kind==="camera")return se.maxSize;if(se.kind==="composite"){const Qe=ae.possiblyEvaluate(new ui(se.maxZoom,{worldview:Ee}),me,Fe).evaluate(we,{},me,Fe),Ve=ae.possiblyEvaluate(new ui(se.minZoom,{worldview:Ee}),me,Fe).evaluate(we,{},me,Fe);return Math.max(Qe,Ve)}return ae.possiblyEvaluate(new ui(ge,{worldview:Ee}),me,Fe).evaluate(we,{},me,Fe)}(u,f,_,C,M,U,W);return g.scaleSelf(ee*B*P)}function v6(g,u,f,_,C,M,P,B,U,W){return{iconPrimary:oLe(g.getPrimary(),u,f,_,C,M,P,B,U,W),iconSecondary:oLe(g.getSecondary(),u,f,_,C,M,P,B,U,W)}}function Qvt(g,u,f){if(!u)return;const _=f.get(g.toString()),C=f.get(u.toString());_&&C&&(_.paddedRect.w===C.paddedRect.w&&_.paddedRect.h===C.paddedRect.h||Rr(`Mismatch in icon variant sizes: ${g.toString()} and ${u.toString()}`),_.usvg!==C.usvg&&Rr(`Mismatch in icon variant image types: ${g.id} and ${u.id}`))}function lLe(g,u,f,_){if(!g)return;const C=u.get(f.toString());if(C&&(g.imagePrimary=C),_){const M=u.get(_.toString());g.imageSecondary=M}}function Jvt(g,u){for(const f in g.horizontal)cLe(g.horizontal[f],u);cLe(g.vertical,u)}function cLe(g,u){if(g){for(const f of g.positionedLines)for(const _ of f.positionedGlyphs)if(_.image!==null){const C=_.image.toString();_.rect=u.get(C).paddedRect}}}function zye(g){switch(g){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function e1t(g,u,f,_,C,M,P,B,U){const W=$7(M.horizontal)||M.vertical,ee=f.get("icon-text-fit-padding").evaluate(_,{},C);let se,ae=u;return u&&U!=="none"&&(g.allowVerticalPlacement&&M.vertical&&(se=Mye(u,M.vertical,U,ee,B,P)),W&&(ae=Mye(u,W,U,ee,B,P))),{defaultShapedIcon:ae,verticallyShapedIcon:se}}function dLe(g,u){return g*u/24}function t1t(g,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe,Ve,at,ut,ft,Bt){let Et=P.textMaxSize.evaluate(u,{},ae);Et===void 0?Et=B*P.textScaleFactor:Et*=P.textScaleFactor;const Ot=g.layers[0].layout,Lt=dLe(B,P.textScaleFactor),Pt=$7(f.horizontal)||f.vertical,hs=g.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),bs=g.getAppearanceFeatureData(u.index);(Ee!=="none"||hs)&&bs&&(bs.textShaping=Pt,bs.iconTextFitPadding=Ot.get("icon-text-fit-padding").evaluate(u,{},ae),bs.fontScale=Lt,bs.textScaleFactor=P.textScaleFactor);const Ts=me.name==="globe",Rs=g.tilePixelRatio*Et/24,Es=(tr=g.overscaling,g.zoom>18&&tr>2&&(tr>>=1),Math.max(fr/(512*tr),1)*Ot.get("symbol-spacing")),Ws=Ot.get("text-padding")*g.tilePixelRatio,ls=Ot.get("icon-padding")*g.tilePixelRatio,Ps=Pr(Ot.get("text-max-angle")),zs=Ot.get("icon-rotation-alignment")==="map"&&Ve!=="point",Ks=Es/2;var tr;g.hasAnyIconTextFit===!1&&Ee!=="none"&&(g.hasAnyIconTextFit=!0);const Ar=u.properties?+u.properties[ea]:null,ur=Ar&&g.elevationFeatureIdToIndex?g.elevationFeatureIdToIndex.get(Ar):65535,dr=(sr,Tr,zr)=>{if(Tr.x<0||Tr.x>=fr||Tr.y<0||Tr.y>=fr)return;let mn=null;if(Ts){const{x:Gr,y:Vn,z:$a}=me.projectTilePoint(Tr.x,Tr.y,zr);mn={anchor:new j1(Gr,Vn,$a,0,void 0),up:me.upVector(zr,Tr.x,Tr.y)}}(function(Gr,Vn,$a,Hn,Va,ca,Ho,hi,Za,Ui,Io,Lc,Lo,cl,Pl,dl,qd,Pc,ha,ah,yl,Xc,ih,Vd,Go,Eu,Qc,a9,IT,Dh,d0e,LT){const N1=Gr.addToLineVertexArray(Vn,Hn);let k1,pp,xp,yN,PT,ga,Jc,ul=0,yc=0,gp=0,Gm=0,Wm=-1,Km=-1;const Tx={};let i9=yx("");const Kg=$a?$a.anchor:Vn,DT=a9!=="none";let RT=0,nc=0;if(Za._unevaluatedLayout.getValue("text-radial-offset")===void 0){const vl=Za.layout.get("text-offset").evaluate(yl,{},Go);RT=vl[0]*Ic,nc=vl[1]*Ic}else RT=Za.layout.get("text-radial-offset").evaluate(yl,{},Go)*Ic,nc=Bye;if(Gr.allowVerticalPlacement&&Va.vertical){const vl=Va.vertical;if(Pl)ga=qye(vl),hi&&(Jc=qye(hi));else{const oh=Za.layout.get("text-rotate").evaluate(yl,{},Go)+90;xp=U7(Ui,Kg,Vn,Io,Lc,Lo,vl,cl,oh,dl,LT),hi&&(yN=U7(Ui,Kg,Vn,Io,Lc,Lo,hi,Pc,oh,null,d0e))}}if(ca){const vl=Za.layout.get("icon-rotate").evaluate(yl,{},Go),oh=Fye(ca,vl,ih,DT,Xc.iconScaleFactor),Rh=hi?Fye(hi,vl,ih,DT,Xc.iconScaleFactor):void 0;pp=U7(Ui,Kg,Vn,Io,Lc,Lo,ca,Pc,vl,null,Dh);const Ax=function(Yg,P6,OT,xbt,gbt,MPe,IPe,ybt,rUs,h0e){const LPe=Yg.layers[0],PPe=LPe.appearances;let FT=P6.length;if(OT&&(FT=Math.max(FT,OT.length)),PPe.length===0)return FT;const[vbt,bbt]=xbt.get("icon-size-scale-range"),_bt=ze(1,vbt,bbt);for(const d9 of PPe)if(d9.hasLayoutProperty("icon-image")){const DPe=LPe.getAppearanceValueAndResolveTokens(d9,"icon-image",MPe,IPe,h0e);if(DPe){const RPe=Yg.getResolvedImageFromTokens(DPe);if(RPe){const OPe=d9.hasLayoutProperty("icon-size")?d9.getUnevaluatedLayoutProperty("icon-size"):gbt._values["icon-size"],wbt=v6(RPe,hN(Yg.zoom,OPe,Yg.worldview,h0e),OPe,IPe,Yg.zoom,MPe,Yg.pixelRatio,_bt,Yg.worldview,h0e),FPe=ybt.get(wbt.iconPrimary.toString());FPe&&(FT=Math.max(FT,qvt(FPe)))}}}return FT}(Gr,oh,Rh,Za.layout,Za._unevaluatedLayout,yl,Go,Gr.iconAtlasPositions,0,Vd);ul=4*Ax;const o9=Za.layout.get("icon-size").evaluate(yl,{},Go,Vd),l9=Xc.compositeIconSizes?Xc.compositeIconSizes[0].evaluate(yl,{},Go,Vd):0,u0e=Xc.compositeIconSizes?Xc.compositeIconSizes[1].evaluate(yl,{},Go,Vd):0,c9=Uye(Gr.layerIds[0],Gr.iconSizeData,o9,Xc.iconScaleFactor,l9,u0e);Gr.addSymbols(Gr.icon,oh,c9,ah,ha,yl,void 0,$a,Vn,N1.lineStartIndex,N1.lineLength,-1,Vd,Go,Eu,Qc,Gr.symbolInstances.length,Ax),Wm=Gr.icon.placedSymbolArray.length-1,Rh&&(yc=4*Ax,Gr.addSymbols(Gr.icon,Rh,c9,ah,ha,yl,Hm.vertical,$a,Vn,N1.lineStartIndex,N1.lineLength,-1,Vd,Go,Eu,Qc,Gr.symbolInstances.length,Ax),Km=Gr.icon.placedSymbolArray.length-1)}for(const vl in Va.horizontal){const oh=vl,Rh=Va.horizontal[oh];k1||(i9=yx(Rh.text),Pl?PT=qye(Rh):k1=U7(Ui,Kg,Vn,Io,Lc,Lo,Rh,cl,Za.layout.get("text-rotate").evaluate(yl,{},Go),dl,LT));const Ax=Rh.positionedLines.length===1;if(gp+=uLe(Gr,$a,Vn,Rh,Ho,Za,Pl,yl,dl,N1,Va.vertical?Hm.horizontal:Hm.horizontalOnly,Ax?Wvt(Va.horizontal):[oh],Tx,Wm,Xc,Vd,Go,Gr.symbolInstances.length,Eu),Ax)break}Va.vertical&&(Gm+=uLe(Gr,$a,Vn,Va.vertical,Ho,Za,Pl,yl,dl,N1,Hm.vertical,["vertical"],Tx,Km,Xc,Vd,Go,Gr.symbolInstances.length,Eu));let ql=-1;const vc=(vl,oh)=>vl?Math.max(vl,oh):oh;ql=vc(PT,ql),ql=vc(ga,ql),ql=vc(Jc,ql);const Ex=ql>-1?1:0;Gr.glyphOffsetArray.length>=65535&&Rr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),yl.sortKey!==void 0&&Gr.addToSortKeyRanges(Gr.symbolInstances.length,yl.sortKey),Gr.symbolInstances.emplaceBack(Vn.x,Vn.y,Kg.x,Kg.y,Kg.z,Tx.right>=0?Tx.right:-1,Tx.center>=0?Tx.center:-1,Tx.left>=0?Tx.left:-1,Tx.vertical>=0?Tx.vertical:-1,Wm,Km,i9,k1!==void 0?k1:Gr.collisionBoxArray.length,k1!==void 0?k1+1:Gr.collisionBoxArray.length,xp!==void 0?xp:Gr.collisionBoxArray.length,xp!==void 0?xp+1:Gr.collisionBoxArray.length,pp!==void 0?pp:Gr.collisionBoxArray.length,pp!==void 0?pp+1:Gr.collisionBoxArray.length,yN||Gr.collisionBoxArray.length,yN?yN+1:Gr.collisionBoxArray.length,Io,gp,Gm,ul,yc,Ex,0,RT,nc,ql,0,DT?1:0,IT)})(g,Tr,mn,sr,f,_,M,C,g.layers[0],g.collisionBoxArray,u.index,u.sourceLayerIndex,g.index,Ws,Qe,W,0,ls,zs,Fe,u,P,ee,se,ae,ge,we,Ee,ur,at,ut,ft)};if(Ve==="line")for(const sr of _7(u.geometry,0,0,fr,fr)){const Tr=Uvt(sr,Es,Ps,f.vertical||Pt,_,24,Rs,g.overscaling,fr);for(const zr of Tr)Pt&&s1t(g,Pt.text,Ks,zr)||dr(sr,zr,ae)}else if(Ve==="line-center"){for(const sr of u.geometry)if(sr.length>1){const Tr=$vt(sr,Ps,f.vertical||Pt,_,24,Rs);Tr&&dr(sr,Tr,ae)}}else if(u.type==="Polygon")for(const sr of t6(u.geometry,0)){const Tr=Hvt(sr,16);dr(sr[0],new j1(Tr.x,Tr.y,0,0,void 0),ae)}else if(u.type==="LineString")for(const sr of u.geometry)dr(sr,new j1(sr[0].x,sr[0].y,0,0,void 0),ae);else if(u.type==="Point")for(const sr of u.geometry)for(const Tr of sr)dr([Tr],new j1(Tr.x,Tr.y,0,0,void 0),ae)}const $ye=255,mN=$ye*w1;function uLe(g,u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe){const Ve=rLe(0,_,U,M,P,B,C,g.allowVerticalPlacement,void 0,ge.textScaleFactor),at=M.layout.get("text-size").evaluate(B,{},Ee),ut=ge.compositeTextSizes?ge.compositeTextSizes[0].evaluate(B,{},Ee):0,ft=ge.compositeTextSizes?ge.compositeTextSizes[1].evaluate(B,{},Ee):0,Bt=Uye(g.layerIds[0],g.textSizeData,at,ge.textScaleFactor,ut,ft);g.addSymbols(g.text,Ve,Bt,U,P,B,ee,u,f,W.lineStartIndex,W.lineLength,me,we,Ee,Qe,!1,Fe,Ve.length);for(const Et of se)ae[Et]=g.text.placedSymbolArray.length-1;return 4*Ve.length}function Uye(g,u,f,_,C,M){const P=u;let B=null;return P.kind==="source"?(B=[w1*f*_],B[0]>mN&&Rr(`${g}: Value for "text-size" is >= ${$ye}. Reduce your "text-size".`)):P.kind==="composite"&&(B=[w1*C*_,w1*M*_],(B[0]>mN||B[1]>mN)&&Rr(`${g}: Value for "text-size" is >= ${$ye}. Reduce your "text-size".`)),B}function $7(g){for(const u in g)return g[u];return null}function U7(g,u,f,_,C,M,P,B,U,W,ee){let se,ae,me,ge;if(se=ee?ee.top:P.top,ae=ee?ee.bottom:P.bottom,me=ee?ee.left:P.left,ge=ee?ee.right:P.right,Aye(P)&&P.collisionPadding){const we=P.collisionPadding;me-=we[0],se-=we[1],ge+=we[2],ae+=we[3]}if(U){const we=new ss(me,se),Ee=new ss(ge,se),Fe=new ss(me,ae),Qe=new ss(ge,ae),Ve=Pr(U);let at=new ss(0,0);W&&(at=new ss(W[0],W[1])),we._rotateAround(Ve,at),Ee._rotateAround(Ve,at),Fe._rotateAround(Ve,at),Qe._rotateAround(Ve,at),me=Math.min(we.x,Ee.x,Fe.x,Qe.x),ge=Math.max(we.x,Ee.x,Fe.x,Qe.x),se=Math.min(we.y,Ee.y,Fe.y,Qe.y),ae=Math.max(we.y,Ee.y,Fe.y,Qe.y)}return g.emplaceBack(u.x,u.y,u.z,f.x,f.y,me,se,ge,ae,B,_,C,M),g.length-1}function qye(g){Aye(g)&&g.collisionPadding&&(g.top-=g.collisionPadding[1],g.bottom+=g.collisionPadding[3]);const u=g.bottom-g.top;return u>0?Math.max(10,u):null}function s1t(g,u,f,_){const C=g.compareText;if(u in C){const M=C[u];for(let P=M.length-1;P>=0;P--)if(_.dist(M[P])Ve&&(at(ft,Ts,Et,Ot,hs,bs),at(Ts,Bt,hs,bs,Lt,Pt))}at(se,ae,_,M,C,M),at(ae,me,C,M,C,P),at(me,ge,C,P,_,P),at(ge,se,_,P,_,M),we-=Ve,Ee-=Ve,Fe+=Ve,Qe+=Ve;const ut=1/Math.max(Fe-we,Qe-Ee);return{scale:ut,x:we*ut,y:Ee*ut,x2:Fe*ut,y2:Qe*ut,projection:u}}function mLe(g,{x:u,y:f},_=0){return new ss(((u-_)*g.scale-g.x)*fr,(f*g.scale-g.y)*fr)}const r1t=b(new Float32Array(16));class T_{constructor(u){this.spec=u,this.name=u.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(u,f){return{x:0,y:0,z:0}}unproject(u,f){return new qt(0,0)}projectTilePoint(u,f,_){return{x:u,y:f,z:0}}locationPoint(u,f,_,C=!0){return u._coordinatePoint(u.locationCoordinate(f,_),C)}pixelsPerMeter(u,f){return Qt(1,u)*f}pixelSpaceConversion(u,f,_){return 1}farthestPixelDistance(u){return hLe(u,u.pixelsPerMeter)}pointCoordinate(u,f,_,C){const M=u.horizonLineFromTop(!1),P=new ss(f,Math.max(M,_));return u.rayIntersectionCoordinate(u.pointRayIntersection(P,C))}pointCoordinate3D(u,f,_){const C=new ss(f,_);if(u.elevation)return u.elevation.pointCoordinate(C);{const M=this.pointCoordinate(u,C.x,C.y,0);return[M.x,M.y,M.z]}}isPointAboveHorizon(u,f){if(u.elevation&&u.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(u,f.x,f.y);const _=u.horizonLineFromTop();return f.y<_}createInversionMatrix(u,f){return r1t}createTileMatrix(u,f,_){let C,M,P;const B=_.canonical,U=b(new Float64Array(16));if(this.isReprojectedInTileSpace){const W=fN(B,this);C=1,M=W.x+_.wrap*W.scale,P=W.y,A(U,U,[C/W.scale,C/W.scale,u.pixelsPerMeter/f])}else C=f/u.zoomScale(B.z),M=(B.x+Math.pow(2,B.z)*_.wrap)*C,P=B.y*C;return T(U,U,[M,P,0]),A(U,U,[C/fr,C/fr,1]),U}upVector(u,f,_){return[0,0,1]}upVectorScale(u,f,_){return{metersToTile:1}}}class n1t extends T_{constructor(u){super(u),this.range=[4,7],this.center=u.center||[-96,37.5];const[f,_]=this.parallels=u.parallels||[29.5,45.5],C=Math.sin(Pr(f));this.n=(C+Math.sin(Pr(_)))/2,this.c=1+C*(2*this.n-C),this.r0=Math.sqrt(this.c)/this.n}project(u,f){const{n:_,c:C,r0:M}=this,P=Pr(u-this.center[0]),B=Pr(f),U=Math.sqrt(C-2*_*Math.sin(B))/_;return{x:U*Math.sin(P*_),y:U*Math.cos(P*_)-M,z:0}}unproject(u,f){const{n:_,c:C,r0:M}=this,P=M+f;let B=Math.atan2(u,Math.abs(P))*Math.sign(P);P*_<0&&(B-=Math.PI*Math.sign(u)*Math.sign(P));const U=Pr(this.center[0])*_;B=gt(B,-Math.PI-U,Math.PI-U);const W=ze(Qn(B/_)+this.center[0],-180,180),ee=Math.asin(ze((C-(u*u+P*P)*_*_)/(2*_),-1,1)),se=ze(Qn(ee),-85.051129,ks);return new qt(W,se)}}const b6=1.340264,_6=-.081106,w6=893e-6,j6=.003796,q7=Math.sqrt(3)/2;class a1t extends T_{project(u,f){f=f/180*Math.PI,u=u/180*Math.PI;const _=Math.asin(q7*Math.sin(f)),C=_*_,M=C*C*C;return{x:.5*(u*Math.cos(_)/(q7*(b6+3*_6*C+M*(7*w6+9*j6*C)))/Math.PI+.5),y:1-.5*(_*(b6+_6*C+M*(w6+j6*C))/Math.PI+1),z:0}}unproject(u,f){u=(2*u-.5)*Math.PI;let _=f=(2*(1-f)-1)*Math.PI,C=_*_,M=C*C*C;for(let ee,se,ae,me=0;me<12&&(se=_*(b6+_6*C+M*(w6+j6*C))-f,ae=b6+3*_6*C+M*(7*w6+9*j6*C),ee=se/ae,_=ze(_-ee,-Math.PI/3,Math.PI/3),C=_*_,M=C*C*C,!(Math.abs(ee)<1e-12));++me);const P=q7*u*(b6+3*_6*C+M*(7*w6+9*j6*C))/Math.cos(_),B=Math.asin(Math.sin(_)/q7),U=ze(180*P/Math.PI,-180,180),W=ze(180*B/Math.PI,-85.051129,ks);return new qt(U,W)}}class i1t extends T_{constructor(u){super(u),this.wrap=!0,this.supportsWorldCopies=!0}project(u,f){return{x:.5+u/360,y:.5-f/360,z:0}}unproject(u,f){const _=360*(u-.5),C=ze(360*(.5-f),-85.051129,ks);return new qt(_,C)}}const kT=Math.PI/2;function V7(g){return Math.tan((kT+g)/2)}class o1t extends T_{constructor(u){super(u),this.center=u.center||[0,30];const[f,_]=this.parallels=u.parallels||[30,30];let C=Pr(f),M=Pr(_);this.southernCenter=C+M<0,this.southernCenter&&(C=-C,M=-M);const P=Math.cos(C),B=V7(C);this.n=C===M?Math.sin(C):Math.log(P/Math.cos(M))/Math.log(V7(M)/B),this.f=P*Math.pow(V7(C),this.n)/this.n}project(u,f){f=Pr(f),this.southernCenter&&(f=-f),u=Pr(u-this.center[0]);const _=1e-6,{n:C,f:M}=this;M>0?f<-kT+_&&(f=-kT+_):f>kT-_&&(f=kT-_);const P=M/Math.pow(V7(f),C);let B=P*Math.sin(C*u),U=M-P*Math.cos(C*u);return B=.5*(B/Math.PI+.5),U=.5*(U/Math.PI+.5),{x:B,y:this.southernCenter?U:1-U,z:0}}unproject(u,f){u=(2*u-.5)*Math.PI,this.southernCenter&&(f=1-f),f=(2*(1-f)-.5)*Math.PI;const{n:_,f:C}=this,M=C-f,P=Math.sign(M),B=Math.sign(_)*Math.sqrt(u*u+M*M);let U=Math.atan2(u,Math.abs(M))*P;M*_<0&&(U-=Math.PI*Math.sign(u)*P);const W=ze(Qn(U/_)+this.center[0],-180,180),ee=ze(Qn(2*Math.atan(Math.pow(C/B,1/_))-kT),-85.051129,ks);return new qt(W,this.southernCenter?-ee:ee)}}class fLe extends T_{constructor(u){super(u),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(u,f){return{x:Os(u),y:Hs(f),z:0}}unproject(u,f){const _=Ht(u),C=us(f);return new qt(_,C)}}const pLe=Pr(ks);class l1t extends T_{project(u,f){const _=(f=Pr(f))*f,C=_*_;return{x:.5*((u=Pr(u))*(.8707-.131979*_+C*(C*(.003971*_-.001529*C)-.013791))/Math.PI+.5),y:1-.5*(f*(1.007226+_*(.015085+C*(.028874*_-.044475-.005916*C)))/Math.PI+1),z:0}}unproject(u,f){u=(2*u-.5)*Math.PI;let _=f=(2*(1-f)-1)*Math.PI,C=25,M=0,P=_*_;do{P=_*_;const W=P*P;M=(_*(1.007226+P*(.015085+W*(.028874*P-.044475-.005916*W)))-f)/(1.007226+P*(.045255+W*(.259866*P-.311325-.005916*11*W))),_=ze(_-M,-pLe,pLe)}while(Math.abs(M)>1e-6&&--C>0);P=_*_;const B=ze(Qn(u/(.8707+P*(P*(P*P*P*(.003971-.001529*P)-.013791)-.131979))),-180,180),U=Qn(_);return new qt(B,U)}}const xLe=Pr(ks);class c1t extends T_{project(u,f){f=Pr(f),u=Pr(u);const _=Math.cos(f),C=2/Math.PI,M=Math.acos(_*Math.cos(u/2)),P=Math.sin(M)/M,B=.5*(u*C+2*_*Math.sin(u/2)/P)||0,U=.5*(f+Math.sin(f)/P)||0;return{x:.5*(B/Math.PI+.5),y:1-.5*(U/Math.PI+1),z:0}}unproject(u,f){let _=u=(2*u-.5)*Math.PI,C=f=(2*(1-f)-1)*Math.PI,M=25;const P=1e-6;let B=0,U=0;do{const W=Math.cos(C),ee=Math.sin(C),se=2*ee*W,ae=ee*ee,me=W*W,ge=Math.cos(_/2),we=Math.sin(_/2),Ee=2*ge*we,Fe=we*we,Qe=1-me*ge*ge,Ve=Qe?1/Qe:0,at=Qe?Math.acos(W*ge)*Math.sqrt(1/Qe):0,ut=.5*(2*at*W*we+2*_/Math.PI)-u,ft=.5*(at*ee+C)-f,Bt=.5*Ve*(me*Fe+at*W*ge*ae)+1/Math.PI,Et=Ve*(Ee*se/4-at*ee*we),Ot=.125*Ve*(se*we-at*ee*me*Ee),Lt=.5*Ve*(ae*ge+at*Fe*W)+.5,Pt=Et*Ot-Lt*Bt;B=(ft*Et-ut*Lt)/Pt,U=(ut*Ot-ft*Bt)/Pt,_=ze(_-B,-Math.PI,Math.PI),C=ze(C-U,-xLe,xLe)}while((Math.abs(B)>P||Math.abs(U)>P)&&--M>0);return new qt(Qn(_),Qn(C))}}class gLe extends T_{constructor(u){super(u),this.center=u.center||[0,0],this.parallels=u.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Pr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(u,f){const{scale:_,cosPhi:C}=this;return{x:Pr(u)*C*_+.5,y:-Math.sin(Pr(f))/C*_+.5,z:0}}unproject(u,f){const{scale:_,cosPhi:C}=this,M=-(f-.5)/_,P=ze(Qn((u-.5)/_)/C,-180,180),B=Math.asin(ze(M*C,-1,1)),U=ze(Qn(B),-85.051129,ks);return new qt(P,U)}}class d1t extends fLe{constructor(u){super(u),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(u,f,_){const C=KP(u,f,_);return et(C,C,YP(d0(_))),{x:C[0],y:C[1],z:C[2]}}locationPoint(u,f,_){const C=St(f.lat,f.lng),M=Le([],C),P=_?u._centerAltitude+_:u.elevation?u.elevation.getAtPointOrZero(u.locationCoordinate(f),u._centerAltitude):u._centerAltitude;Ue(C,C,M,Qt(1,0)*fr*P);const B=b(new Float64Array(16));return S(B,u.pixelMatrix,u.globeMatrix),et(C,C,B),new ss(C[0],C[1])}pixelsPerMeter(u,f){return Qt(1,0)*f}pixelSpaceConversion(u,f,_){const C=Qt(1,u)*f,M=hn(Qt(1,45)*f,C,_);return this.pixelsPerMeter(u,f)/M}createTileMatrix(u,f,_){const C=Oge(d0(_.canonical));return S(new Float64Array(16),u.globeMatrix,C)}createInversionMatrix(u,f){const{center:_}=u,C=YP(d0(f));return D(C,C,Pr(_.lng)),I(C,C,Pr(_.lat)),A(C,C,[u._pixelsPerMercatorPixel,u._pixelsPerMercatorPixel,1]),Float32Array.from(C)}pointCoordinate(u,f,_,C){return LAe(u,f,_,!0)||new Br(0,0)}pointCoordinate3D(u,f,_){const C=this.pointCoordinate(u,f,_,0);return[C.x,C.y,C.z]}isPointAboveHorizon(u,f){return!LAe(u,f.x,f.y,!1)}farthestPixelDistance(u){const f=function(C,M){const P=C.cameraToCenterDistance,B=C._centerAltitude*M,U=C._camera,W=C._camera.forward(),ee=ne([],be([],W,-P),[0,0,B]),se=C.worldSize/(2*Math.PI),ae=[0,0,-se],me=C.width/C.height,ge=Math.tan(C.fovAboveCenter),we=be([],U.up(),ge),Ee=be([],U.right(),ge*me),Fe=Le([],ne([],ne([],W,we),Ee)),Qe=[];let Ve;if(new _a(ee,Fe).closestPointOnSphere(ae,se,Qe)){const at=ne([],Qe,ae),ut=We([],at,ee);Ve=Math.cos(C.fovAboveCenter)*re(ut)}else{const at=We([],ee,ae),ut=We([],ae,ee);Le(ut,ut);const ft=re(at)-se;Ve=Math.sqrt(ft*(ft+2*se));const Bt=Math.acos(Ve/(se+ft))-Math.acos(Ie(W,ut));Ve*=Math.cos(Bt)}return 1.01*Ve}(u,this.pixelsPerMeter(u.center.lat,u.worldSize)),_=v1(u.zoom);if(_>0){const C=hLe(u,Qt(1,u.center.lat)*u.worldSize),M=u.worldSize/(2*Math.PI),P=Math.max(u.width,u.height)/u.worldSize*Math.PI;return hn(f,C+M*(1-Math.cos(P)),Math.pow(_,10))}return f}upVector(u,f,_){return KP(f,_,u,1)}upVectorScale(u){return{metersToTile:r7(a7(d0(u)))}}}function yLe(g){const u=g.parallels,f=!!u&&Math.abs(u[0]+u[1])<.01;switch(g.name){case"mercator":return new fLe(g);case"equirectangular":return new i1t(g);case"naturalEarth":return new l1t(g);case"equalEarth":return new a1t(g);case"winkelTripel":return new c1t(g);case"albers":return f?new gLe(g):new n1t(g);case"lambertConformalConic":return f?new gLe(g):new o1t(g);case"globe":return new d1t(g)}throw new Error(`Invalid projection name: ${g.name}`)}class u1t{constructor(u,f){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=f,this.appearances=u;const _=u.map(C=>function(M){if(!M.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const P=M.condition.expression;return{featureDependent:!a1(P),stateDependent:!o_(P),zoomDependent:!vx(P,["zoom"]),pitchDependent:!vx(P,["pitch"]),brightnessDependent:!vx(P,["brightness","measure-light"]),worldviewDependent:!vx(P,["worldview"])}}(C));this.anyFeatureDependent=_.some(C=>C.featureDependent),this.anyStateDependent=_.some(C=>C.stateDependent)}update(u,f){const _=this.lastParams,C=!_||_.zoom!==u.zoom||_.pitch!==(u.pitch||0)||_.brightness!==(u.brightness||0)||_.worldview!==u.worldview;this.lastParams={zoom:u.zoom,pitch:u.pitch||0,brightness:u.brightness||0,worldview:u.worldview};const M=f&&this.anyStateDependent;if(!C&&!M&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!M){const P=this.evaluateAllFeatures(u);return P===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=P,{kind:"all-features",appearanceIndex:P})}return{kind:"per-feature"}}evaluateAllFeatures(u){for(let f=0;f{for(let C=0;CP-B),M=new Map;for(const P of C){const B=_.get(P);M.set(P,new Bi(B))}return f&&(this.cachedBatchIndices=C,this.cachedBatchSegments=M),{batchIndices:C,batchSegments:M}}snapshotSymbolVertexData(u,f){const _=u*CT;return this.layoutVertexArray.uint16.slice(_,_+f*CT)}restoreSymbolVertexData(u,f){this.layoutVertexArray.uint16.set(f,u*CT)}updateSymbolVertexData(u,f,_,C,M,P,B,U,W,ee,se,ae,me){const ge=this.layoutVertexArray.uint16,we=u*CT;ge[we]=f,ge[we+1]=_,ge[we+2]=C,ge[we+3]=M,ge[we+4]=P,ge[we+5]=B,ge[we+6]=U,ge[we+7]=W,ge[we+8]=ee,ge[we+9]=se,ge[we+10]=ae,ge[we+11]=me}upload(u,f,_,C,M,P){this.isEmpty()||(_&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,fvt.members,!!P),this.indexBuffer=u.createIndexBuffer(this.indexArray,f),this.dynamicLayoutVertexBuffer=u.createVertexBuffer(this.dynamicLayoutVertexArray,xvt.members,!0),this.opacityVertexBuffer=u.createVertexBuffer(this.opacityVertexArray,m1t,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=u.createVertexBuffer(this.iconTransitioningVertexArray,bvt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=u.createVertexBuffer(this.globeExtVertexArray,pvt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||M)&&(this.zOffsetVertexBuffer=u.createVertexBuffer(this.zOffsetVertexArray,gvt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=u.createVertexBuffer(this.orientationVertexArray,vvt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=u.createVertexBuffer(this.featureIdArray,yvt.members,!1))),(_||C)&&(this.programConfigurations.upload(u),this.uboBinder&&this.uboBinder.upload(u)))}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())}}Dr(Vye,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class Hye{constructor(u,f,_){this.layoutVertexArray=new u,this.layoutAttributes=f,this.indexArray=new _,this.segments=new Bi,this.collisionVertexArray=new J2,this.collisionVertexArrayExt=new $g}upload(u){this.layoutVertexBuffer=u.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=u.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=u.createVertexBuffer(this.collisionVertexArray,_vt.members,!0),this.collisionVertexBufferExt=u.createVertexBuffer(this.collisionVertexArrayExt,wvt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Dr(Hye,"CollisionBuffers");class Hg{constructor(u){this.collisionBoxArray=u.collisionBoxArray,this.zoom=u.zoom,this.overscaling=u.overscaling,this.layers=u.layers,this.layerIds=this.layers.map(P=>P.fqid),this.index=u.index,this.pixelRatio=u.pixelRatio,this.sourceLayerIndex=u.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=b([]),this.placementViewportMatrix=b([]);const f=this.layers[0]._unevaluatedLayout._values;this.worldview=u.worldview,this.localizable=u.localizable,this.maxUniformBufferBindings=u.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=u.maxUniformBlockSizeDwords,this.disableSymbolUBO=u.disableSymbolUBO,this.textSizeData=hN(this.zoom,f["text-size"],this.worldview,u.availableImages),this.iconSizeData=hN(this.zoom,f["icon-size"],this.worldview,u.availableImages);const _=this.layers[0].layout,C=_.get("symbol-sort-key"),M=_.get("symbol-z-order");this.lut=u.lut,this.canOverlap=_.get("text-allow-overlap")||_.get("icon-allow-overlap")||_.get("text-ignore-placement")||_.get("icon-ignore-placement"),this.sortFeaturesByKey=M!=="viewport-y"&&C.constantOr(1)!==void 0,this.sortFeaturesByY=(M==="viewport-y"||M==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=_.get("text-writing-mode").map(P=>Hm[P]),this.stateDependentLayerIds=this.layers.filter(P=>P.isStateDependent()).map(P=>P.id),this.sourceID=u.sourceID,this.projection=u.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(u){const f=this.layers[0].getAppearances();if(!f||f.length===0)return!1;const _=Array.isArray(u)?u:[u];return f.some(C=>_.some(M=>C.hasLayoutProperty(M)))}getAppearanceFeatureData(u){return this.featureAppearanceData.get(u)}createArrays(){this.text=new Vye(new Me(this.layers,{zoom:this.zoom,lut:this.lut},u=>u.startsWith("text")||u.startsWith("symbol"))),this.icon=new Vye(new Me(this.layers,{zoom:this.zoom,lut:this.lut},u=>u.startsWith("icon")||u.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new Sye(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new Sye(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new Xz,this.lineVertexArray=new sN,this.symbolInstances=new Zz}calculateGlyphDependencies(u,f,_,C,M){for(const P of u){const B=P.codePointAt(0);if(B===void 0)break;if(f[B]=!0,C&&M&&B<=65535){const U=f6[P];U&&(f[U.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(u,f,_,C,M,P,B){if(!u.hasLayoutProperty("icon-size"))return B*P;let U=1;const W=u.getUnevaluatedLayoutProperty("icon-size"),ee=hN(this.zoom,W,this.worldview,M),se=jT(ee,f);if(ee.kind!=="constant"&&ee.kind!=="camera"||(U=se.uSize),ee.kind==="composite"){const{minZoom:ae,maxZoom:me}=ee,ge=W.possiblyEvaluate(new ui(ae,{worldview:this.worldview}),C),we=W.possiblyEvaluate(new ui(me,{worldview:this.worldview}),C),Ee=ge.evaluate(_,{},C,M);U=Ee+(we.evaluate(_,{},C,M)-Ee)*se.uSizeT}return ee.kind==="source"&&(U=W.possiblyEvaluate(new ui(this.zoom,{worldview:this.worldview}),C).evaluate(_,{},C,M)),U*P}updateFootprints(u,f){}updateReplacement(u,f){if(f.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=f.updateTime;const _=f.getReplacementRegionsForTile(u.toUnwrapped(),!0);return!p7(this.activeReplacements,_)&&(this.activeReplacements=_,!0)}getResolvedImageFromTokens(u){return typeof u=="string"?Lh.build(u):u}populate(u,f,_,C){const M=this.layers[0],P=M.layout,B=this.projection.name==="globe",U=P.get("text-font"),W=P.get("text-field"),ee=P.get("icon-image"),[se,ae]=P.get("icon-size-scale-range"),me=ze(f.scaleFactor||1,se,ae),[ge,we]=P.get("text-size-scale-range"),Ee=ze(f.scaleFactor||1,ge,we),Fe=(W.value.kind!=="constant"||W.value.value instanceof iu&&!W.value.value.isEmpty()||W.value.value.toString().length>0)&&(U.value.kind!=="constant"||U.value.value.length>0),Qe=ee.value.kind!=="constant"||!!ee.value.value||Object.keys(ee.parameters).length>0,Ve=this.hasAnyAppearanceLayoutProperty("icon-image"),at=P.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!Fe&&!Qe&&!Ve)return;const ut=f.iconDependencies,ft=f.glyphDependencies,Bt=f.availableImages,Et=new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),Ot=Lt=>{const Pt=Lt.id.toString();ut.has(Pt)?ut.get(Pt).push(Lt):ut.set(Pt,[Lt])};for(const Lt of u){const{feature:Pt,id:hs,index:bs,sourceLayerIndex:Ts}=Lt,Rs=M._featureFilter.needGeometry,Es=la(Pt,Rs);if(!M._featureFilter.filter(Et,Es,_))continue;if(Rs||(Es.geometry=pn(Pt,_,C)),B&&Pt.type!==1&&_.z<=5){const ur=Es.geometry,dr=.98078528056,sr=(Tr,zr)=>Ie(KP(Tr.x,Tr.y,_,1),KP(zr.x,zr.y,_,1)){if(!ur.getLayoutProperty("icon-image"))return;const dr=this.getCombinedIconPrimary(ur,Ps,Es,_,Bt,tr,me);dr&&Ot(dr)}),Ws){const ur=U.evaluate(Es,{},_).join(","),dr=P.get("text-rotation-alignment")==="map"&&P.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Hm.vertical)>=0;for(const sr of Ws.sections)if(sr.image){const Tr=sr.image.getPrimary().scaleSelf(this.pixelRatio*Ee),zr=Tr.id.toString(),mn=ut.get(zr)||[];mn.push(Tr),ut.set(zr,mn)}else{const Tr=xP(Ws.toString()),zr=sr.fontStack||ur,mn=ft[zr]=ft[zr]||{};this.calculateGlyphDependencies(sr.text,mn,dr,this.allowVerticalPlacement,Tr)}}}if(P.get("symbol-placement")==="line"&&(this.features=function(Lt){const Pt={},hs={},bs=[];let Ts=0;function Rs(Ps){bs.push(Lt[Ps]),Ts++}function Es(Ps,zs,Ks){const tr=hs[Ps];return delete hs[Ps],hs[zs]=tr,bs[tr].geometry[0].pop(),bs[tr].geometry[0]=bs[tr].geometry[0].concat(Ks[0]),tr}function Ws(Ps,zs,Ks){const tr=Pt[zs];return delete Pt[zs],Pt[Ps]=tr,bs[tr].geometry[0].shift(),bs[tr].geometry[0]=Ks[0].concat(bs[tr].geometry[0]),tr}function ls(Ps,zs,Ks){const tr=Ks?zs[0][zs[0].length-1]:zs[0][0];return`${Ps}:${tr.x}:${tr.y}`}for(let Ps=0;PsPs.geometry)}(this.features)),P.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",f.elevationFeatures){!this.elevationFeatures&&f.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Lt of f.elevationFeatures)this.elevationFeatureIdToIndex.set(Lt.id,this.elevationFeatures.length),this.elevationFeatures.push(Lt)}}else P.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Lt,Pt)=>Lt.sortKey-Pt.sortKey)}getCombinedIconPrimary(u,f,_,C,M,P,B){let U,W;if(u.hasLayoutProperty("icon-image")){const ee=f.getAppearanceValueAndResolveTokens(u,"icon-image",_,C,M);U=this.getResolvedImageFromTokens(ee)}else{const ee=f.getValueAndResolveTokens("icon-image",_,C,M);U=this.getResolvedImageFromTokens(ee)}if(U){const ee=u.hasLayoutProperty("icon-size")?u.getUnevaluatedLayoutProperty("icon-size"):f._unevaluatedLayout._values["icon-size"];W=v6(U,hN(this.zoom,ee,this.worldview,M),ee,C,this.zoom,P,this.pixelRatio,B,this.worldview,M).iconPrimary}return W}updateSymbolInstanceIconVertices(u,f,_,C,M,P){const{canonical:B,availableImages:U,globalProperties:W,layer:ee,iconScaleFactor:se,featureState:ae,layoutIconOffset:me,layoutIconSize:ge,layoutIconRotate:we}=P;if(u.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(f.activeAppearanceIndex===_)return{vertexOffsetDelta:u.numIconVertices,hasChanges:!1};const Ee=_>=0?ee.appearances[_]:null;if(Ee){const Fe=this.getCombinedIconPrimary(Ee,ee,C,B,U,{sortKey:void 0,text:void 0,icon:null,index:u.featureIndex,sourceLayerIndex:u.featureIndex,geometry:[],properties:f.properties,type:"Point",id:f.id},se);if(!Fe)return{vertexOffsetDelta:0,hasChanges:!1};const Qe=Fe.toString(),Ve=this.iconAtlasPositions&&this.iconAtlasPositions.get(Qe);if(Ve){const{appearanceIconOffset:at,appearanceIconRotate:ut}=aLe(Ee,ee,C,B,me,we,ge,se);let ft=P7(Ve,void 0,at,ee.layout.get("icon-anchor").evaluate(C,ae,B));const Bt=Ve.sdf,Et=ee.layout.get("icon-text-fit").constantOr("none");Et!=="none"&&f.textShaping&&f.iconTextFitPadding&&f.fontScale&&(ft=Mye(ft,f.textShaping,Et,f.iconTextFitPadding,at,f.fontScale));const Ot=this.calculateEffectiveAppearanceIconSize(Ee,W.zoom,C,B,U,se,ge),Lt=0,Pt=1+(Math.min(mN,Math.round(Ot*w1))<<1),hs=Fye(ft,ut,Bt,Et!=="none",se);f.isUsingAppearanceIconVertexData||(f.isUsingAppearanceIconVertexData=!0,f.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(M,u.numIconVertices));const bs=Math.floor(u.numIconVertices/4),Ts=Math.min(hs.length,bs);let Rs=M;for(let Ws=0;Ws0||u.numVerticalGlyphVertices>0;if(!at)return{vertexOffsetDelta:at?u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices:0,hasChanges:!1};if(f.activeAppearanceIndex===_)return{vertexOffsetDelta:u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices,hasChanges:!1};const ut=_>=0?U.appearances[_]:null;if(ut&&f.textShaping){const{appearanceTextOffset:ft,appearanceTextRotate:Bt,appearanceTextSize:Et}=iLe(ut,U,C,B,ae,ge,me);f.fontScale=dLe(Et,f.textScaleFactor);const Ot=ut.getUnevaluatedLayoutProperty("text-size");let Lt=this.textSizeData,Pt=Fe,hs=Qe;ut.hasLayoutProperty("text-size")&&(Lt=hN(this.zoom,Ot,this.worldview,Ve),Pt=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,hs=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const bs=f.textShaping.bottom-ae[1],Ts=f.textShaping.left-ae[0],Rs=f.textShaping.right-ae[0];f.textShaping.top=ft[1]+(f.textShaping.top-ae[1]),f.textShaping.bottom=ft[1]+bs,f.textShaping.left=ft[0]+Ts,f.textShaping.right=ft[0]+Rs;const Es=rLe(0,f.textShaping,ft,U,!1,C,ee,this.allowVerticalPlacement,Bt),Ws=Et&&Lt.kind==="composite"?Ot.possiblyEvaluate(new ui(Pt,{}),B).evaluate(C,se,B):we,ls=Et&&Lt.kind==="composite"?Ot.possiblyEvaluate(new ui(hs,{}),B).evaluate(C,se,B):Ee,Ps=Uye(ut.name,Lt,Et,W,Ws,ls),zs=Array.isArray(Ps)?Ps[1]:Et,Ks=0,tr=1+(Math.min(mN,Math.round(zs*w1))<<1);f.isUsingAppearanceTextVertexData||(f.isUsingAppearanceTextVertexData=!0,f.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(M,u.numHorizontalGlyphVertices+u.numVerticalGlyphVertices));for(let Ar=0;Ar0){const W=new Set(Object.keys(u).map(ee=>{const se=Number(ee);return!isNaN(se)&&Number.isSafeInteger(se)&&String(se)===ee?se:ee}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(W,M[0],f,U,_,u,B),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(W,M[0],f,U,_,u,B)}}}updateRoadElevation(u){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let f=!1;const _=Us(u),C=1/_;let M=!1,P=!1;for(let B=0;B0||ae>0,Ee=me>0,Fe=this.elevationFeatures[U.elevationFeatureIndex];if(Fe){const Qe=new ss(U.tileAnchorX,U.tileAnchorY),Ve=.075+Fe.pointElevation(Qe);U.zOffset!==Ve&&(f=!0,U.zOffset=Ve),Ve!==0&&(this.hasAnyZOffset=!0);const at=Fe.computeSlopeNormal(Qe,C),ut=cs(Xe(),le(0,0,1),at);it(W,W,ut),it(ee,ee,ut),W[2]*=_,ee[2]*=_,W[0]===1&&W[1]===0&&W[2]===0&&ee[0]===0&&ee[1]===1&&ee[2]===0||(M=M||we,P=P||Ee)}if(we&&(H7(this.text.orientationVertexArray,se,W,ee),H7(this.text.orientationVertexArray,ae,W,ee)),Ee){const{placedIconSymbolIndex:Qe,verticalPlacedIconSymbolIndex:Ve}=U;Qe>=0&&H7(this.icon.orientationVertexArray,me,W,ee),Ve>=0&&H7(this.icon.orientationVertexArray,ge,W,ee)}}M||(this.text.orientationVertexArray=void 0),P||(this.icon.orientationVertexArray=void 0),f&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const u=(M,P,B)=>{_+=P,_>M.length&&M.resize(_);for(let U=-P;U<0;U++)M.emplace(U+_,B)},f=(M,P,B)=>{C+=P,C>M.length&&M.resize(C);for(let U=-P;U<0;U++)M.emplace(U+C,B)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let _=0,C=0;for(let M=0;M0;if((B>0||U>0)&&(u(this.text.zOffsetVertexArray,B,ee),u(this.text.zOffsetVertexArray,U,ee)),se){const{placedIconSymbolIndex:ae,verticalPlacedIconSymbolIndex:me}=P;ae>=0&&f(this.icon.zOffsetVertexArray,W,ee),me>=0&&f(this.icon.zOffsetVertexArray,P.numVerticalIconVertices,ee)}}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(u,f,_,C,M){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(u),this.iconCollisionBox.upload(u)),this.text.upload(u,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(P=>P.appearances&&P.appearances.length>0)),this.icon.upload(u,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(u,f,_,C,M,P=!1){const B={hasLayoutChanges:!1,hasUboChanges:!1};if(!u||!_||!this.featureAppearanceData)return B;const U=f||{},W=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,ee=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!W&&!ee)return B;const se=this.layers[0],ae=se.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===se.appearancesVersion||(this.featureAppearances=new u1t(se.appearances,se.appearancesVersion));const me=this.featureAppearances.update(C,P);if(me.kind==="no-changes")return B;let ge=1,we=0,Ee=!1,Fe=!1;if(W){const[ft,Bt]=ae.get("icon-size-scale-range");ge=ze(1,ft,Bt)}let Qe=1,Ve=0,at=!1;if(ee){const[ft,Bt]=ae.get("text-size-scale-range");Qe=ze(1,ft,Bt)}const ut=new Map;if(M&&_)for(const ft of _){const Bt=M.getImage(ft,se.scope);if(Bt){const Et=new Sf(ft.toString());ut.set(Et.toString(),Bt)}}for(let ft=0;ftRs.isActive({globals:C,feature:Pt,canonical:u,featureState:Lt})):-1;hs=Ts>=0?Ts:-1}const bs=Et.activeAppearanceIndex!==hs;if(ee){const Ts=ae.get("text-size"),Rs=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Es=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Ws={canonical:u,layer:se,featureState:Lt,availableImages:_,textScaleFactor:Qe,imageMap:ut,layoutTextOffset:ae.get("text-offset").evaluate(Pt,Lt,u).map(Ps=>Ps*Ic),layoutTextSize:Ts.evaluate(Pt,Lt,u),layoutTextRotate:ae.get("text-rotate").evaluate(Pt,Lt,u),layoutMinZoomSize:Ts.evaluate(Pt,{zoom:Rs},u),layoutMaxZoomSize:Ts.evaluate(Pt,{zoom:Es},u),layoutTextSizeMinZoom:Rs,layoutTextSizeMaxZoom:Es},ls=this.updateSymbolInstanceTextVertices(Bt,Et,hs,Pt,Ve,Ws);Ve+=ls.vertexOffsetDelta,at=at||ls.hasChanges}if(W){const Ts={canonical:u,layer:se,featureState:Lt,availableImages:_,globalProperties:C,iconScaleFactor:ge,layoutIconOffset:ae.get("icon-offset").evaluate(Pt,Lt,u),layoutIconSize:ae.get("icon-size").evaluate(Pt,Lt,u,_),layoutIconRotate:ae.get("icon-rotate").evaluate(Pt,Lt,u)},Rs=this.updateSymbolInstanceIconVertices(Bt,Et,hs,Pt,we,Ts);we+=Rs.vertexOffsetDelta,Ee=Ee||Rs.hasChanges}if(bs){const Ts=Bt.featureIndex,Rs=C?C.brightness:null,Es=Lt||{},Ws=hs>=0?se.appearances[hs]:null;this.text.uboBinder&&(this.text.uboBinder.layer=se,Fe=this.text.uboBinder.updateFeaturePaintForAppearance(Ts,Pt,Es,u,_,Rs,Ws)||Fe),this.icon.uboBinder&&(this.icon.uboBinder.layer=se,Fe=this.icon.uboBinder.updateFeaturePaintForAppearance(Ts,Pt,Es,u,_,Rs,Ws)||Fe)}Et.activeAppearanceIndex=hs}return Ee&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),at&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Ee||at,hasUboChanges:Fe}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=yLe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(u,f){const _=this.lineVertexArray.length;if(u.segment!==void 0)for(const{x:C,y:M}of f)this.lineVertexArray.emplaceBack(C,M);return{lineStartIndex:_,lineLength:this.lineVertexArray.length-_}}addSymbols(u,f,_,C,M,P,B,U,W,ee,se,ae,me,ge,we,Ee,Fe,Qe){const Ve=u.indexArray,at=u.layoutVertexArray,ut=u.globeExtVertexArray,ft=Qe,Bt=u.uboBinder?u.uboBinder.getCurrentBatchIndex():void 0,Et=u.segments.prepareSegment(4*ft,at,Ve,this.canOverlap?P.sortKey:void 0,Bt),Ot=this.glyphOffsetArray.length,Lt=Et.vertexLength,Pt=this.allowVerticalPlacement&&B===Hm.vertical?Math.PI/2:0,hs=P.text&&P.text.sections;let bs=at.length,Ts=-1;for(let Ws=0;Ws=0)){const Ws=4*Rs;for(let ls=0;ls=0?f.rightJustifiedTextSymbolIndex:f.centerJustifiedTextSymbolIndex>=0?f.centerJustifiedTextSymbolIndex:f.leftJustifiedTextSymbolIndex>=0?f.leftJustifiedTextSymbolIndex:f.verticalPlacedTextSymbolIndex>=0?f.verticalPlacedTextSymbolIndex:C),P=Iye(this.textSizeData,u,M)/Ic;return this.tilePixelRatio*P}getSymbolInstanceIconSize(u,f,_){const C=this.icon.placedSymbolArray.get(_),M=Iye(this.iconSizeData,u,C);return this.tilePixelRatio*M}_commitDebugCollisionVertexUpdate(u,f,_,C){u.emplaceBack(f,-_,-_,C),u.emplaceBack(f,_,-_,C),u.emplaceBack(f,_,_,C),u.emplaceBack(f,-_,_,C)}_updateTextDebugCollisionBoxes(u,f,_,C,M,P,B){for(let U=C;U0}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(u,f){const _=u.placedSymbolArray.get(f),C=_.vertexStartIndex+4*_.numGlyphs;for(let M=_.vertexStartIndex;MC[B]-C[U]||M[U]-M[B]),P}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let u=0;uthis.symbolInstances.get(f).zOffset-this.symbolInstances.get(u).zOffset)}addToSortKeyRanges(u,f){const _=this.sortKeyRanges[this.sortKeyRanges.length-1];_&&_.sortKey===f?_.symbolInstanceEnd=u+1:this.sortKeyRanges.push({sortKey:f,symbolInstanceStart:u,symbolInstanceEnd:u+1})}sortFeatures(u){if(this.sortFeaturesByY&&this.sortedAngle!==u)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(u),this.sortedAngle=u,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const f of this.symbolInstanceIndexes){const _=this.symbolInstances.get(f);this.featureSortOrder.push(_.featureIndex);const{rightJustifiedTextSymbolIndex:C,centerJustifiedTextSymbolIndex:M,leftJustifiedTextSymbolIndex:P,verticalPlacedTextSymbolIndex:B,placedIconSymbolIndex:U,verticalPlacedIconSymbolIndex:W}=_;C>=0&&this.addIndicesForPlacedSymbol(this.text,C),M>=0&&M!==C&&this.addIndicesForPlacedSymbol(this.text,M),P>=0&&P!==M&&P!==C&&this.addIndicesForPlacedSymbol(this.text,P),B>=0&&this.addIndicesForPlacedSymbol(this.text,B),U>=0&&this.addIndicesForPlacedSymbol(this.icon,U),W>=0&&this.addIndicesForPlacedSymbol(this.icon,W)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(u,f){const _=(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 C of this.symbolsByBatch.values())for(const M of C){const P=this.symbolInstances.get(M.index);M.rotatedY=0|Math.round(u*P.tileAnchorX+f*P.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let C=0;CM.rotatedY-P.rotatedY||P.featureIndex-M.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(u,f){for(const _ of u){const C=_.batchIndex;if(C===void 0)continue;const M=f.get(C);if(!M){_.primitiveOffset=this.text.indexArray.length,_.primitiveLength=0;continue}_.primitiveOffset=this.text.indexArray.length;const P=this.text.indexArray.length;for(const{index:B}of M){const U=this.symbolInstances.get(B),{rightJustifiedTextSymbolIndex:W,centerJustifiedTextSymbolIndex:ee,leftJustifiedTextSymbolIndex:se,verticalPlacedTextSymbolIndex:ae}=U;W>=0&&this.addIndicesForPlacedSymbol(this.text,W),ee>=0&&ee!==W&&this.addIndicesForPlacedSymbol(this.text,ee),se>=0&&se!==ee&&se!==W&&this.addIndicesForPlacedSymbol(this.text,se),ae>=0&&this.addIndicesForPlacedSymbol(this.text,ae)}_.primitiveLength=this.text.indexArray.length-P}}rebuildIconSegmentIndices(u,f){for(const _ of u){const C=_.batchIndex;if(C===void 0)continue;const M=f.get(C);if(!M){_.primitiveOffset=this.icon.indexArray.length,_.primitiveLength=0;continue}_.primitiveOffset=this.icon.indexArray.length;const P=this.icon.indexArray.length;for(const{index:B}of M){const U=this.symbolInstances.get(B),{placedIconSymbolIndex:W,verticalPlacedIconSymbolIndex:ee}=U;W>=0&&this.addIndicesForPlacedSymbol(this.icon,W),ee>=0&&this.addIndicesForPlacedSymbol(this.icon,ee)}_.primitiveLength=this.icon.indexArray.length-P}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const u=Math.sin(this.sortedAngle),f=Math.cos(this.sortedAngle),_=this.getOrCreateSortedSymbolsByBatch(u,f),C=Array.from(_.keys()).sort((M,P)=>M-P);for(const M of C){const P=_.get(M);for(const{index:B}of P){const U=this.symbolInstances.get(B);this.featureSortOrder.push(U.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),_),this.rebuildIconSegmentIndices(this.icon.segments.get(),_),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(u){const f=this.symbolInstances.get(this.text.symbolInstanceIndices[u]).elevationFeatureIndex;let _;return this.elevationFeatures&&f_ in g?String(g[_]):"")}let bLe,_Le,Gye;Dr(Hg,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Hg.addDynamicAttributes=ST;class wLe{constructor(u){this.type=u.property.overrides?u.property.overrides.runtimeType:Lg,this.defaultValue=u}evaluate(u){if(u.formattedSection){const f=this.defaultValue.property.overrides;if(f&&f.hasOverride(u.formattedSection))return f.getOverride(u.formattedSection)}return u.feature&&u.featureState?this.defaultValue.evaluate(u.feature,u.featureState):this.defaultValue.property.specification.default}eachChild(u){this.defaultValue.isConstant()||u(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Dr(wLe,"FormatSectionOverride",{omit:["defaultValue"]});const Wye=()=>Gye||(Gye={layout:bLe||(bLe=new jo({"symbol-placement":new nr(Yt.layout_symbol["symbol-placement"]),"symbol-spacing":new nr(Yt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new nr(Yt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Qs(Yt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new nr(Yt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new nr(Yt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new nr(Yt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new nr(Yt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new nr(Yt.layout_symbol["icon-ignore-placement"]),"icon-optional":new nr(Yt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new nr(Yt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Qs(Yt.layout_symbol["icon-size"]),"icon-size-scale-range":new nr(Yt.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Qs(Yt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Qs(Yt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Qs(Yt.layout_symbol["icon-image"]),"icon-image-use-theme":new nr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Qs(Yt.layout_symbol["icon-rotate"]),"icon-padding":new nr(Yt.layout_symbol["icon-padding"]),"icon-keep-upright":new nr(Yt.layout_symbol["icon-keep-upright"]),"icon-offset":new Qs(Yt.layout_symbol["icon-offset"]),"icon-anchor":new Qs(Yt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new nr(Yt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new nr(Yt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new nr(Yt.layout_symbol["text-rotation-alignment"]),"text-field":new Qs(Yt.layout_symbol["text-field"]),"text-font":new Qs(Yt.layout_symbol["text-font"]),"text-size":new Qs(Yt.layout_symbol["text-size"]),"text-size-scale-range":new nr(Yt.layout_symbol["text-size-scale-range"]),"text-max-width":new Qs(Yt.layout_symbol["text-max-width"]),"text-line-height":new Qs(Yt.layout_symbol["text-line-height"]),"text-letter-spacing":new Qs(Yt.layout_symbol["text-letter-spacing"]),"text-justify":new Qs(Yt.layout_symbol["text-justify"]),"text-radial-offset":new Qs(Yt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new nr(Yt.layout_symbol["text-variable-anchor"]),"text-anchor":new Qs(Yt.layout_symbol["text-anchor"]),"text-max-angle":new nr(Yt.layout_symbol["text-max-angle"]),"text-writing-mode":new nr(Yt.layout_symbol["text-writing-mode"]),"text-rotate":new Qs(Yt.layout_symbol["text-rotate"]),"text-padding":new nr(Yt.layout_symbol["text-padding"]),"text-keep-upright":new nr(Yt.layout_symbol["text-keep-upright"]),"text-transform":new Qs(Yt.layout_symbol["text-transform"]),"text-offset":new Qs(Yt.layout_symbol["text-offset"]),"text-allow-overlap":new nr(Yt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new nr(Yt.layout_symbol["text-ignore-placement"]),"text-optional":new nr(Yt.layout_symbol["text-optional"]),visibility:new nr(Yt.layout_symbol.visibility)})),paint:_Le||(_Le=new jo({"icon-opacity":new Qs(Yt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Qs(Yt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Qs(Yt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Qs(Yt.paint_symbol["text-emissive-strength"]),"icon-color":new Qs(Yt.paint_symbol["icon-color"]),"icon-halo-color":new Qs(Yt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Qs(Yt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Qs(Yt.paint_symbol["icon-halo-blur"]),"icon-translate":new nr(Yt.paint_symbol["icon-translate"]),"icon-translate-anchor":new nr(Yt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new nr(Yt.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Qs(Yt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Qs(Yt.paint_symbol["text-occlusion-opacity"]),"text-color":new Qs(Yt.paint_symbol["text-color"],{runtimeType:rh,getOverride:g=>g.textColor,hasOverride:g=>!!g.textColor}),"text-halo-color":new Qs(Yt.paint_symbol["text-halo-color"]),"text-halo-width":new Qs(Yt.paint_symbol["text-halo-width"]),"text-halo-blur":new Qs(Yt.paint_symbol["text-halo-blur"]),"text-translate":new nr(Yt.paint_symbol["text-translate"]),"text-translate-anchor":new nr(Yt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new nr(Yt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new nr(Yt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new nr(Yt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new nr(Yt.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Qs(Yt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"})}))},Gye);class G7 extends Tu{constructor(u,f,_,C){super(u,Wye(),f,_,C,u.layout?u.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=b([]),this.hasOcclusionOpacityProperties=u.paint!==void 0&&("icon-occlusion-opacity"in u.paint||"text-occlusion-opacity"in u.paint)}_handleSpecialPaintPropertyUpdate(u){u!=="icon-occlusion-opacity"&&u!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(u,f){super.recalculate(u,f),this.appearances&&this.appearances.forEach(C=>{C.recalculate(u,f,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const _=this.layout.get("text-writing-mode");if(_){const C=[];for(const M of _)C.indexOf(M)<0&&C.push(M);this.layout._values["text-writing-mode"]=C}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(u,f,_,C){return this._saturation===u&&this._contrast===f&&this._brightnessMin===_&&this._brightnessMax===C||(this._colorAdjustmentMatrix=function(M,P,B,U){M=eo(M),P=bi(P);const W=v(),ee=M/3,se=1-2*ee,ae=[se,ee,ee,0,ee,se,ee,0,ee,ee,se,0,0,0,0,1],me=.5-.5*P,ge=U-B;return S(W,[ge,0,0,0,0,ge,0,0,0,0,ge,0,B,B,B,1],[P,0,0,0,0,P,0,0,0,0,P,0,me,me,me,1]),S(W,W,ae),W}(u,f,_,C),this._saturation=u,this._contrast=f,this._brightnessMin=_,this._brightnessMax=C),this._colorAdjustmentMatrix}getValueAndResolveTokens(u,f,_,C){const M=this.layout.get(u).evaluate(f,{},_,C),P=this._unevaluatedLayout._values[u];return P.isDataDriven()||$2(P.value)||!M?M:vLe(f.properties,M)}getAppearanceValueAndResolveTokens(u,f,_,C,M){const P=u.getLayoutProperty(f);if(!P)return;const B=P.evaluate(_,{},C,M),U=u.getUnevaluatedLayoutProperties()._values[f];return U.isDataDriven()||$2(U.value)||!B||typeof B!="string"?B:vLe(_.properties,B)}createBucket(u){return new Hg(u)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const u of Wye().paint.overridableProperties){if(!G7.hasPaintOverride(this.layout,u))continue;const f=this.paint.get(u),_=new wLe(f),C=new U5(_,f.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let M=null;M=f.value.kind==="constant"||f.value.kind==="source"?new m_("source",C):new o1("composite",C,f.value.zoomStops,f.value.interpolationType),this.paint._values[u]=new u1(f.property,M,f.parameters)}}_handleOverridablePaintPropertyUpdate(u,f,_){return!(!this.layout||f.isDataDriven()||_.isDataDriven())&&G7.hasPaintOverride(this.layout,u)}static hasPaintOverride(u,f){const _=u.get("text-field"),C=Wye().paint.properties[f];let M=!1;const P=B=>{for(const U of B)if(C.overrides&&C.overrides.hasOverride(U))return void(M=!0)};if(_.value.kind==="constant"&&_.value.value instanceof iu)P(_.value.value.sections);else if(_.value.kind==="source"){const B=W=>{M||(W instanceof $r&&xl(W.value)===g2?P(W.value.sections):W instanceof e1?P(W.sections):W.eachChild(B))},U=_.value;U._styleExpression&&B(U._styleExpression.expression)}return M}getProgramIds(){return["symbol"]}getDefaultProgramParams(u,f,_){return{config:new je(this,{zoom:f,lut:_}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let jLe,NLe,kLe,SLe;var W7=Ta([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function K7(g,u,f,_,C,M,P,B){const U=[g,u,1,f,_,1,C,M,1],W=[P,B,1],ee=x([],U),[se,ae,me]=fe(W,W,ee);return y(U,U,[se,0,0,0,ae,0,0,0,me])}function CLe(g,u,f,_,C,M,P,B){const U=function(W,ee,se,ae,me,ge,we,Ee){const Fe=K7(0,0,1,0,1,1,0,1),Qe=K7(W,ee,se,ae,me,ge,we,Ee);return y(Qe,Qe,x([],Fe))}(g,u,f,_,C,M,P,B);return[U[2]/U[8]/fr,U[5]/U[8]/fr]}function Y7(g){return[g[0],Math.min(Math.max(g[1],-85.051129),ks)]}class TLe extends Qv{constructor(u,f,_,C){super(),this.id=u,this.dispatcher=_,this.coordinates=f.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(C),this.options=f,this._dirty=!1}load(u,f){if(this._loaded=f||!1,this.fire(new Pm("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return u&&(this.coordinates=u),this._loaded=!0,void this._finishLoading();this._imageRequest=Eg(this.map._requestManager.transformRequest(this.url,Zv.Image),(_,C)=>{this._imageRequest=null,this._loaded=!0,_?this.fire(new Zy(_)):C&&(this.image=C,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,u&&(this.coordinates=u),this._finishLoading())})}loaded(){return this._loaded}updateImage(u){return u.url?(this._imageRequest&&u.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=u.url,this.load(u.coordinates,this._loaded),this):this}setTexture(u){if(!(u.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new u6(this.map.painter.context,u.handle),this.width=u.dimensions[0],this.height=u.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Pm("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(u){this.map=u,this.load()}onRemove(u){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof u6||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(u){if(this.coordinates=u,this._boundsArray=void 0,this._unsupportedCoords=!1,!u.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let f=u[0][1],_=u[0][1];for(const M of u)M[1]>_&&(_=M[1]),M[1]ks?this.onNorthPole=!0:C<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const M=u.map(Br.fromLngLat);this.tileID=function(P){let B=1/0,U=1/0,W=-1/0,ee=-1/0;for(const we of P)B=Math.min(B,we.x),U=Math.min(U,we.y),W=Math.max(W,we.x),ee=Math.max(ee,we.y);const se=Math.max(W-B,ee-U),ae=Math.max(0,Math.floor(-Math.log2(se))),me=Math.pow(2,ae);let ge=Math.floor((B+W)/2*me);return ge>1&&(ge-=1),new oN(ae,ge,Math.floor((U+ee)/2*me))}(M),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Pm("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof u6||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(u){for(const Ee in this.tiles){const Fe=this.tiles[Ee];Fe.state!=="loaded"&&(Fe.state="loaded",Fe.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const f=fN(new oN(0,0,0),this.map.transform.projection),_=[f.projection.project(this.coordinates[0][0],this.coordinates[0][1]),f.projection.project(this.coordinates[1][0],this.coordinates[1][1]),f.projection.project(this.coordinates[2][0],this.coordinates[2][1]),f.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Ee){const Fe=Ee[1].x-Ee[0].x,Qe=Ee[1].y-Ee[0].y,Ve=Ee[2].x-Ee[1].x,at=Ee[2].y-Ee[1].y,ut=Ee[3].x-Ee[2].x,ft=Ee[3].y-Ee[2].y,Bt=Ee[0].x-Ee[3].x,Et=Ee[0].y-Ee[3].y,Ot=Fe*at-Ve*Qe,Lt=Ve*ft-ut*at,Pt=ut*Et-Bt*ft,hs=Bt*Qe-Fe*Et;return Ot>0&&Lt>0&&Pt>0&&hs>0||Ot<0&&Lt<0&&Pt<0&&hs<0}(_))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const C=fN(this.tileID,this.map.transform.projection),[M,P,B,U]=this.coordinates.map(Ee=>{const Fe=C.projection.project(Ee[0],Ee[1]);return mLe(C,Fe)._round()});this.perspectiveTransform=CLe(M.x,M.y,P.x,P.y,B.x,B.y,U.x,U.y);const W=this._boundsArray=new $d;W.emplaceBack(M.x,M.y,0,0),W.emplaceBack(P.x,P.y,fr,0),W.emplaceBack(U.x,U.y,0,fr),W.emplaceBack(B.x,B.y,fr,fr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=u.createVertexBuffer(W,W7.members),this.boundsSegments=Bi.simpleSegment(0,0,4,2);const ee=[],se=function(Ee){return[Y7(Ee[0]),Y7(Ee[1]),Y7(Ee[2]),Y7(Ee[3])]}(this.coordinates),[ae,me,ge,we]=function(Ee){let Fe=Ee[0][0],Qe=Fe,Ve=Ee[0][1],at=Ve;for(let ut=1;utQe&&(Qe=Ee[ut][0]),Ee[ut][1]at&&(at=Ee[ut][1]);return[Fe,Ve,Qe-Fe,at-Ve]}(se);{const Ee=new $d,[Fe,Qe,Ve,at]=function(Es){let Ws=Es[0].x,ls=Ws,Ps=Es[0].y,zs=Ps;for(let Ks=1;Ksls&&(ls=Es[Ks].x),Es[Ks].yzs&&(zs=Es[Ks].y);return[Ws,Ps,ls-Ws,zs-Ps]}(_),ut=Es=>[(Es.x-Fe)/Ve,(Es.y-Qe)/at],[ft,Bt,Et,Ot]=_.map(ut),Lt=function(Es,Ws,ls,Ps,zs,Ks,tr,Ar){const ur=K7(0,0,1,0,1,1,0,1);return y(ur,ur,x([],K7(Es,Ws,ls,Ps,zs,Ks,tr,Ar)))}(ft[0],ft[1],Bt[0],Bt[1],Et[0],Et[1],Ot[0],Ot[1]);this.elevatedGlobePerspectiveTransform=CLe(ft[0],ft[1],Bt[0],Bt[1],Et[0],Et[1],Ot[0],Ot[1]);const Pt=(Es,Ws)=>{ee.push(Es.lng);const ls=Math.round((Es.lng-ae)/ge*fr),Ps=Math.round((Es.lat-me)/we*fr),zs=ut(Ws),Ks=fe([],[zs[0],zs[1],1],Lt),tr=Math.round(Ks[0]/Ks[2]*fr),Ar=Math.round(Ks[1]/Ks[2]*fr);Ee.emplaceBack(ls,Ps,tr,Ar)},hs=_[3].x-_[0].x,bs=_[3].y-_[0].y,Ts=_[2].x-_[1].x,Rs=_[2].y-_[1].y;for(let Es=0;Es<65;Es++){const Ws=Es/64,ls=[_[0].x+Ws*hs,_[0].y+Ws*bs],Ps=[_[1].x+Ws*Ts,_[1].y+Ws*Rs],zs=Ps[0]-ls[0],Ks=Ps[1]-ls[1];for(let tr=0;tr<65;tr++){const Ar=tr/64,ur={x:ls[0]+zs*Ar,y:ls[1]+Ks*Ar};Pt(f.projection.unproject(ur.x,ur.y),ur)}}this.elevatedGlobeVertexBuffer=u.createVertexBuffer(Ee,W7.members)}{this.maxLongitudeTriangleSize=0;let Ee=[],Fe=new ll;const Qe=(Ve,at,ut)=>{Fe.emplaceBack(Ve,at,ut);const ft=ee[Ve],Bt=ee[at],Et=ee[ut],Ot=Math.min(Math.min(ft,Bt),Et),Lt=Math.max(Math.max(ft,Bt),Et)-Ot;Lt>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Lt),Ee.push(Ot+Lt/2)};for(let Ve=0;Ve<64;Ve++)for(let at=0;at<64;at++){const ut=65*Ve+at,ft=ut+1,Bt=ut+65,Et=Bt+1;Qe(ut,Bt,ft),Qe(ft,Bt,Et)}[Ee,Fe]=function(Ve,at){const ut=Array.from({length:Ve.length},(Et,Ot)=>Ot);ut.sort((Et,Ot)=>Ve[Et]-Ve[Ot]);const ft=[],Bt=new ll;for(let Et=0;Et{P.segments.push({vertexOffset:0,primitiveOffset:se,vertexLength:f.segments[0].vertexLength,primitiveLength:ae,sortKey:void 0,vaos:{}})},U=.51*this.maxLongitudeTriangleSize;if(Math.abs(_[0]-C)<=U){const se=il(_,0,_.length,C+U);return se===_.length||B(se,Ji(_,se+1,_.length,C+360-U)-se),P}C<_[0]&&(C+=360);const W=Ji(_,0,_.length,C-U);if(W===_.length)return B(0,_.length),P;B(0,W-0);const ee=il(_,W+1,_.length,C+U);return ee!==_.length&&B(ee,_.length-ee),P}}const Kye=1024,p1t=(Math.pow(Kye,2)-1)/268170240;class ELe extends Tu{constructor(u,f,_,C){super(u,{layout:kLe||(kLe=new jo({visibility:new nr(Yt.layout_raster.visibility)})),paint:SLe||(SLe=new jo({"raster-opacity":new nr(Yt.paint_raster["raster-opacity"]),"raster-color":new g_(Yt.paint_raster["raster-color"]),"raster-color-mix":new nr(Yt.paint_raster["raster-color-mix"]),"raster-color-range":new nr(Yt.paint_raster["raster-color-range"]),"raster-hue-rotate":new nr(Yt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new nr(Yt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new nr(Yt.paint_raster["raster-brightness-max"]),"raster-saturation":new nr(Yt.paint_raster["raster-saturation"]),"raster-contrast":new nr(Yt.paint_raster["raster-contrast"]),"raster-resampling":new nr(Yt.paint_raster["raster-resampling"]),"raster-fade-duration":new nr(Yt.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new nr(Yt.paint_raster["raster-emissive-strength"]),"raster-array-band":new nr(Yt.paint_raster["raster-array-band"]),"raster-elevation":new nr(Yt.paint_raster["raster-elevation"]),"raster-elevation-reference":new nr(Yt.paint_raster["raster-elevation-reference"]),"raster-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"})}))},f,_,C),this.updateColorRamp(),this._curRampRange=[NaN,NaN]}getProgramIds(){return["raster"]}hasColorMap(){return!!this._transitionablePaint._values["raster-color"].value.value}tileCoverLift(){return this.paint.get("raster-elevation")}isDraped(u){return!(u&&u._source instanceof TLe&&(u._source.onNorthPole||u._source.onSouthPole))&&this.paint.get("raster-elevation")===0}_handleSpecialPaintPropertyUpdate(u){u!=="raster-color"&&u!=="raster-color-range"||(this._curRampRange=[NaN,NaN],this.updateColorRamp())}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}updateColorRamp(u){if(!this.hasColorMap()||!this._curRampRange)return;const f=this._transitionablePaint._values["raster-color"].value.expression,[_,C]=u||this._transitionablePaint._values["raster-color-range"].value.expression.evaluate({zoom:0})||[NaN,NaN];isNaN(_)&&isNaN(C)||_===this._curRampRange[0]&&C===this._curRampRange[1]||(this.colorRamp=ZP({expression:f,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:_,end:C}],resolution:Kye}),this.colorRampTexture=null,this._curRampRange=[_,C])}is3D(u){return this.paint.get("raster-elevation")>0}}let ALe,MLe,ILe,LLe,PLe,DLe,RLe;class OLe extends Tu{constructor(u,f,_,C){super(u,{layout:ALe||(ALe=new jo({visibility:new nr(Yt["layout_raster-particle"].visibility)})),paint:MLe||(MLe=new jo({"raster-particle-array-band":new nr(Yt["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new nr(Yt["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new g_(Yt["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new nr(Yt["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new nr(Yt["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new nr(Yt["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new nr(Yt["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new nr(Yt["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"})}))},f,_,C),this._updateColorRamp(),this.lastInvalidatedAt=ju.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(u){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(u){return!1}_handleSpecialPaintPropertyUpdate(u){u!=="raster-particle-color"&&u!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),u==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const u=this._transitionablePaint._values["raster-particle-color"].value.expression,f=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=ZP({expression:u,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:f}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=ju.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class x1t extends Tu{constructor(u,f){super(u,{},f,null),this.implementation=u,u.slot&&(this.slot=u.slot)}is3D(u){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(u){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(u){this.implementation.onAdd&&this.implementation.onAdd(u,u.painter.context.gl)}onRemove(u){this.implementation.onRemove&&this.implementation.onRemove(u,u.painter.context.gl)}}function Yye(g,u,f){const _=[0,0,1],C=Je([]);return ns(C,C,f?-Pr(g)+Math.PI:Pr(g)),jt(C,C,-Pr(u)),it(_,_,C),Le(_,_)}class Z7{constructor(u,f,_,C){this.message=(u?`${u}: `:"")+_,C&&(this.identifier=C),f!=null&&f.__line__&&(this.line=f.__line__)}}function Zye(g,u){const f=g.indexOf("://")===-1;try{return new URL(g,f&&u?"http://example.com":void 0),!0}catch{return!1}}class FLe{constructor(u,f){this.feature=u,this.instancedDataOffset=f,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class BLe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new $P,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(u){const f=16*u,_=this.instancedDataArray.float32;let C=Math.floor(_[f+2]);const M=1.05*(_[f+2]-C);return C/=100,[_[f]%1*1.05,_[f+1]%1*1.05,M,C]}tileCoordinatesForInstance(u){const f=16*u,_=this.instancedDataArray.float32;let C=_[f+0];return C=C>fr?C-fr:C,new ss(Math.trunc(C),Math.trunc(_[f+1]))}translationForInstance(u){const f=16*u,_=this.instancedDataArray.float32;return[_[f+4],_[f+5],_[f+6]]}rotationScaleForInstance(u){const f=16*u,_=this.instancedDataArray.float32;return[_[f+7],_[f+8],_[f+9],_[f+10],_[f+11],_[f+12],_[f+13],_[f+14],_[f+15]]}transformForInstance(u){const f=16*u,_=this.instancedDataArray.float32;return[_[f+7],_[f+8],_[f+9],_[f+4],_[f+10],_[f+11],_[f+12],_[f+5],_[f+13],_[f+14],_[f+15],_[f+6],0,0,0,1]}}class Xye{constructor(u){this.zoom=u.zoom,this.canonical=u.canonical,this.overscaledZ=this.canonical.z+Math.log2(u.overscaling),this.layers=u.layers,this.layerIds=this.layers.map(f=>f.fqid),this.projection=u.projection,this.index=u.index,this.worldview=u.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(f=>f.isStateDependent()).map(f=>f.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=u.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(u,f){}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(u,f,_,C){this.tileToMeter=Us(_);const M=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const P=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?f.elevationFeatures:void 0;for(const{feature:B,id:U,index:W,sourceLayerIndex:ee}of u){const se=U??(B.properties&&B.properties.hasOwnProperty("id")?B.properties.id:void 0),ae=la(B,M);if(!this.layers[0]._featureFilter.filter(new ui(this.zoom,{worldview:this.worldview,activeFloors:f.activeFloors}),ae,_))continue;const me={id:se,sourceLayerIndex:ee,index:W,geometry:M?ae.geometry:pn(B,_,C),properties:B.properties,type:B.type,patterns:{}},ge=this.addFeature(me,me.geometry,ae,P,_);ge&&f.featureIndex.insert(B,me.geometry,W,ee,this.index,this.instancesPerModel[ge].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const u=this.layers[0].modelManager,f=this.layers[0].scope;let _=0;for(const C of this.modelUris){const M=u.getModel(C,f);if(!M)continue;const P=this.instancesPerModel[C];if(P){const B=.5*Be(M.aabb.max,M.aabb.min)*P.maxScale+P.maxXYTranslationDistance,U=Math.min(fr,Math.max(B/this.tileToMeter,256));_=Math.max(U,_)}}return _}update(u,f,_,C){for(const M in this.instancesPerModel){const P=this.instancesPerModel[M];for(const B in u)P.idToFeaturesIndex.hasOwnProperty(B)&&(this.evaluate(P.features[P.idToFeaturesIndex[B]],u[B],P,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let u=!1;for(const f in this.instancesPerModel){const _=this.instancesPerModel[f];for(const C of _.features){const M=this.layers[0],P=C.feature,B=this.canonical,U=M.paint.get("model-rotation").evaluate(P,{},B),W=M.paint.get("model-scale").evaluate(P,{},B),ee=M.paint.get("model-translation").evaluate(P,{},B);Ye(C.rotation,U)&&Ye(C.scale,W)&&Ye(C.translation,ee)||(this.evaluate(C,C.featureStates,_,!0),u=!0)}}return u}updateReplacement(u,f,_,C){if(f.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=f.updateTime;const M=f.getReplacementRegionsForTile(u.toUnwrapped(),!0);if(p7(this.activeReplacements,M))return!1;this.activeReplacements=M;let P=!1;for(const B in this.instancesPerModel){const U=this.instancesPerModel[B],W=U.instancedDataArray;for(const ee of U.features){const se=ee.instancedDataOffset,ae=ee.instancedDataCount;for(let me=0;mefr;we=Ee?we-fr:we;const Fe=Math.floor(we),Qe=Math.floor(W.float32[ge+1]);let Ve=!1;for(const at of this.activeReplacements)if(!bMe(at,_,x7.Model,C)&&!(at.min.x>Fe||Fe>at.max.x||at.min.y>Qe||Qe>at.max.y)&&(Ve=kMe(NMe(Fe,Qe,u.canonical,at.footprintTileId.canonical),at.footprint),Ve))break;W.float32[ge]=Ve?we+fr:we,P=P||Ve!==Ee}}}return P}isEmpty(){for(const u in this.instancesPerModel)if(this.instancesPerModel[u].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(u){if(!this.uploaded)for(const f in this.instancesPerModel){const _=this.instancesPerModel[f];_.instancedDataArray.length<0||_.instancedDataArray.length===0||(_.instancedDataBuffer?_.instancedDataBuffer.updateData(_.instancedDataArray):_.instancedDataBuffer=u.createVertexBuffer(_.instancedDataArray,D0t.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(u){for(const _ in this.instancesPerModel){const C=this.instancesPerModel[_];C.instancedDataArray.length!==0&&C.instancedDataBuffer&&C.instancedDataBuffer.destroy()}const f=this.layers[0].modelManager;if(u&&f&&this.modelUris&&this.modelsRequested)for(const _ of this.modelUris)f.removeModel(_,"",!0)}addFeature(u,f,_,C,M){const P=this.layers[0],B=P.layout.get("model-id"),U=P.layout.get("model-allow-density-reduction"),W=B.evaluate(_,{},this.canonical);if(!W)return Rr(`modelId is not evaluated for layer ${P.id} and it is not going to get rendered.`),W;(Zye(W,!1)||this.styleDefinedModelURLs[W]!==void 0)&&(this.modelUris.includes(W)||this.modelUris.push(W)),this.instancesPerModel[W]||(this.instancesPerModel[W]=new BLe);const ee=this.instancesPerModel[W],se=ee.instancedDataArray,ae=new FLe(_,se.length);let me;C&&(me=qi.getElevationFeature(u,C));for(const ge of f)for(const we of ge){if(we.x<0||we.x>=fr||we.y<0||we.y>=fr)continue;if(this.lookupDim!==0&&U){const Fe=(this.lookupDim-1)/fr,Qe=this.lookupDim*(we.y*Fe|0)+we.x*Fe|0;if(this.lookup){if(this.lookup[Qe]!==0)continue;this.lookup[Qe]=1}}this.instanceCount++;const Ee=se.length;if(se.resize(Ee+1),C){ee.instancesRoadElevation||(ee.instancesRoadElevation=[]);const Fe=me?me.pointElevation(new ss(we.x,we.y)):0;ee.instancesRoadElevation.push(Fe)}ee.instancesEvaluatedElevation.push(0),se.float32[16*Ee]=we.x,se.float32[16*Ee+1]=we.y}return ae.instancedDataCount=ee.instancedDataArray.length-ae.instancedDataOffset,ae.instancedDataCount>0&&(u.id&&(ee.idToFeaturesIndex[u.id]=ee.features.length),ee.features.push(ae),this.evaluate(ae,{},ee,!1)),W}getModelUris(){return this.modelUris}evaluate(u,f,_,C){const M=this.layers[0],P=u.feature,B=this.canonical,U=u.rotation=M.paint.get("model-rotation").evaluate(P,f,B),W=u.scale=M.paint.get("model-scale").evaluate(P,f,B),ee=u.translation=M.paint.get("model-translation").evaluate(P,f,B),se=Object.assign({},M.paint.get("model-color").evaluate(P,f,B));se.a=M.paint.get("model-color-mix-intensity").evaluate(P,f,B);const ae=[];this.maxVerticalOffset0?Math.sqrt(me):0;_.maxScale=Math.max(Math.max(_.maxScale,W[0]),Math.max(W[1],W[2])),_.maxXYTranslationDistance=Math.max(_.maxXYTranslationDistance,ge),this.maxScale=Math.max(Math.max(this.maxScale,W[0]),Math.max(W[1],W[2])),cIe(ae,U,W);const we=Math.round(100*se.a)+se.b/1.05;for(let Ee=0;Ee10?this.tileToMeter:Us(B,ut)),Ve[Qe+4]=ee[0],Ve[Qe+5]=ee[1],Ve[Qe+6]=ee[2]+(_.instancesRoadElevation?_.instancesRoadElevation[Fe]:0)+at,Ve[Qe+7]=ae[0],Ve[Qe+8]=ae[1],Ve[Qe+9]=ae[2],Ve[Qe+10]=ae[4],Ve[Qe+11]=ae[5],Ve[Qe+12]=ae[6],Ve[Qe+13]=ae[8],Ve[Qe+14]=ae[9],Ve[Qe+15]=ae[10],_.instancesEvaluatedElevation[Fe]=ee[2]}}}Dr(Xye,"ModelBucket",{omit:["layers"]}),Dr(BLe,"PerModelAttributes"),Dr(FLe,"ModelFeature");class TT{constructor(u,f,_){this._demTile=u,this._dem=this._demTile.dem,this._scale=f,this._offset=_}static create(u,f,_){const C=_||u.findDEMTileFor(f);if(!C||!C.dem)return;const M=C.dem,P=C.tileID,B=1<W.fqid),this.stateDependentLayerIds=this.layers.filter(W=>W.isStateDependent()).map(W=>W.id),this.modelTraits|=bT.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,C&&(this.modelTraits|=bT.HasMapboxMeshFeatures),M&&(this.modelTraits|=bT.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=P,this.worldview=U,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const W of f)this.nodesInfo.push(new qLe(W)),$Le(W,B.featureIndexArray.length,B.grid),B.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,B.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(u,f){for(const _ of this.getNodesInfo()){const C=_.node;C.footprint&&f.push({footprint:C.footprint,id:u})}}updateAppearances(u,f,_,C){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(u){const f=Object.keys(u).length!==0;if(f&&!this.stateDependentLayers.length)return;const _=f?this.stateDependentLayers:this.layers;if(!ta(u,this.states))for(const C of _)this.evaluate(C,u);this.states=structuredClone(u)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(u){if(!this.needsUpload)return;const f=this.getNodesInfo();for(const _ of f){const C=_.node;this.uploaded?this.updatePbrBuffer(C):pye(C,u,!0)}for(const _ of f)E7(_.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(u){let f=!1;if(!u.meshes)return f;for(const _ of u.meshes)_.pbrBuffer&&(_.pbrBuffer.updateData(_.featureArray),f=!0);return f}needsReEvaluation(u,f,_){const C=u.transform.projectionOptions,M=u.style.getBrightness(),P=this.brightness!==M;if(!this.uploaded||this.dirty||C.name!==this.projection.name||C6(_.paint.get("model-color").value,P)||C6(_.paint.get("model-color-mix-intensity").value,P)||C6(_.paint.get("model-roughness").value,P)||C6(_.paint.get("model-emissive-strength").value,P)||C6(_.paint.get("model-height-based-emissive-strength-multiplier").value,P)){this.projection=C,this.brightness=M;const B=this.getNodesInfo();for(const U of B)U.state=null;return!0}return!1}evaluateTransform(u,f){if(u.transform.zoom===this.zoom)return;this.zoom=u.transform.zoom;const _=this.getNodesInfo(),C=this.id.canonical;for(const M of _){const P=M.feature;M.evaluatedTranslation=f.paint.get("model-translation").evaluate(P,{},C),M.evaluatedScale=f.paint.get("model-scale").evaluate(P,{},C)}}evaluate(u,f){const _=this.getNodesInfo();for(const C of _){if(!C.node.meshes)continue;const M=C.feature,P=f&&f[M.id];if(ta(P,C.state))continue;C.state=structuredClone(P);const B=C.node.meshes&&C.node.meshes[0].featureData,U=C.evaluatedColor[2],W=C.evaluatedRMEA[2],ee=this.id.canonical;if(C.hasTranslucentParts=!1,B){for(let se=0;se=ft)continue;const Ws=Qye[Es],ls=Math.abs(Ws);ls>Pt&&(Lt=Ws,Pt=ls,hs=Rs,bs=Ts)}if(Pt>.1){const Ts=1-(ft+.5*Math.abs(hs*bs))/ge;let Rs=f._dem.get(Et,Bt)+Lt*Ts;const Es=f._dem.get(Et+hs,Bt+bs),Ws=f._dem.get(Et-hs,Bt-bs,!0);(Rs-Es)*(Rs-Ws)>0&&(Rs=(Es+Ws)/2),Qye[Ot]=f._dem.set(Et,Bt,Rs),pN[Ot]=ft}}}}}B&&(f._demTile.needsDEMTextureUpload=!0,f._dem._timestamp=ju.now())}setFilter(u){this.filter=u?eT(u):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(u=>this.filter.filter(new ui(this.id.overscaledZ,{worldview:this.worldview}),u.feature,this.id.canonical)):this.nodesInfo}destroy(){const u=this.getNodesInfo();for(const f of u)E7(f.node),xye(f.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(u,f){if(f.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=f.updateTime;const _=f.getReplacementRegionsForTile(u.toUnwrapped());for(const C of this.getNodesInfo()){const M=C.node.footprint;C.hiddenByReplacement=!!M&&!_.find(P=>P.footprint===M)}}getHeightAtTileCoord(u,f){const _=[],C=[0,0,0],M=b([]);for(const P of this.getNodesInfo()){const B=P.node.meshes[0],U=B.transformedAabb;if(uU.max[0]||f>U.max[1])continue;if(P.node.hidden===!0)return{height:1/0,maxHeight:P.feature.properties.height,hidden:!1,verticalScale:P.evaluatedScale[2]};N(M,P.node.globalMatrix),C[0]=u,C[1]=f,et(C,C,M);const W=(C[0]-B.aabb.min[0])/(B.aabb.max[0]-B.aabb.min[0])*dN|0,ee=Math.min(63,(C[1]-B.aabb.min[1])/(B.aabb.max[1]-B.aabb.min[1])*dN|0)*dN+Math.min(63,W),se=B.heightmap[ee];if(!(se<0&&P.node.footprint))return P.hiddenByReplacement?void 0:{height:se,maxHeight:P.feature.properties.height,hidden:!1,verticalScale:P.evaluatedScale[2]};if(P.node.footprint.grid.query(new ss(u,f),new ss(u,f),_),_.length>0)return{height:void 0,maxHeight:P.feature.properties.height,hidden:P.hiddenByReplacement,verticalScale:P.evaluatedScale[2]}}}}function C6(g,u){return g instanceof m_&&!g.isLightConstant&&u}function g1t(g,u,f,_,C,M,P,B){let U=(61440&u|(61440&u)>>4)>>8,W=(3840&u|(3840&u)>>4)>>4,ee=240&u|(240&u)>>4;f[3]>0&&(U=hn(U,255*f[0],f[3]),W=hn(W,255*f[1],f[3]),ee=hn(ee,255*f[2],f[3]));const se=U<<8|W,ae=ee<<8|Math.floor(255*_[3]),me=function(ft){const Bt=ze(ft,0,2);return Math.min(Math.round(.5*Bt*255),255)}(_[2])<<8|15*_[0]<<4|15*_[1],ge=ze(C[0],0,1),we=ze(C[1],0,1),Ee=ze(C[2],0,1),Fe=ze(C[3],0,1);let Qe,Ve,at,ut;if(ge!==we&&P!==M&&we!==ge){const ft=P-M;Ve=1/(ft*(we-ge)),at=-(M+ft*ge)/(ft*(we-ge));const Bt=ze(C[4],-1,1);ut=Math.pow(10,Bt),Qe=255*Ee<<8|255*Fe}else Qe=65535,Ve=0,at=1,ut=1;if(g.emplaceBack(se,ae,me,Qe,Ve,at,ut),B){const ft=B.length;B.clear();for(let Bt=0;Bt>16&65535,ee=M?U>>16&65535:65535&U,se=(15&ee)<8?15&ee:0,ae=g.evaluatedRMEA[se],me=g.evaluatedColor[se],ge=g.emissionHeightBasedParams[se];let we;if(B&&se===2&&_.lights&&(we=new lT,we.resize(10*_.lights.length)),g1t(P.featureArray,W,me,ae,ge,P.aabb.min[2],P.aabb.max[2],we),we&&B){B=!1;const Ee=_.meshes[_.lightMeshIndex];Ee.featureArray=we,Ee.featureArray._trim()}}P.featureArray._trim(),C++}}Dr(X7,"Tiled3dModelBucket",{omit:["layers"]}),Dr(qLe,"Tiled3dModelFeature");const v1t=["id","tile","layer","source","sourceLayer","state"];class xN{constructor(u,f,_,C,M){this.type="Feature",this._vectorTileFeature=u,this._z=f,this._x=_,this._y=C,this.properties=u?u.properties:{},this.id=M}clone(){const u=new xN(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(u.state=Object.assign({},this.state)),this.layer&&(u.layer=Object.assign({},this.layer)),this.source&&(u.source=this.source),this.sourceLayer&&(u.sourceLayer=this.sourceLayer),u}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(u){this._geometry=u}toJSON(){const u={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const f of v1t)this[f]!==void 0&&(u[f]=this[f]);return u}}class gN extends Qv{constructor(u,f,_,C){super(),this.id=u,this.type="model",this.models=[],this._options=f,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(u,f){return aIe(this.map._requestManager.transformRequest(u,Zv.Model).url,f)}async loadModel(u,f,_){try{const C=await this.loadGLTFFromURI(f.uri,_);if(_.aborted)return;const M=this._modelsInfo.get(u);if(!M)return;const P=yye(C),B=M.modelSpec,U=new dIe(u,B.uri,B.position,B.orientation,P);gN.applyModelSpecification(U,B),U.computeBoundsAndApplyParent(),this.models.push(U),M.model=U}catch(C){if(C instanceof Error&&C.name==="AbortError")return;const M=C instanceof Error?C.message:"Unknown error";this.fire(new Zy(new Error(`Could not load model ${u} from ${f.uri}: ${M}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const u=this._abortController.signal,f=[];for(const _ in this._options.models){const C=this._options.models[_],M=this._modelsInfo.get(_);if(M&&M.model){M.modelSpec=C;const P=M.model;P.position=C.position!=null?new qt(C.position[0],C.position[1]):new qt(0,0),P.orientation=C.orientation!=null?C.orientation:[0,0,0],gN.applyModelSpecification(P,C),P.computeBoundsAndApplyParent(),this.models.push(P)}else M?M.modelSpec=C:(this._modelsInfo.set(_,{modelSpec:C,model:null}),f.push(this.loadModel(_,C,u)))}f.length!==0?(await Promise.allSettled(f),u.aborted||this.fire(new Pm("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Pm("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(u,f){f.nodeOverrides&&gN.convertNodeOverrides(u,f.nodeOverrides),f.materialOverrides&&gN.convertMaterialOverrides(u,f.materialOverrides),f.nodeOverrideNames&&(u.nodeOverrideNames=[...f.nodeOverrideNames]),f.materialOverrideNames&&(u.materialOverrideNames=[...f.materialOverrideNames]),f.featureProperties&&(u.featureProperties=f.featureProperties)}static convertNodeOverrides(u,f){if(Array.isArray(f)&&f.every(_=>typeof _=="string")){u.nodeOverrideNames=[];for(const _ of f)u.nodeOverrideNames.push(_)}else Object.entries(f).forEach(([_,C])=>{const M={orientation:[0,0,0]};if(C.hasOwnProperty("orientation")){const P=C.orientation;P&&(M.orientation=P)}u.nodeOverrides.set(_,M)})}static convertMaterialOverrides(u,f){if(Array.isArray(f)&&f.every(_=>typeof _=="string")){u.materialOverrideNames=[];for(const _ of f)u.materialOverrideNames.push(_)}else Object.entries(f).forEach(([_,C])=>{const M={color:new wr(1,1,1),colorMix:0,emissionStrength:0,opacity:1},P=C["model-color"];P!==void 0&&(M.color.r=P[0],M.color.g=P[1],M.color.b=P[2]);const B=C["model-color-mix-intensity"];B!==void 0&&(M.colorMix=B);const U=C["model-emissive-strength"];U!==void 0&&(M.emissionStrength=U);const W=C["model-opacity"];W!==void 0&&(M.opacity=W),u.materialOverrides.set(_,M)})}onAdd(u){this.map=u,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const u of this._modelsInfo.values())if(u.model==null)return!1;return!0}getModels(){return this.models}loadTile(u,f){}serialize(){return this._options}setProperty(u,f){return!1}reload(){this.cancelModelRequests();const u=h1(this.id,this.scope);this.map.style.clearSource(u),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(u){this.cancelModelRequests()}setModels(u){this.models=[];const f=new Map;for(const _ in u){const C=u[_],M=this._modelsInfo.get(_);M&&M.modelSpec.uri===C.uri&&f.set(_,M)}if(this._modelsInfo.size!==f.size){this.cancelModelRequests();for(const[_,C]of f)C.model||f.delete(_)}this._modelsInfo=f,this._options.models=u,this.load()}}function Jye(g,u,f,_){const C=1<U>=ut.vertexArrayOffset&&Uat.polygon).flat());const Ee=me?B:null,[Fe,Qe]=VMe(M,_,se,ee,W,P,Ee,ae,ge,M.center.lat,g.tileID.canonical),Ve=g.queryGeometry;return qMe(Fe,Qe,Ve.isPointQuery()?Ve.screenBounds:Ve.screenGeometry)}},building:class extends Tu{constructor(g,u,f,_){super(g,{layout:gIe||(gIe=new jo({visibility:new nr(Yt.layout_building.visibility),"building-facade":new Qs(Yt.layout_building["building-facade"]),"building-facade-floors":new Qs(Yt.layout_building["building-facade-floors"]),"building-facade-unit-width":new Qs(Yt.layout_building["building-facade-unit-width"]),"building-facade-window":new Qs(Yt.layout_building["building-facade-window"]),"building-roof-shape":new Qs(Yt.layout_building["building-roof-shape"]),"building-height":new Qs(Yt.layout_building["building-height"]),"building-base":new Qs(Yt.layout_building["building-base"]),"building-flood-light-wall-radius":new Qs(Yt.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Qs(Yt.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Qs(Yt.layout_building["building-flip-roof-orientation"])})),paint:yIe||(yIe=new jo({"building-opacity":new nr(Yt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new nr(Yt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new nr(Yt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new nr(Yt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new nr(Yt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new nr(Yt.paint_building["building-vertical-scale"]),"building-cast-shadows":new nr(Yt.paint_building["building-cast-shadows"]),"building-color":new Qs(Yt.paint_building["building-color"]),"building-emissive-strength":new Qs(Yt.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new nr(Yt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new nr(Yt.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new nr(Yt.paint_building["building-front-cutoff"]),"building-flood-light-color":new nr(Yt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new nr(Yt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new nr(Yt.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Qs({type:"string",default:"default","property-type":"data-driven"})}))},u,f,_),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(g){return new xIe(g)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(g){return!0}queryRadius(g){return 0}queryIntersectsFeature(g,u,f,_,C,M,P,B,U,W){let ee=this.layout.get("building-height").evaluate(u,f);const se=this.layout.get("building-base").evaluate(u,f),ae=g.tile.getBucket(this).getFootprint(u);if(ae){if(ae.hiddenFlags!==0)return!1;ee=ae.height}const[me,ge]=VMe(M,_,se,ee,new ss(0,0),P,null,[0,0],1,M.center.lat,g.tileID.canonical),we=g.queryGeometry;return qMe(me,ge,we.isPointQuery()?we.screenBounds:we.screenGeometry)}},line:class extends Tu{constructor(g,u,f,_){const C=TIe();super(g,C,u,f,_),C.layout&&(this.layout=new Bg(C.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(g){if(g==="line-gradient"){const u=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=u._styleExpression&&u._styleExpression.expression instanceof M2,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(g,u){super.recalculate(g,u),this.paint._values["line-floorwidth"]=(()=>{if(m6)return m6;const f=TIe();return m6=new mvt(f.paint.properties["line-width"].specification),m6.useIntegerZoom=!0,m6})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,g)}createBucket(g){return new M7(g)}getProgramIds(){const g=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&g.push("lineBlendComposite"),g}getDefaultProgramParams(g,u,f){if(g==="lineBlendComposite")return{};const _=SIe(this);return{config:new je(this,{zoom:u,lut:f}),defines:_,overrideFog:!1}}queryRadius(g){const u=g,f=EIe(w_("line-width",this,u),w_("line-gap-width",this,u)),_=w_("line-offset",this,u);return f/2+Math.abs(_)+t7(this.paint.get("line-translate"))}queryIntersectsFeature(g,u,f,_,C,M){if(g.queryGeometry.isAboveHorizon)return!1;const P=CAe(g.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),M.angle,g.pixelToTileUnitsFactor),B=g.pixelToTileUnitsFactor/2*EIe(this.paint.get("line-width").evaluate(u,f),this.paint.get("line-gap-width").evaluate(u,f)),U=this.paint.get("line-offset").evaluate(u,f);return U&&(_=function(W,ee){const se=[],ae=new ss(0,0);for(let me=0;me=3){for(let ge=0;ge{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 VLe{constructor(u){this._stringToNumber={},this._numberToString=[];for(let f=0;f=0&&ae[3]>=0&&W.insert(U,ae[0],ae[1],ae[2],ae[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new ri(new I7(this.rawTileData)).layers,this.sourceLayerCoder=new VLe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const u in this.vtLayers)this.vtFeatures[u]=[]}return this.vtLayers}query(u,f){const{tilespaceGeometry:_,transform:C,tileTransform:M,pixelPosMatrix:P,availableImages:B,worldview:U}=f;this.loadVTLayers(),this.serializedLayersCache.clear();const W=f.queryRadius?f.queryRadius:0,ee=_.bufferedTilespaceBounds,se=this.grid.query(ee.min.x,ee.min.y,ee.max.x,ee.max.y,(we,Ee,Fe,Qe)=>o0(_.bufferedTilespaceGeometry,we-W,Ee-W,Fe+W,Qe+W));se.sort(j1t);let ae=null;C.elevation&&se.length>0&&(ae=TT.create(C.elevation,this.tileID));const me={};let ge;for(let we=0;we(Qe||(Qe=pn(Ve,this.tileID.canonical,M)),at.queryIntersectsFeature(_,Ve,ut,Qe,this.z,C,P,ae,ft,f.scope)))}return me}loadMatchingFeature(u,f,_,C,M,P){const{featureIndex:B,bucketIndex:U,sourceLayerIndex:W,layoutVertexArrayOffset:ee}=f,se=this.bucketLayerIDs[U],ae=_.layers,me=Object.keys(ae);if(me.length&&!Wr(me,se))return;const ge=_.sourceCache,we=this.sourceLayerCoder.decode(W),Ee=this.vtLayers[we].feature(B),Fe=this.getId(Ee,we);for(let Qe=0;Qe`${B.key}: ${B.message}`).join(", ");return void Rr(`Failed to create expression for promoteId: ${P}`)}this.promoteIdExpression=M.value}_=this.promoteIdExpression.evaluate({zoom:0},u)}else _=u.properties[C];typeof _=="boolean"&&(_=Number(_))}return _}}function GLe(g,u,f,_,C){return qs(g,(M,P)=>{const B=u instanceof Bg?u.get(P):null;return B&&B.evaluate?B.evaluate(f,_,void 0,C):B})}function j1t(g,u){return u-g}function WLe(g,u){const f={};if(!u)return f;for(const _ of g){const C=_.layerIds.map(M=>u.getLayer(M)).filter(Boolean);if(C.length!==0){_.layers=C,_.stateDependentLayerIds&&(_.stateDependentLayers=_.stateDependentLayerIds.map(M=>C.filter(P=>P.id===M)[0]));for(const M of C)f[M.fqid]=_}}return f}Dr(HLe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Sx=32,f0=33,E_=new Uint16Array(8184);for(let g=0;g<2046;g++){let u=g+2,f=0,_=0,C=0,M=0,P=0,B=0;for(1&u?C=M=P=Sx:f=_=B=Sx;(u>>=1)>1;){const W=f+C>>1,ee=_+M>>1;1&u?(C=f,M=_,f=P,_=B):(f=C,_=M,C=P,M=B),P=W,B=ee}const U=4*g;E_[U+0]=f,E_[U+1]=_,E_[U+2]=C,E_[U+3]=M}const p0=new Uint16Array(2178),A_=new Uint8Array(1089),Q7=new Uint16Array(1089);function KLe(g){return g===0?-.03125:g===32?.03125:0}const YLe={Other:0,Symbol:1,FillExtrusion:2},ZLe={type:2,extent:fr,loadGeometry:()=>[[new ss(0,0),new ss(8193,0),new ss(8193,8193),new ss(0,8193),new ss(0,0)]]};class N1t{constructor(){this.tasks={},this.taskQueue=[],Jt(["process"],this),this.invoker=new w1t(this.process),this.nextId=0}add(u,f){const _=this.nextId++,C=function({type:M,renderSourceType:P,zoom:B}){B=B||0;const U=P===YLe.Symbol;return M==="message"?0:M!=="maybePrepare"||U?M!=="parseTile"||U?M==="parseTile"&&U?300-B:M==="maybePrepare"&&U?400-B:500:200-B:100-B}(f);if(C===0){try{u()}finally{}return null}return this.tasks[_]={fn:u,metadata:f,priority:C,id:_},this.taskQueue.push(_),this.invoker.trigger(),{cancel:()=>{delete this.tasks[_]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(_=>!!this.tasks[_]),!this.taskQueue.length)return;const u=this.pick();if(u===null)return;const f=this.tasks[u];if(delete this.tasks[u],this.taskQueue.length&&this.invoker.trigger(),!f)return;f.fn()}finally{}}pick(){let u=null,f=1/0;for(let C=0;C>16&255)/255,(g>>8&255)/255,(255&g)/255,1)}function R1t(g,u,f){g===1?(u.rgb_color=t9(f.readVarint()),u.paint="rgb_color"):g===2?(u.linear_gradient_idx=f.readVarint(),u.paint="linear_gradient_idx"):g===3?(u.radial_gradient_idx=f.readVarint(),u.paint="radial_gradient_idx"):g===5?f.readPackedFloat(u.dasharray):g===6?u.dashoffset=f.readFloat():g===7?u.miterlimit=f.readFloat():g===8?u.opacity=f.readVarint():g===9?u.width=f.readFloat():g===10?u.linecap=f.readVarint():g===11&&(u.linejoin=f.readVarint())}function O1t(g,u,f){g===1?u.transform=e9(f,f.readVarint()+f.pos):g===2?u.spread_method=f.readVarint():g===3?u.stops.push(JLe(f,f.readVarint()+f.pos)):g===4?u.x1=f.readFloat():g===5?u.y1=f.readFloat():g===6?u.x2=f.readFloat():g===7&&(u.y2=f.readFloat())}function JLe(g,u){return g.readFields(F1t,{offset:0,opacity:255,rgb_color:e0e},u)}function F1t(g,u,f){g===1?u.offset=f.readFloat():g===2?u.opacity=f.readVarint():g===3&&(u.rgb_color=t9(f.readVarint()))}function B1t(g,u,f){g===1?u.transform=e9(f,f.readVarint()+f.pos):g===2?u.spread_method=f.readVarint():g===3?u.stops.push(JLe(f,f.readVarint()+f.pos)):g===4?u.cx=f.readFloat():g===5?u.cy=f.readFloat():g===6?u.r=f.readFloat():g===7?u.fx=f.readFloat():g===8?u.fy=f.readFloat():g===9&&(u.fr=f.readFloat())}function z1t(g,u,f){g===1?u.transform=e9(f,f.readVarint()+f.pos):g===2?u.clip_path_idx=f.readVarint():g===3&&u.children.push(J7(f,f.readVarint()+f.pos))}function $1t(g,u,f){g===1?u.left=u.top=f.readFloat():g===2?u.width=u.height=f.readFloat():g===3?u.top=f.readFloat():g===4?u.height=f.readFloat():g===5?u.mask_type=f.readVarint():g===6?u.mask_idx=f.readVarint():g===7&&u.children.push(J7(f,f.readVarint()+f.pos))}class U1t{static calculate(u={},f=[]){const _=new Map,C=new Map;if(Object.keys(u).length===0)return _;f.forEach(M=>{C.set(M.name,M.rgb_color||new wr(0,0,0))});for(const[M,P]of Object.entries(u))C.has(M)?_.set(C.get(M).toString(),P):console.warn(`Ignoring unknown image variable "${M}"`);return _}}function ET(g,u=255,f){const _=u/255,C=g.toString(),M=f.has(C)?f.get(C).clone():g.clone();return M.a*=_,M.toString()}function T6(g,u){if(!am()){const f=document.createElement("canvas");return f.width=g,f.height=u,f}return new OffscreenCanvas(g,u)}let t0e,E6=null;function s0e(g,u,f,_,C){for(const M of _.children)ePe(g,u,f,M,C)}function ePe(g,u,f,_,C){_.group?(g.save(),function(M,P,B,U,W){const ee=U.mask_idx!=null?B.masks[U.mask_idx]:null,se=U.clip_path_idx!=null?B.clip_paths[U.clip_path_idx]:null;if(U.transform&&(P=AT(U.transform).preMultiplySelf(P)),!function(ge,we,Ee){return ge.opacity!==255||we||Ee}(U,se!=null,ee!=null))return void s0e(M,P,B,U,W);const ae=T6(M.canvas.width,M.canvas.height),me=ae.getContext("2d");s0e(me,P,B,U,W),se&&oPe(me,P,B,se),ee&&lPe(me,P,B,ee,W),M.globalAlpha=U.opacity/255,M.drawImage(ae,0,0)}(g,u,f,_.group,C),g.restore()):_.path&&(g.save(),function(M,P,B,U,W){M.setTransform(P),U.paint_order===1?(tPe(M,B,U,W),rPe(M,B,U,W)):(rPe(M,B,U,W),tPe(M,B,U,W))}(g,u,f,_.path,C),g.restore())}function tPe(g,u,f,_){const C=f.fill;if(!C)return;const M=C.opacity/255;switch(g.save(),g.beginPath(),cPe(f,g),C.paint){case"rgb_color":g.fillStyle=ET(C.rgb_color,C.opacity,_);break;case"linear_gradient_idx":{const P=u.linear_gradients[C.linear_gradient_idx];P.transform&&g.setTransform(AT(P.transform).preMultiplySelf(g.getTransform())),g.fillStyle=nPe(g,P,M,_);break}case"radial_gradient_idx":{const P=u.radial_gradients[C.radial_gradient_idx];P.transform&&g.setTransform(AT(P.transform).preMultiplySelf(g.getTransform())),g.fillStyle=aPe(g,P,M,_)}}g.fill(sPe(f)),g.restore()}function sPe(g){return g.rule===1?"nonzero":g.rule===2?"evenodd":void 0}function rPe(g,u,f,_){const C=f.stroke;if(!C)return;const M=dPe(f);g.lineWidth=C.width,g.miterLimit=C.miterlimit,g.setLineDash(C.dasharray),g.lineDashOffset=C.dashoffset;const P=C.opacity/255;switch(C.paint){case"rgb_color":g.strokeStyle=ET(C.rgb_color,C.opacity,_);break;case"linear_gradient_idx":g.strokeStyle=nPe(g,u.linear_gradients[C.linear_gradient_idx],P,_,!0);break;case"radial_gradient_idx":g.strokeStyle=aPe(g,u.radial_gradients[C.radial_gradient_idx],P,_,!0)}switch(C.linejoin){case 2:case 1:g.lineJoin="miter";break;case 3:g.lineJoin="round";break;case 4:g.lineJoin="bevel"}switch(C.linecap){case 1:g.lineCap="butt";break;case 2:g.lineCap="round";break;case 3:g.lineCap="square"}g.stroke(M)}function nPe(g,u,f,_,C=!1){if(u.stops.length===1){const ae=u.stops[0];return ET(ae.rgb_color,ae.opacity*f,_)}const{x1:M,y1:P,x2:B,y2:U}=u;let W=new DOMPoint(M,P),ee=new DOMPoint(B,U);if(C){const ae=AT(u.transform);W=ae.transformPoint(W),ee=ae.transformPoint(ee)}const se=g.createLinearGradient(W.x,W.y,ee.x,ee.y);for(const ae of u.stops)se.addColorStop(ae.offset,ET(ae.rgb_color,ae.opacity*f,_));return se}function aPe(g,u,f,_,C=!1){if(u.stops.length===1){const Fe=u.stops[0];return ET(Fe.rgb_color,Fe.opacity*f,_)}const M=AT(u.transform),{fx:P,fy:B,fr:U,cx:W,cy:ee,r:se}=u;let ae=new DOMPoint(P,B),me=new DOMPoint(W,ee),ge=U,we=se;if(C){ae=M.transformPoint(ae),me=M.transformPoint(me);const Fe=(M.a+M.d)/2;ge=U*Fe,we=u.r*Fe}const Ee=g.createRadialGradient(ae.x,ae.y,ge,me.x,me.y,we);for(const Fe of u.stops)Ee.addColorStop(Fe.offset,ET(Fe.rgb_color,Fe.opacity*f,_));return Ee}function iPe(g,u,f,_){const C=_.transform?AT(_.transform).preMultiplySelf(u):u,M=T6(g.canvas.width,g.canvas.height),P=M.getContext("2d");for(const U of _.children)if(U.group)iPe(P,C,f,U.group);else if(U.path){const W=U.path,ee=new Path2D;ee.addPath(dPe(W),C),P.fill(ee,sPe(W))}const B=_.clip_path_idx!=null?f.clip_paths[_.clip_path_idx]:null;B&&oPe(P,C,f,B),g.globalCompositeOperation="source-over",g.drawImage(M,0,0)}function oPe(g,u,f,_){const C=T6(g.canvas.width,g.canvas.height);iPe(C.getContext("2d"),u,f,_),g.globalCompositeOperation="destination-in",g.drawImage(C,0,0)}function lPe(g,u,f,_,C){if(_.children.length===0)return;const M=_.mask_idx!=null?f.masks[_.mask_idx]:null;M&&lPe(g,u,f,M,C);const P=g.canvas.width,B=g.canvas.height,U=T6(P,B),W=U.getContext("2d"),ee=_.width,se=_.height,ae=_.left,me=_.top,ge=new Path2D,we=new Path2D;we.rect(ae,me,ee,se),ge.addPath(we,u),W.clip(ge);for(const Qe of _.children)ePe(W,u,f,Qe,C);const Ee=W.getImageData(0,0,P,B),Fe=Ee.data;if(_.mask_type===1)for(let Qe=0;Qeu[P])return null}else{const B=1/_[P];let U=(g[P]-f[P])*B,W=(u[P]-f[P])*B;if(U>W){const ee=U;U=W,W=ee}if(U>C&&(C=U),WM)return null}return C}function mPe(g,u,f,_,C,M,P,B,U,W,ee){const se=_-g,ae=C-u,me=M-f,ge=P-g,we=B-u,Ee=U-f,Fe=ee[1]*Ee-ee[2]*we,Qe=ee[2]*ge-ee[0]*Ee,Ve=ee[0]*we-ee[1]*ge,at=se*Fe+ae*Qe+me*Ve;if(Math.abs(at)<1e-15)return null;const ut=1/at,ft=W[0]-g,Bt=W[1]-u,Et=W[2]-f,Ot=(ft*Fe+Bt*Qe+Et*Ve)*ut;if(Ot<0||Ot>1)return null;const Lt=Bt*me-Et*ae,Pt=Et*se-ft*me,hs=ft*ae-Bt*se,bs=(ee[0]*Lt+ee[1]*Pt+ee[2]*hs)*ut;return bs<0||Ot+bs>1?null:(ge*Lt+we*Pt+Ee*hs)*ut}function fPe(g,u,f){return(g-u)/(f-u)}function pPe(g,u,f,_,C,M,P,B,U){const W=1<{const Qe=Ee?1:0,Ve=(me+1)*we-Qe,at=ge*we,ut=(ge+1)*we-Qe;Fe[0]=me*we,Fe[1]=at,Fe[2]=Ve,Fe[3]=ut};let se=new uPe(U);const ae=[];for(let me=0;me=1;U/=2){const me=B[B.length-1];se=new uPe(U);for(let ge=0;ge0;){const{idx:ge,t:we,nodex:Ee,nodey:Fe,depth:Qe}=me.pop();if(this.leaves[ge]){pPe(Ee,Fe,Qe,u,f,_,C,se,ae);const at=1<=Es[2])return we}continue}let Ve=0;for(let at=0;at=W[ee[Et]]&&(ee.splice(Et,0,at),Bt=!0);Bt||(ee[Ve]=at),Ve++}}for(let at=0;at=this.dim+1||f<-1||f>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(f+1)*this.stride+(u+1)}static pack(u,f){const _=[0,0,0,0],C=r9.getUnpackVector(f);let M=Math.floor((u+C[3])/C[2]);return _[2]=M%256,M=Math.floor(M/256),_[1]=M%256,M=Math.floor(M/256),_[0]=M,_}getPixels(){return new QAe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(u,f,_){if(this.dim!==u.dim)throw new Error("dem dimension mismatch");let C=f*this.dim,M=f*this.dim+this.dim,P=_*this.dim,B=_*this.dim+this.dim;switch(f){case-1:C=M-1;break;case 1:M=C+1}switch(_){case-1:P=B-1;break;case 1:B=P+1}const U=-f*this.dim,W=-_*this.dim;for(let ee=P;ee=1;_--){const C=_===1?1:0,M=_===2?1:0;for(let P=0;P>>1^-(1&g[u]);return g}function sbt(g,u){switch(u){case"uint32":return g;case"uint16":for(let f=0;f>4|(61440&_)>>8|(240&C)<<4|61440&C,g[f+1]=15&_|(3840&_)>>4|(15&C)<<8|(3840&C)<<4}return g;case"uint8":for(let f=0;f>6|(192&C)>>4|(192&M)>>2|192&P,g[f+1]=(48&_)>>4|(48&C)>>2|48&M|(48&P)<<2,g[f+2]=(12&_)>>2|12&C|(12&M)<<2|(12&P)<<4,g[f+3]=3&_|(3&C)<<2|(3&M)<<4|(3&P)<<6}return g;default:throw new Error(`Invalid pixel format, "${u}"`)}}Dr(r9,"DEMData"),Dr(xPe,"DemMinMaxQuadTree",{omit:["dem"]});var fp=Uint8Array,A6=Uint16Array,rbt=Int32Array,yPe=new fp([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]),vPe=new fp([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]),nbt=new fp([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),bPe=function(g,u){for(var f=new A6(31),_=0;_<31;++_)f[_]=u+=1<>1|(21845&gc)<<1;jPe[gc]=((65280&(MT=(61680&(MT=(52428&MT)>>2|(13107&MT)<<2))>>4|(3855&MT)<<4))>>8|(255&MT)<<8)>>1}var M6=function(g,u,f){for(var _=g.length,C=0,M=new A6(u);C<_;++C)g[C]&&++M[g[C]-1];var P,B=new A6(u);for(C=1;C>U]=W;return P},I6=new fp(288);for(gc=0;gc<144;++gc)I6[gc]=8;for(gc=144;gc<256;++gc)I6[gc]=9;for(gc=256;gc<280;++gc)I6[gc]=7;for(gc=280;gc<288;++gc)I6[gc]=8;var NPe=new fp(32);for(gc=0;gc<32;++gc)NPe[gc]=5;var obt=M6(I6,9),lbt=M6(NPe,5),n0e=function(g){for(var u=g[0],f=1;fu&&(u=g[f]);return u},Gg=function(g,u,f){var _=u/8|0;return(g[_]|g[_+1]<<8)>>(7&u)&f},a0e=function(g,u){var f=u/8|0;return(g[f]|g[f+1]<<8|g[f+2]<<16)>>(7&u)},cbt=function(g){return(g+7)/8|0},dbt=["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"],Wg=function(g,u,f){var _=new Error(u||dbt[g]);if(_.code=g,Error.captureStackTrace&&Error.captureStackTrace(_,Wg),!f)throw _;return _},ubt=new fp(0),hbt=typeof TextDecoder<"u"&&new TextDecoder;try{hbt.decode(ubt,{stream:!0})}catch{}const mbt={gzip_data:"gzip"};class Cx extends Error{constructor(u){super(u),this.name="MRTError"}}const fbt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},kPe={uint32:1,uint16:2,uint8:4},pbt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let i0e;class n9{constructor(u=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=u}getLayer(u){const f=this.layers[u];if(!f)throw new Cx(`Layer '${u}' not found`);return f}getHeaderLength(u){const f=new Uint8Array(u),_=new DataView(u);if(f[0]!==13)throw new Cx("File is not a valid MRT.");return _.getUint32(1,!0)}parseHeader(u){const f=new Uint8Array(u),_=this.getHeaderLength(u);if(f.length<_)throw new Cx(`Expected header with length >= ${_} but got buffer of length ${f.length}`);const C=new i0e(f.subarray(0,_)).readFields(G1t,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==C.x||this.y!==C.y||this.z!==C.z))throw new Cx(`Invalid attempt to parse header ${C.z}/${C.x}/${C.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=C.x,this.y=C.y,this.z=C.z;for(const M of C.layers)this.layers[M.name]=new SPe(M,{cacheSize:this._cacheSize});return this}createDecodingTask(u){const f=[],_=this.getLayer(u.layerName);for(let C of u.blockIndices){const M=_.dataIndex[C],P=M.firstByte-u.firstByte,B=M.lastByte-u.firstByte;if(_._blocksInProgress.has(C))continue;const U={layerName:_.name,firstByte:P,lastByte:B,pixelFormat:_.pixelFormat,blockIndex:C,blockShape:[M.bands.length].concat(_.bandShape),buffer:_.buffer,codec:M.codec.codec,filters:M.filters.map(W=>W.filter)};_._blocksInProgress.add(C),f.push(U)}return new CPe(f,()=>{f.forEach(C=>_._blocksInProgress.delete(C.blockIndex))},(C,M)=>{if(f.forEach(P=>_._blocksInProgress.delete(P.blockIndex)),C)throw C;M.forEach(P=>{this.getLayer(P.layerName).processDecodedData(P)})})}}class SPe{constructor({version:u,name:f,units:_,tileSize:C,pixelFormat:M,buffer:P,dataIndex:B},U){if(this.version=u,this.version!==1)throw new Cx(`Cannot parse raster layer encoded with MRT version ${u}`);this.name=f,this.units=_,this.tileSize=C,this.buffer=P,this.pixelFormat=fbt[M],this.dataIndex=B,this.bandShape=[C+2*P,C+2*P,kPe[this.pixelFormat]],this._decodedBlocks=new s9(U?U.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return kPe[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:u})=>u).flat()}processDecodedData(u){const f=u.blockIndex.toString();this._decodedBlocks.get(f)||this._decodedBlocks.put(f,u.data)}getBlockForBand(u){let f=0;switch(typeof u){case"string":for(const[_,C]of this.dataIndex.entries()){for(const[M,P]of C.bands.entries())if(P===u)return{bandIndex:f+M,blockIndex:_,blockBandIndex:M};f+=C.bands.length}break;case"number":for(const[_,C]of this.dataIndex.entries()){if(u>=f&&uthis.cacheSize)throw new Cx(`Number of blocks to decode (${M.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:f,lastByte:_,blockIndices:C}}hasBand(u){const{blockIndex:f}=this.getBlockForBand(u);return f>=0}hasDataForBand(u){const{blockIndex:f}=this.getBlockForBand(u);return f>=0&&!!this._decodedBlocks.get(f.toString())}getBandView(u){const{blockIndex:f,blockBandIndex:_}=this.getBlockForBand(u);if(f<0)throw new Cx(`Band not found: ${JSON.stringify(u)}`);const C=this._decodedBlocks.get(f.toString());if(!C)throw new Cx(`Data for band ${JSON.stringify(u)} of layer "${this.name}" not decoded.`);const M=this.dataIndex[f],P=this.bandShape.reduce((W,ee)=>W*ee,1),B=_*P,U=C.subarray(B,B+P);return{data:U,bytes:new Uint8Array(U.buffer).subarray(U.byteOffset,U.byteOffset+U.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:M.offset,scale:M.scale}}}n9.setPbf=function(g){i0e=g};class CPe{constructor(u,f,_){this.tasks=u,this._onCancel=f,this._onComplete=_,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(u,f){this._finalized||(this._onComplete(u,f),this._finalized=!0)}}n9.performDecoding=function(g,u){const f=new Uint8Array(g);return Promise.all(u.tasks.map(_=>{const{layerName:C,firstByte:M,lastByte:P,pixelFormat:B,blockShape:U,blockIndex:W,filters:ee,codec:se}=_,ae=f.subarray(M,P+1),me=new Uint32Array(U[0]*U[1]*U[2]);let ge;if(se!=="gzip_data")throw new Cx(`Unhandled codec: ${se}`);return ge=function(we,Ee){if(!globalThis.DecompressionStream&&Ee==="gzip_data")return Promise.resolve((ut=function(Et){Et[0]==31&&Et[1]==139&&Et[2]==8||Wg(6,"invalid gzip data");var Ot=Et[3],Lt=10;4&Ot&&(Lt+=2+(Et[10]|Et[11]<<8));for(var Pt=(Ot>>3&1)+(Ot>>4&1);Pt>0;Pt-=!Et[Lt++]);return Lt+(2&Ot)}(Fe=we),ut+8>Fe.length&&Wg(6,"invalid gzip data"),function(Et,Ot,Lt,Pt){var hs=Et.length;if(!hs||Ot.f&&!Ot.l)return Lt||new fp(0);var bs=!Lt,Ts=bs||Ot.i!=2,Rs=Ot.i;bs&&(Lt=new fp(3*hs));var Es=function(Go){var Eu=Lt.length;if(Go>Eu){var Qc=new fp(Math.max(2*Eu,Go));Qc.set(Lt),Lt=Qc}},Ws=Ot.f||0,ls=Ot.p||0,Ps=Ot.b||0,zs=Ot.l,Ks=Ot.d,tr=Ot.m,Ar=Ot.n,ur=8*hs;do{if(!zs){Ws=Gg(Et,ls,1);var dr=Gg(Et,ls+1,3);if(ls+=3,!dr){var sr=Et[(hi=cbt(ls)+4)-4]|Et[hi-3]<<8,Tr=hi+sr;if(Tr>hs){Rs&&Wg(0);break}Ts&&Es(Ps+sr),Lt.set(Et.subarray(hi,Tr),Ps),Ot.b=Ps+=sr,Ot.p=ls=8*Tr,Ot.f=Ws;continue}if(dr==1)zs=obt,Ks=lbt,tr=9,Ar=5;else if(dr==2){var zr=Gg(Et,ls,31)+257,mn=Gg(Et,ls+10,15)+4,Gr=zr+Gg(Et,ls+5,31)+1;ls+=14;for(var Vn=new fp(Gr),$a=new fp(19),Hn=0;Hn>4)<16)Vn[Hn++]=hi;else{var Ui=0,Io=0;for(hi==16?(Io=3+Gg(Et,ls,3),ls+=2,Ui=Vn[Hn-1]):hi==17?(Io=3+Gg(Et,ls,7),ls+=3):hi==18&&(Io=11+Gg(Et,ls,127),ls+=7);Io--;)Vn[Hn++]=Ui}}var Lc=Vn.subarray(0,zr),Lo=Vn.subarray(zr);tr=n0e(Lc),Ar=n0e(Lo),zs=M6(Lc,tr),Ks=M6(Lo,Ar)}else Wg(1);if(ls>ur){Rs&&Wg(0);break}}Ts&&Es(Ps+131072);for(var cl=(1<>4;if((ls+=15&Ui)>ur){Rs&&Wg(0);break}if(Ui||Wg(2),qd<256)Lt[Ps++]=qd;else{if(qd==256){dl=ls,zs=null;break}var Pc=qd-254;qd>264&&(Pc=Gg(Et,ls,(1<<(yl=yPe[Hn=qd-257]))-1)+wPe[Hn],ls+=yl);var ha=Ks[a0e(Et,ls)&Pl],ah=ha>>4;if(ha||Wg(3),ls+=15&ha,Lo=ibt[ah],ah>3){var yl=vPe[ah];Lo+=a0e(Et,ls)&(1<ur){Rs&&Wg(0);break}Ts&&Es(Ps+131072);var Xc=Ps+Pc;if(PsGo.length)&&(Qc=Go.length),new fp(Go.subarray(0,Qc))}(Lt,0,Ps):Lt.subarray(0,Ps)}(Fe.subarray(ut,-8),{i:2},new fp(((Ve=Fe)[(at=Ve.length)-4]|Ve[at-3]<<8|Ve[at-2]<<16|Ve[at-1]<<24)>>>0),Qe)));var Fe,Qe,Ve,at,ut;const ft=mbt[Ee];if(!ft)throw new Error(`Unhandled codec: ${Ee}`);const Bt=new globalThis.DecompressionStream(ft);return new Response(new Blob([we]).stream().pipeThrough(Bt)).arrayBuffer().then(Et=>new Uint8Array(Et))}(ae,se).then(we=>(function(Ee,Fe){Ee.readFields(Q1t,Fe)}(new i0e(we),me),new pbt[B](me.buffer))),ge.then(we=>{for(let Ee=ee.length-1;Ee>=0;Ee--)switch(ee[Ee]){case"delta_filter":ebt(we,U);break;case"zigzag_filter":tbt(we);break;case"bitshuffle_filter":sbt(we,B);break;default:throw new Cx(`Unhandled filter "${ee[Ee]}"`)}return{layerName:C,blockIndex:W,data:we}}).catch(we=>{throw we})}))},Dr(CPe,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Dr(n9,"MapboxRasterTile"),Dr(SPe,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const TPe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class o0e{static from(u){if(!(u instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[f,_]=new Uint8Array(u,0,2);if(f!==219)throw new Error("Data does not appear to be in a KDBush format.");const C=_>>4;if(C!==1)throw new Error(`Got v${C} data when expected v1.`);const M=TPe[15&_];if(!M)throw new Error("Unrecognized array type.");const[P]=new Uint16Array(u,2,1),[B]=new Uint32Array(u,4,1);return new o0e(B,P,M,u)}constructor(u,f=64,_=Float64Array,C){if(isNaN(u)||u<0)throw new Error(`Unpexpected numItems value: ${u}.`);this.numItems=+u,this.nodeSize=Math.min(Math.max(+f,2),65535),this.ArrayType=_,this.IndexArrayType=u<65536?Uint16Array:Uint32Array;const M=TPe.indexOf(this.ArrayType),P=2*u*this.ArrayType.BYTES_PER_ELEMENT,B=u*this.IndexArrayType.BYTES_PER_ELEMENT,U=(8-B%8)%8;if(M<0)throw new Error(`Unexpected typed array class: ${_}.`);C&&C instanceof ArrayBuffer?(this.data=C,this.ids=new this.IndexArrayType(this.data,8,u),this.coords=new this.ArrayType(this.data,8+B+U,2*u),this._pos=2*u,this._finished=!0):(this.data=new ArrayBuffer(8+P+B+U),this.ids=new this.IndexArrayType(this.data,8,u),this.coords=new this.ArrayType(this.data,8+B+U,2*u),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+M]),new Uint16Array(this.data,2,1)[0]=f,new Uint32Array(this.data,4,1)[0]=u)}add(u,f){const _=this._pos>>1;return this.ids[_]=_,this.coords[this._pos++]=u,this.coords[this._pos++]=f,_}finish(){const u=this._pos>>1;if(u!==this.numItems)throw new Error(`Added ${u} items when expected ${this.numItems}.`);return l0e(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(u,f,_,C){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:M,coords:P,nodeSize:B}=this,U=[0,M.length-1,0],W=[];for(;U.length;){const ee=U.pop()||0,se=U.pop()||0,ae=U.pop()||0;if(se-ae<=B){for(let Ee=ae;Ee<=se;Ee++){const Fe=P[2*Ee],Qe=P[2*Ee+1];Fe>=u&&Fe<=_&&Qe>=f&&Qe<=C&&W.push(M[Ee])}continue}const me=ae+se>>1,ge=P[2*me],we=P[2*me+1];ge>=u&&ge<=_&&we>=f&&we<=C&&W.push(M[me]),(ee===0?u<=ge:f<=we)&&(U.push(ae),U.push(me-1),U.push(1-ee)),(ee===0?_>=ge:C>=we)&&(U.push(me+1),U.push(se),U.push(1-ee))}return W}within(u,f,_){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:C,coords:M,nodeSize:P}=this,B=[0,C.length-1,0],U=[],W=_*_;for(;B.length;){const ee=B.pop()||0,se=B.pop()||0,ae=B.pop()||0;if(se-ae<=P){for(let Ee=ae;Ee<=se;Ee++)APe(M[2*Ee],M[2*Ee+1],u,f)<=W&&U.push(C[Ee]);continue}const me=ae+se>>1,ge=M[2*me],we=M[2*me+1];APe(ge,we,u,f)<=W&&U.push(C[me]),(ee===0?u-_<=ge:f-_<=we)&&(B.push(ae),B.push(me-1),B.push(1-ee)),(ee===0?u+_>=ge:f+_>=we)&&(B.push(me+1),B.push(se),B.push(1-ee))}return U}}function l0e(g,u,f,_,C,M){if(C-_<=f)return;const P=_+C>>1;EPe(g,u,P,_,C,M),l0e(g,u,f,_,P-1,1-M),l0e(g,u,f,P+1,C,1-M)}function EPe(g,u,f,_,C,M){for(;C>_;){if(C-_>600){const W=C-_+1,ee=f-_+1,se=Math.log(W),ae=.5*Math.exp(2*se/3),me=.5*Math.sqrt(se*ae*(W-ae)/W)*(ee-W/2<0?-1:1);EPe(g,u,f,Math.max(_,Math.floor(f-ee*ae/W+me)),Math.min(C,Math.floor(f+(W-ee)*ae/W+me)),M)}const P=u[2*f+M];let B=_,U=C;for(L6(g,u,_,f),u[2*C+M]>P&&L6(g,u,_,C);BP;)U--}u[2*_+M]===P?L6(g,u,_,U):(U++,L6(g,u,U,C)),U<=f&&(_=U+1),f<=U&&(C=U-1)}}function L6(g,u,f,_){c0e(g,f,_),c0e(u,2*f,2*_),c0e(u,2*f+1,2*_+1)}function c0e(g,u,f){const _=g[u];g[u]=g[f],g[f]=_}function APe(g,u,f,_){const C=g-f,M=u-_;return C*C+M*M}o.$=o_,o.A=class{constructor(g,u,f){this.target=g,this.parent=u,this.mapId=f,this.callbacks={},this.cancelCallbacks={},Jt(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new N1t}send(g,u,f,_,C=!1,M){const P=Math.round(1e18*Math.random()).toString(36).substring(0,10);f&&(f.metadata=M,this.callbacks[P]=f);const B=new Set;return this.target.postMessage({id:P,type:g,hasCallback:!!f,targetMapId:_,mustQueue:C,sourceMapId:this.mapId,data:Rg(u,B)},B),{cancel:()=>{f&&delete this.callbacks[P],this.target.postMessage({id:P,type:"",targetMapId:_,sourceMapId:this.mapId})}}}receive(g){const u=g.data;if(!u)return;const f=u.id;if(f&&(!u.targetMapId||this.mapId===u.targetMapId))if(u.type===""){const _=this.cancelCallbacks[f];delete this.cancelCallbacks[f],_&&_.cancel()}else if(u.mustQueue||fa(self)){const _=this.callbacks[f],C=this.scheduler.add(()=>this.processTask(f,u),_&&_.metadata||{type:"message"});C&&(this.cancelCallbacks[f]=C)}else this.processTask(f,u)}processTask(g,u){if(delete this.cancelCallbacks[g],u.type===""){const f=this.callbacks[g];delete this.callbacks[g],f&&(u.error?f(a0(u.error)):f(null,a0(u.data)))}else{const f=new Set,_=u.hasCallback?(M,P)=>{this.target.postMessage({id:g,type:"",sourceMapId:this.mapId,error:M?Rg(M):null,data:Rg(P,f)},f)}:()=>{},C=a0(u.data);if(this.parent[u.type])this.parent[u.type](u.sourceMapId,C,_);else if(this.parent.getWorkerSource){const M=u.type.split("."),{source:P,scope:B}=C;this.parent.getWorkerSource(u.sourceMapId,{type:M[0],source:P,scope:B,uid:0})[M[1]](C,_)}else _(new Error(`Could not find function ${u.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=Zy,o.C=Pm,o.D=Sf,o.E=Qv,o.F=h1,o.G=2,o.H=x6,o.I=kt,o.J=KIe,o.K=v5,o.L=Bz,o.M=_2,o.N=w2,o.O=$5,o.P=ss,o.Q=z5,o.R=Zv,o.S=rP,o.T=m0,o.U=$2,o.V=Z7,o.W=J5,o.X=n0,o.Y=aP,o.Z=vx,o._=a1,o.a=function(g){return ba.API_CDN_URL_REGEX.test(g)},o.a$=I7,o.a0=Mc,o.a1=j2,o.a2=b5,o.a3=An,o.a4=NP,o.a5=class extends Z7{},o.a6=nP,o.a7=wz,o.a8=Yt,o.a9=function(g){const u=g.value;return u?b5(u)?Zye(u,!0)?[]:[new Z7(g.key,u,`invalid url "${u}"`)]:[new Z7(g.key,u,`string expected, "${_2(u)}" found`)]:[]},o.aA=wIe,o.aB=function(g){let u=1/0,f=1/0,_=-1/0,C=-1/0;for(const M of g)u=Math.min(u,M.x),f=Math.min(f,M.y),_=Math.max(_,M.x),C=Math.max(C,M.y);return{min:new ss(u,f),max:new ss(_,C)}},o.aC=ze,o.aD=S,o.aE=xt,o.aF=vt,o.aG=Ph,o.aH=Os,o.aI=Er,o.aJ=function(g,u){const f={};for(let _=0;_=0?u.slice(f+1):""}catch{return""}},o.aN=class{constructor(g){this.entries={},this.scheduler=g}request(g,u,f,_){const C=this.entries[g]=this.entries[g]||{callbacks:[]};if(C.result){const[M,P]=C.result;return this.scheduler?this.scheduler.add(()=>{_(M,P)},u):_(M,P),()=>{}}return C.callbacks.push(_),C.cancel||(C.cancel=f((M,P)=>{C.result=[M,P];for(const B of C.callbacks)this.scheduler?this.scheduler.add(()=>{B(M,P)},u):B(M,P);setTimeout(()=>delete this.entries[g],3e3)})),()=>{C.result||(C.callbacks=C.callbacks.filter(M=>M!==_),C.callbacks.length||(C.cancel(),delete this.entries[g]))}}},o.aO=function(g,u,f){const _=JSON.stringify(g.request);return g.data&&(this.deduped.entries[_]={result:[null,g.data]}),this.deduped.request(_,{type:"parseTile",renderSourceType:g.renderSourceType,zoom:g.tileZoom},C=>{const M=Yy(g.request,(P,B,U)=>{P?Tg(P)?C(null,null):C(P):B&&C(null,{rawData:B,vectorTile:f?void 0:new ri(new I7(B)),responseHeaders:new Map(U.entries())})});return()=>{M.cancel(),C(null,null)}},u)},o.aP=function(g){return g?{cacheControl:g.get("cache-control"),expires:g.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(g){f2++,f2>Zb&&(g.getActor().send("enforceCacheSizeLimit",Kv),f2=0)},o.aR=nh,o.aS=ELe,o.aT=OLe,o.aU=qt,o.aV=TLe,o.aW=function(g,u){const f=document.createElement("video");f.muted=!0,f.onloadstart=function(){u(null,f)};for(let _=0;_{}}},o.aX=u6,o.aY=gN,o.aZ=Jt,o.a_=n9,o.aa=Q5,o.ab=jo,o.ac=nr,o.ad=class{constructor(g){this.specification=g}possiblyEvaluate(g,u){return un(g.expression.evaluate(u))}interpolate(g,u,f){return{x:hn(g.x,u.x,f),y:hn(g.y,u.y,f),z:hn(g.z,u.z,f),azimuthal:hn(g.azimuthal,u.azimuthal,f),polar:hn(g.polar,u.polar,f)}}},o.ae=ui,o.af=o1,o.ag=Br,o.ah=et,o.ai=re,o.aj=st,o.ak=Bg,o.al=v1,o.am=hn,o.an=fr,o.ao=gd,o.ap=Pr,o.aq=wr,o.ar=class{constructor(g){this.specification=g}possiblyEvaluate(g,u){return function([f,_]){const C=un([1,f,_]);return{x:C.x,y:C.y,z:C.z}}(g.expression.evaluate(u))}interpolate(g,u,f){return{x:hn(g.x,u.x,f),y:hn(g.y,u.y,f),z:hn(g.z,u.z,f)}}},o.as=function(g,u,f=0,_=!0){const C=new ss(f,f),M=g.sub(C),P=u.add(C),B=[M,new ss(P.x,M.y),P,new ss(M.x,P.y)];return _&&B.push(M.clone()),B},o.at=function(g,u){const f=[];for(let _=0;_this.buckets[se].layers.some(ae=>P.has(ae.fqid))),U=Object.keys(this.buckets).some(se=>this.buckets[se].layers.some(ae=>ae.hasTransition&&ae.hasTransition())),W=this._firstPrepareComplete&&M!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(u));const ee=this._lastUpdatedBrightness!==_;this._lastAvailableImagesCount=M,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||_||this._hasAppearances||B||U||W)&&(!(this._hasAppearances||B||U||W)&&this._lastUpdatedBrightness&&_&&Math.abs(this._lastUpdatedBrightness-_)<.001||(this.updateBuckets(u,ee,void 0,W||B||U,P,C),this._lastUpdatedBrightness=_))}evaluateQueryRenderedFeaturePadding(){let g=0;for(const u in this.buckets){const f=this.buckets[u];f.evaluateQueryRenderedFeaturePadding&&(g=Math.max(g,f.evaluateQueryRenderedFeaturePadding()))}return g}queryRenderedFeatures(g,u,f,_,C,M,P){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const B=this.evaluateQueryRenderedFeaturePadding(),U=function(W,ee){const se=$([],[.5*W.width,.5*-W.height,1]);return T(se,se,[1,-1,0]),S(se,se,W.calculateProjMatrix(ee.toUnwrapped())),Float32Array.from(se)}(C,this.tileID);return this.latestFeatureIndex.query(g,{tilespaceGeometry:u,pixelPosMatrix:U,transform:_,availableImages:f,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:B,scope:P})}querySourceFeatures(g,u){const f=this.latestFeatureIndex;if(!f||!f.rawTileData)return;const _=f.loadVTLayers(),C=u?u.sourceLayer:"",M=_._geojsonTileLayer||_[C];if(!M)return;const P=eT(u&&u.filter),{z:B,x:U,y:W}=this.tileID.canonical,ee={z:B,x:U,y:W};for(let se=0;sef)_=!1;else if(u)if(this.expirationTimef.appearances&&f.appearances.length>0))return!0;return!1}updateBuckets(g,u,f,_,C,M){if(!this.latestFeatureIndex||!g.style)return;const P=M||g.style.listImages(),B=g.style.getBrightness(),U=C||new Set;for(const W in this.buckets){if(!g.style.hasLayer(W))continue;const ee=this.buckets[W],se=ee.layers[0],ae=se.sourceLayer||"_geojsonTileLayer",me=g.style.getLayerSourceCache(se),ge=ee.layers.some(ut=>U.has(ut.fqid)),we=(_||ge)&&ee instanceof Hg?g.style.getOwnLayer(W):void 0;let Ee=f&&f[ae]||{};me&&!f&&(Ee=me._state.getState(ae,void 0));const Fe=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},Qe=Object.keys(Ee).length>0&&!u;ee.hasAppearances=ee.layers.some(ut=>ut.appearances&&ut.appearances.length>0);const Ve=Qe?ee.stateDependentLayers:ee.layers;if(Qe&&ee.stateDependentLayers.length!==0||u||ge||_){const ut=this.latestFeatureIndex.loadVTLayers()[ae];if(ee.update(Ee,ut,P,Fe,Ve,u,B,this.tileID.canonical),(_||ge)&&!u&&ee instanceof Hg&&we&&we.type==="symbol"){const ft=ee;ft.text&&ft.text.uboBinder&&ft.text.uboBinder.updateDynamicExpressions(we,ut,this.tileID.canonical,P,Ee,B),ft.icon&&ft.icon.uboBinder&&ft.icon.uboBinder.updateDynamicExpressions(we,ut,this.tileID.canonical,P,Ee,B)}if(ee instanceof Hg){const ft=ee,Bt=g.context;ft.text&&ft.text.uboBinder&&ft.text.uboBinder.upload(Bt),ft.icon&&ft.icon.uboBinder&&ft.icon.uboBinder.upload(Bt)}}if(Qe&&ee.stateDependentLayers.length!==0||u||ee.hasAppearances){const ut={zoom:g.transform.zoom,pitch:g.transform.pitch,brightness:g.style.getBrightness()||0,worldview:g.worldview},ft=ee.updateAppearances(this.tileID.canonical,Ee,P,ut,g.imageManager,Qe&&ee.stateDependentLayers.length!==0);if(ft&&ft.hasUboChanges){const Bt=g.context;ee instanceof Hg&&ee.text&&ee.text.uboBinder&&ee.text.uboBinder.upload(Bt),ee instanceof Hg&&ee.icon&&ee.icon.uboBinder&&ee.icon.uboBinder.upload(Bt)}}(ee instanceof M7||ee instanceof h7)&&g._terrain&&g._terrain.enabled&&me&&ee.uploadPending()&&g._terrain._clearRenderCacheForTile(me.id,this.tileID);const at=g&&g.style&&g.style.getOwnLayer(W);at&&(this.queryPadding=Math.max(this.queryPadding,at.queryRadius(ee)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;we--){const Ee=4*we,Fe=E_[Ee+0],Qe=E_[Ee+1],Ve=E_[Ee+2],at=E_[Ee+3],ut=Fe+Ve>>1,ft=Qe+at>>1,Bt=ut+ft-Qe,Et=ft+Fe-ut,Ot=Qe*f0+Fe,Lt=at*f0+Ve,Pt=ft*f0+ut,hs=Math.hypot((p0[2*Ot+0]+p0[2*Lt+0])/2-p0[2*Pt+0],(p0[2*Ot+1]+p0[2*Lt+1])/2-p0[2*Pt+1])>=16;A_[Pt]=A_[Pt]||(hs?1:0),we<1022&&(A_[Pt]=A_[Pt]||A_[(Qe+Et>>1)*f0+(Fe+Bt>>1)]||A_[(at+Et>>1)*f0+(Ve+Bt>>1)])}const ee=new $d,se=new ll;let ae=0;function me(we,Ee){const Fe=Ee*f0+we;return Q7[Fe]===0&&(ee.emplaceBack(p0[2*Fe+0],p0[2*Fe+1],we*fr/Sx,Ee*fr/Sx),Q7[Fe]=++ae),Q7[Fe]-1}function ge(we,Ee,Fe,Qe,Ve,at){const ut=we+Fe>>1,ft=Ee+Qe>>1;if(Math.abs(we-Ve)+Math.abs(Ee-at)>1&&A_[ft*f0+ut])ge(Ve,at,we,Ee,ut,ft),ge(Fe,Qe,Ve,at,ut,ft);else{const Bt=me(we,Ee),Et=me(Fe,Qe),Ot=me(Ve,at);se.emplaceBack(Bt,Et,Ot)}}return ge(0,0,Sx,Sx,Sx,0),ge(Sx,Sx,0,0,0,Sx),{vertices:ee,indices:se}}(this.tileID.canonical,u);_=M.vertices,C=M.indices}else{_=new $d,C=new ll;for(const{x:P,y:B}of f)_.emplaceBack(P,B,0,0);const M=pT(_.int16.subarray(0,4*_.length),void 0,4);for(let P=0;P0&&(P=N(new Float64Array(16),u.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(g,_,u,C,P,M),this._makeGlobeTileDebugTextBuffer(g,_,u,C,P,M)}_globePoint(g,u,f,_,C,M,P){let B=KP(g,u,f);if(M){const U=1<.5?ae=-1:se<-.5&&(ae=1);let me=(g/fr+f.x)/U+ae,ge=(u/fr+f.y)/U;me=(me-W)*_._pixelsPerMercatorPixel+W,ge=(ge-ee)*_._pixelsPerMercatorPixel+ee;const we=[me*_.worldSize,ge*_.worldSize,0];et(we,we,M),B=y1(B,we,P)}return et(B,B,C)}_makeGlobeTileDebugBorderBuffer(g,u,f,_,C,M){const P=new om,B=new p1,U=new jx,W=(se,ae,me,ge,we)=>{const Ee=(me-se)/(we-1),Fe=(ge-ae)/(we-1),Qe=P.length;for(let Ve=0;VeW*se+ae;for(let se=0;se1)return!1;const f=u.getSource().maxzoom,_=1<1)return u;const C=_.getSource().maxzoom,M=1<{const B=this.getAtTileOffset(g,C,M,P),U=_.upVector(g.canonical,C.x,C.y);return be(U,U,B*_.upVectorScale(g.canonical,u,f).metersToTile),U}}getForTilePoints(g,u,f,_){if(this.isUsingMockSource())return!1;const C=TT.create(this,g,_);return!!C&&(u.forEach(M=>{M[2]=this.exaggeration()*C.getElevationAt(M[0],M[1],f)}),!0)}getMinMaxForTile(g){if(this.isUsingMockSource())return null;const u=this.findDEMTileFor(g);if(!u||!u.dem)return null;const f=u.dem.tree,_=u.tileID,C=1<0&&(_+=(g[C]-0)*(g[C]-0)),u[C]<0&&(_+=(0-u[C])*(0-u[C]));return _},o.cL=function(g){return g*g*g*g*g},o.cM=as,o.cN=45,o.cO=hT,o.cP=function(g,u,f){const _=Math.sqrt(g*g+u*u+f*f),C=_>0?Math.acos(f/_)*hr:0;let M=g!==0||u!==0?Math.atan2(-u,-g)*hr+90:0;return M<0&&(M+=360),[_,M,C]},o.cQ=le,o.cR=un,o.cS=Us,o.cT=ne,o.cU=fi,o.cV=ie,o.cW=function(g){return[Math.pow(g[0],1/2.2),Math.pow(g[1],1/2.2),Math.pow(g[2],1/2.2)]},o.cX=aIe,o.cY=yye,o.cZ=dIe,o.c_=Zye,o.ca=2,o.cb=7,o.cc=6,o.cd=xe,o.ce=X,o.cf=Z,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=fT,o.cl=lm,o.cm=oIe,o.cn=oN,o.co=RAe,o.cp=function(g,u,f,_,C,M,P,B,U){if(U.name==="globe")return RAe(g,u,new oN(f,_,C),!1);const W=fN({z:f,x:_,y:C},U);return new fi([(M+W.x/W.scale)*u,u*(W.y/W.scale),P],[(M+W.x2/W.scale)*u,u*(W.y2/W.scale),B])},o.cq=function(g,u,f){return g[0]=Math.min(u[0],f[0]),g[1]=Math.min(u[1],f[1]),g[2]=Math.min(u[2],f[2]),g[3]=Math.min(u[3],f[3]),g},o.cr=function(g,u,f){return g[0]=Math.max(u[0],f[0]),g[1]=Math.max(u[1],f[1]),g[2]=Math.max(u[2],f[2]),g[3]=Math.max(u[3],f[3]),g},o.cs=function(g){const u=Math.round((g+45+360)%360/90)%4;return Gt[u]},o.ct=ks,o.cu=Ke,o.cv=6,o.cw=function(g){const u=b(new Float64Array(16));S(u,g.pixelMatrix,g.globeMatrix);const f=[0,Tt,0],_=[0,$t,0];return et(f,f,u),et(_,_,u),[f[0]>0&&f[0]<=g.width&&f[1]>0&&f[1]<=g.height&&!Bge(g,new qt(g.center.lat,90)),_[0]>0&&_[0]<=g.width&&_[1]>0&&_[1]<=g.height&&!Bge(g,new qt(g.center.lat,-90))]},o.cx=function(g,u){const{scale:f}=g.tileTransform,_=f*fr/(g.tileSize*Math.pow(2,u.zoom-g.tileID.overscaledZ+g.tileID.canonical.z));return function(C,M,P){var B=M[1],U=M[2],W=M[3],ee=P[0],se=P[1];return C[0]=M[0]*ee,C[1]=B*ee,C[2]=U*se,C[3]=W*se,C}(new Float32Array(4),u.inverseAdjustmentMatrix,[_,_])},o.cy=k7,o.cz=K,o.d=function(g){return ba.API_TILEJSON_REGEX.test(g)},o.d$=Nyt,o.d0=Vo,o.d1=class{static calculate(g,u,f){const _=new Set,C=new Map,M=new Set,P=new Set;for(const U of Object.values(g))for(const[W,ee]of Object.entries(U.floors)){M.add(W),ee.isDefault&&P.add(W),ee.conflicts&&C.set(W,ee.conflicts);const se=W===u,ae=ee.connections&&u&&ee.connections.has(u);(se||ae)&&_.add(W)}const B=U=>{const W=C.get(U)||new Set;for(const ee of _)if((C.get(ee)||new Set).has(U)||W.has(ee))return!0;return!1};if(f)for(const U of f)M.has(U)&&(B(U)||_.add(U));for(const U of P)_.has(U)||B(U)||_.add(U);return _}},o.d2=R7,o.d3=Oye,o.d4=qa,o.d5=function(){return{API_URL:ba.API_URL,DRACO_URL:ba.DRACO_URL,MESHOPT_URL:ba.MESHOPT_URL,MESHOPT_SIMD_URL:ba.MESHOPT_SIMD_URL,BUILDING_GEN_URL:ba.BUILDING_GEN_URL}},o.d6=Rz,o.d7=m2,o.d8=yx,o.d9=xr,o.dA=r7,o.dB=om,o.dC=ll,o.dD=function(g,u){return[Math.pow(g[0],2.2)*u,Math.pow(g[1],2.2)*u,Math.pow(g[2],2.2)*u]},o.dE=m,o.dF=function(g,u){var f=Math.sin(u),_=Math.cos(u);return g[0]=_,g[1]=f,g[2]=0,g[3]=-f,g[4]=_,g[5]=0,g[6]=0,g[7]=0,g[8]=1,g},o.dG=fe,o.dH=FAe,o.dI=bi,o.dJ=eo,o.dK=Kye,o.dL=function(g,u){const f=[0,0,0];return et(f,f,YP(d0(u.canonical))),et(f,f,g),f},o.dM=g=>({u_matrix:new p(g),u_texsize:new Mf(g),u_pixels_to_tile_units:new O(g),u_device_pixel_ratio:new sc(g),u_width_scale:new sc(g),u_floor_width_scale:new sc(g),u_image:new aN(g),u_units_to_pixels:new Mf(g),u_tile_units_to_pixels:new sc(g),u_alpha_discard_threshold:new sc(g),u_trim_offset:new Mf(g),u_trim_fade_range:new Mf(g),u_trim_gradient_mix_range:new Mf(g),u_trim_color:new hT(g),u_zbias_factor:new sc(g),u_tile_to_meter:new sc(g),u_ground_shadow_factor:new iN(g),u_pattern_transition:new sc(g)}),o.dN=g=>({u_matrix:new p(g),u_pixels_to_tile_units:new O(g),u_device_pixel_ratio:new sc(g),u_width_scale:new sc(g),u_floor_width_scale:new sc(g),u_units_to_pixels:new Mf(g),u_dash_image:new aN(g),u_gradient_image:new aN(g),u_image_height:new sc(g),u_texsize:new Mf(g),u_tile_units_to_pixels:new sc(g),u_alpha_discard_threshold:new sc(g),u_trim_offset:new Mf(g),u_trim_fade_range:new Mf(g),u_trim_gradient_mix_range:new Mf(g),u_trim_color:new hT(g),u_zbias_factor:new sc(g),u_tile_to_meter:new sc(g),u_ground_shadow_factor:new iN(g)}),o.dO=g=>({u_camera_to_center_distance:new sc(g),u_extrude_scale:new O(g),u_device_pixel_ratio:new sc(g),u_matrix:new p(g),u_inv_rot_matrix:new p(g),u_merc_center:new Mf(g),u_tile_id:new iN(g),u_zoom_transition:new sc(g),u_up_dir:new iN(g),u_emissive_strength:new sc(g)}),o.dP=RP,o.dQ=jvt,o.dR=class{constructor(g,u,f,_){this.context=g,this.format=_,this.size=f,this.texture=g.gl.createTexture();const[C,M,P]=this.size,{gl:B}=g;B.bindTexture(B.TEXTURE_3D,this.texture),g.pixelStoreUnpackFlipY.set(!1),g.pixelStoreUnpack.set(1),g.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in u&&u.data&&B.texImage3D(B.TEXTURE_3D,0,this.format,C,M,P,0,uye(this.format),hye(this.format),u.data)}bind(g,u){const{context:f}=this,{gl:_}=f;_.bindTexture(_.TEXTURE_3D,this.texture),g!==this.minFilter&&(_.texParameteri(_.TEXTURE_3D,_.TEXTURE_MAG_FILTER,g),_.texParameteri(_.TEXTURE_3D,_.TEXTURE_MIN_FILTER,g),this.minFilter=g),u!==this.wrapS&&(_.texParameteri(_.TEXTURE_3D,_.TEXTURE_WRAP_S,u),_.texParameteri(_.TEXTURE_3D,_.TEXTURE_WRAP_T,u),this.wrapS=u)}destroy(){const{gl:g}=this.context;g.deleteTexture(this.texture),this.texture=null}},o.dS=UAe,o.dT=(g,u,f,_,C,M)=>{const P=g.transform,B=P.projection.name==="globe";let U;if(M.paint.get("circle-pitch-alignment")==="map")if(B){const ee=FAe(P.zoom,u.canonical)*P._pixelsPerMercatorPixel;U=Float32Array.from([ee,0,0,ee])}else U=P.calculatePixelsToTileUnitsMatrix(f);else U=new Float32Array([P.pixelsToGLUnits[0],0,0,P.pixelsToGLUnits[1]]);const W={u_camera_to_center_distance:g.transform.getCameraToCenterDistance(P.projection),u_matrix:g.translatePosMatrix(u.projMatrix,f,M.paint.get("circle-translate"),M.paint.get("circle-translate-anchor")),u_device_pixel_ratio:ju.devicePixelRatio,u_extrude_scale:U,u_inv_rot_matrix:Ayt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:M.paint.get("circle-emissive-strength")};if(B){W.u_inv_rot_matrix=_,W.u_merc_center=C,W.u_tile_id=[u.canonical.x,u.canonical.y,1<{const ee=g.transform,se=ee.pitch<15?jIe(.07,.7,ze((14-ee.zoom)/5,0,1)):.07,ae=f.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:kIe(g,u,f,_),u_texsize:u.imageAtlasTexture?u.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:ee.calculatePixelsToTileUnitsMatrix(u),u_device_pixel_ratio:C,u_width_scale:M,u_floor_width_scale:P,u_image:0,u_tile_units_to_pixels:NIe(u,ee),u_units_to_pixels:[1/ee.pixelsToGLUnits[0],1/ee.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:B,u_trim_fade_range:f.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:f.paint.get("line-trim-color").toPremultipliedRenderColor(ae?null:f.lut).toArray01(),u_zbias_factor:se,u_tile_to_meter:Us(u.tileID.canonical,0),u_ground_shadow_factor:U,u_pattern_transition:W}},o.dX=(g,u,f,_,C,M,P,B,U,W)=>{const ee=g.transform,se=ee.calculatePixelsToTileUnitsMatrix(u),ae=f.paint.get("line-trim-color-use-theme").constantOr("default")==="none",me=ee.pitch<15?jIe(.07,.7,ze((14-ee.zoom)/5,0,1)):.07;return{u_matrix:kIe(g,u,f,_),u_pixels_to_tile_units:se,u_device_pixel_ratio:M,u_width_scale:P,u_floor_width_scale:B,u_units_to_pixels:[1/ee.pixelsToGLUnits[0],1/ee.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:C,u_texsize:CIe(f)&&u.lineAtlasTexture?u.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:NIe(u,g.transform),u_alpha_discard_threshold:0,u_trim_offset:U,u_trim_fade_range:f.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:f.paint.get("line-trim-color").toPremultipliedRenderColor(ae?null:f.lut).toArray01(),u_zbias_factor:me,u_tile_to_meter:Us(u.tileID.canonical,0),u_ground_shadow_factor:W}},o.dY=Vt,o.dZ=ZP,o.d_=vs,o.da=function(g){const u=g.indexOf(K2);return u>=0?g.slice(0,u):g},o.db=function(g){return g.indexOf(K2)>=0},o.dc=function(g){const u=g.lastIndexOf(K2);return u>=0?g.slice(u+1):""},o.dd=function(g){const u=[],f=g.id;return f===void 0&&u.push({message:`layers.${f}: missing required property "id"`}),g.render===void 0&&u.push({message:`layers.${f}: missing required method "render"`}),g.renderingMode&&g.renderingMode!=="2d"&&g.renderingMode!=="3d"&&u.push({message:`layers.${f}: property "renderingMode" must be either "2d" or "3d"`}),u},o.de=function(g,u,f,_){return g.type==="custom"?new x1t(g,u):new _1t[g.type](g,u,f,_)},o.df=Cs,o.dg=eT,o.dh=Vz,o.di=class extends xN{constructor(g,u){super(g._vectorTileFeature,g._z,g._x,g._y,g.id),g.state&&(this.state=Object.assign({},g.state)),this.target=u.target,this.namespace=u.namespace,u.properties&&(this.properties=u.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=g.source,this.sourceLayer=g.sourceLayer,this.layer=g.layer)}toJSON(){const g=super.toJSON();return g.target=this.target,g.namespace=this.namespace,g}},o.dj=bP,o.dk=function(g){return g({pluginStatus:Cu,pluginURL:Fm}),bP.on("pluginStateChange",g),g},o.dl=Pge,o.dm=class extends Af{constructor(g){super(g),this.current=j}set(g,u,f){if(this.fetchUniformLocation(g,u)){for(let _=0;_<9;_++)if(f[_]!==this.current[_]){this.current=f,this.gl.uniformMatrix3fv(this.location,!1,f);break}}}},o.dn=gr,o.dp=function(g,u,f){const _=v1(f.zoom),C=g.style.map._antialias,M=g.terrain&&g.terrain.exaggeration()>0;return _===0&&!C&&!M},o.dq=function(g){const u=g.pixelsPerMeter,f=u/Qt(1,g.center.lat),_=b(new Float64Array(16));return T(_,_,[g.point.x,g.point.y,0]),A(_,_,[f,f,u]),Float32Array.from(_)},o.dr=n7,o.ds=function(g){const u=80.051129;g=ze(g,-80.051129,u)/u*90;const f=Math.pow(Math.abs(Math.sin(Pr(g))),3);return Math.round(f*(Ut.length-1))},o.dt=function(g,u,f,_){const C=u.getNorth(),M=u.getSouth(),P=u.getWest(),B=u.getEast(),U=1<0){const ge=180/_;y(me,me,[ge/W+1,0,0,0,ge/ee+1,0,-.5*ge/se,.5*ge/ae,1])}return me[2]=U,me[5]=g.x,me[8]=g.y,me},o.du=YP,o.dv=d0,o.dw=function(g,u,f){const _=b(new Float64Array(16)),C=(u/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(g,u=!1){const f=wMe(new ss(0,0),new ss(fr,fr),g),_=[];if(u&&!eye(f,this._globalClipBounds))return _;for(const C of this._activeRegions){if(C.hiddenByOverlap||!eye(f,C))continue;const M=h0t(C.min,C.max,g);_.push({min:M.min,max:M.max,sourceId:this._sourceIds[C.priority],footprint:C.footprint,footprintTileId:C.tileId,order:C.order,clipMask:C.clipMask,clipScope:C.clipScope})}return _}setSources(g){this._setSources(g.map(u=>({getSourceId:()=>u.cache.id,getFootprints:()=>{const f=[];for(const _ of u.cache.getVisibleCoordinates()){const C=u.cache.getTile(_).buckets[u.layer];C&&C.updateFootprints(_.toUnwrapped(),f)}return f},getOrder:()=>u.order,getClipMask:()=>u.clipMask,getClipScope:()=>u.clipScope})))}_addSource(g){const u=g.getFootprints();if(u.length===0)return;const f=g.getOrder(),_=g.getClipMask(),C=g.getClipScope();for(const M of u){if(!M.footprint)continue;const P=wMe(M.footprint.min,M.footprint.max,M.id);this._activeRegions.push({min:P.min,max:P.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:M.id,footprint:M.footprint,order:f,clipMask:_,clipScope:C})}this._sourceIds.push(g.getSourceId())}_computeReplacement(){this._activeRegions.sort((u,f)=>u.priority-f.priority||f7(u.min,f.min)||f7(u.max,f.max)||u.order-f.order||u.clipMask-f.clipMask||function(_,C){const M=(P,B)=>P+B;return _.length-C.length||_.reduce(M,"").localeCompare(C.reduce(M,""))}(u.clipScope,f.clipScope));let g=this._activeRegions.length!==this._prevRegions.length;if(!g){let u=0;for(;!g&&u!==this._activeRegions.length;){const f=this._activeRegions[u],_=this._prevRegions[u];g=f.priority!==_.priority||!_Me(f,_)||f.order!==_.order||f.clipMask!==_.clipMask||!ta(f.clipScope,_.clipScope),this._activeRegions[u].hiddenByOverlap=_.hiddenByOverlap,++u}}if(g){++this._updateTime;for(const f of this._activeRegions)f.order!==n6&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,f.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,f.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,f.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,f.max.y));const u=f=>{const _=this._activeRegions;if(f>=_.length)return f;const C=_[f].priority;for(;f<_.length&&_[f].priority===C;)++f;return f};if(this._sourceIds.length>1){let f=0,_=u(f);for(;f!==_;){let C=f;const M=f;for(;C!==_;){const P=this._activeRegions[C];P.hiddenByOverlap=!1;for(let B=0;B=0;u--)this._addSource(g[u]);this._computeReplacement()}},o.eH=$d,o.eI=W7,o.eJ=p1,o.eK=n6,o.eL=class{constructor(g){this._createGrid(g),this._createPoles(g)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const g of this._poleSegments)g.destroy();for(const g of this._gridSegments)g.withSkirts.destroy(),g.withoutSkirts.destroy()}_fillGridMeshWithLods(g,u){const f=new om,_=new ll,C=[],M=g+1+2,P=u[0]+1,B=u[0]+1+(1+u.length),U=(W,ee,se)=>{let ae=W===M-1?W-2:W===0?W:W-1;return ae+=se?24575:0,[ae,ee]};for(let W=0;W>>=0,g=Math.imul(2747636419^g,2654435769)>>>0,g=Math.imul(g^g>>>16,2654435769)>>>0,(g=Math.imul(g^g>>>16,2654435769)>>>0)/4294967296},o.ec=PAe,o.ed=Oge,o.ee=Tf,o.ef=D,o.eg=function(g,u){return g[0]=u[0],g[1]=u[1],g[2]=u[2],g[3]=u[4],g[4]=u[5],g[5]=u[6],g[6]=u[8],g[7]=u[9],g[8]=u[10],g},o.eh=m1,o.ei=eN,o.ej=function(g,u,f,_,C){return ze((g-u)/(f-u)*(C-_)+_,_,C)},o.ek=ns,o.el=function(g,u){var f=u[0],_=u[1],C=u[2],M=u[3],P=u[4],B=u[5],U=u[6],W=u[7],ee=u[8],se=ee*P-B*W,ae=-ee*M+B*U,me=W*M-P*U,ge=f*se+_*ae+C*me;return ge?(g[0]=se*(ge=1/ge),g[1]=(-ee*_+C*W)*ge,g[2]=(B*_-C*P)*ge,g[3]=ae*ge,g[4]=(ee*f-C*U)*ge,g[5]=(-B*f+C*M)*ge,g[6]=me*ge,g[7]=(-W*f+_*U)*ge,g[8]=(P*f-_*M)*ge,g):null},o.em=yz,o.en=2,o.eo=He,o.ep=Xe,o.eq=z,o.er=function(g,u){var f=new d(3);z(f,u);var _=1/f[0],C=1/f[1],M=1/f[2],P=u[0]*_,B=u[1]*C,U=u[2]*M,W=u[4]*_,ee=u[5]*C,se=u[6]*M,ae=u[8]*_,me=u[9]*C,ge=u[10]*M,we=P+ee+ge,Ee=0;return we>0?(Ee=2*Math.sqrt(we+1),g[3]=.25*Ee,g[0]=(se-me)/Ee,g[1]=(ae-U)/Ee,g[2]=(B-W)/Ee):P>ee&&P>ge?(Ee=2*Math.sqrt(1+P-ee-ge),g[3]=(se-me)/Ee,g[0]=.25*Ee,g[1]=(B+W)/Ee,g[2]=(ae+U)/Ee):ee>ge?(Ee=2*Math.sqrt(1+ee-P-ge),g[3]=(ae-U)/Ee,g[0]=(B+W)/Ee,g[1]=.25*Ee,g[2]=(se+me)/Ee):(Ee=2*Math.sqrt(1+ge-P-ee),g[3]=(B-W)/Ee,g[0]=(ae+U)/Ee,g[1]=(se+me)/Ee,g[2]=.25*Ee),g},o.es=function(g,u){var f=2*Math.acos(u[3]),_=Math.sin(f/2);return _>c?(g[0]=u[0]/_,g[1]=u[1]/_,g[2]=u[2]/_):(g[0]=1,g[1]=0,g[2]=0),f},o.et=Jye,o.eu=T7,o.ev=C7,o.ew=[1,1,1],o.ex=TT,o.ey=function(g,u,f,_){var C=u[0],M=u[1],P=u[2],B=u[3];return g[0]=C+_*(f[0]-C),g[1]=M+_*(f[1]-M),g[2]=P+_*(f[2]-P),g[3]=B+_*(f[3]-B),g},o.ez=bT,o.f=qo,o.f0=zAe,o.f1=function(g){const u=[0,0,0],f=b(new Float64Array(16));return S(f,g.pixelMatrix,g.globeMatrix),et(u,u,f),new ss(u[0],u[1])},o.f2=_P,o.f3=function(g,u,f=!1){if(Cu===im.deferred||Cu===im.loading||Cu===im.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Fm=ju.resolveURL(g),Cu=im.deferred,wx=u,vP(),f||Oz()},o.f4=Ci,o.f5=ra,o.f6=ir,o.f7=function(g){const u=Cg();if(!u)return;const f=u.delete(Im);g&&f.then(()=>g()).catch(g)},o.f8=Dr,o.f9=j_,o.fA=Dn,o.fB=function(g){let u=0;if(new Uint32Array(g,0,1)[0]!==eIe){const f=new Uint32Array(g,0,7),[,,_,C,M,P]=f;u=f.byteLength+C+M+P+M,(_!==g.byteLength||u>=g.byteLength)&&Rr("Invalid b3dm header information.")}return nIe(g,u)},o.fC=function(g,u){const f=yye(g);for(const _ of f){for(const C of _.meshes)q0t(C);_.lights&&(_.lightMeshIndex=_.meshes.length,_.meshes.push(V0t(_.lights,u)))}return f},o.fD=X7,o.fE=fa,o.fF=Fg,o.fG=im,o.fH=function(g){lp(),Nu!=null&&Nu.then(u=>{u.keys().then(f=>{for(let _=0;_Rr(C.message))}).catch(f=>Rr(f.message))}).catch(u=>Rr(u.message))},o.fa=2,o.fb=Dg,o.fc=fN,o.fd=UP,o.fe=VLe,o.ff=HLe,o.fg=vIe,o.fh=ea,o.fi="hd_road_elevation",o.fj=qi,o.fk=qs,o.fl=h7,o.fm=b1,o.fn=Dye,o.fo=1,o.fp=Hg,o.fq=function(g,u,f,_,C,M,P,B=1,U,W,ee,se){g.createArrays(),g.tilePixelRatio=fr/(512*g.overscaling),g.compareText={},g.iconsNeedLinear=!1;const ae=g.layers[0].layout,me=g.layers[0]._unevaluatedLayout._values,ge={};ge.scaleFactor=B,ge.textSizeScaleRange=ae.get("text-size-scale-range"),ge.iconSizeScaleRange=ae.get("icon-size-scale-range");const[we,Ee]=ge.textSizeScaleRange,[Fe,Qe]=ge.iconSizeScaleRange;ge.textScaleFactor=ze(ge.scaleFactor,we,Ee),ge.iconScaleFactor=ze(ge.scaleFactor,Fe,Qe);const Ve=me["text-size"],at=me["icon-size"];if(g.textSizeData.kind==="composite"){const{minZoom:Lt,maxZoom:Pt}=g.textSizeData;ge.compositeTextSizes=[Ve.possiblyEvaluate(new ui(Lt,{worldview:ee}),M),Ve.possiblyEvaluate(new ui(Pt,{worldview:ee}),M)]}if(g.iconSizeData.kind==="composite"){const{minZoom:Lt,maxZoom:Pt}=g.iconSizeData;ge.compositeIconSizes=[at.possiblyEvaluate(new ui(Lt,{worldview:ee}),M,se),at.possiblyEvaluate(new ui(Pt,{worldview:ee}),M,se)]}ge.layoutTextSize=Ve.possiblyEvaluate(new ui(P+1,{worldview:ee}),M),ge.layoutIconSize=at.possiblyEvaluate(new ui(P+1,{worldview:ee}),M,se),ge.textMaxSize=Ve.possiblyEvaluate(new ui(18,{worldview:ee}),M);const ut=ae.get("symbol-placement"),ft=ae.get("text-rotation-alignment")==="map"&&ut!=="point",Bt=ae.get("text-size");let Et=!1;const Ot=[];for(const Lt of g.features){const Pt=ae.get("text-font").evaluate(Lt,{},M).join(","),hs=Bt.evaluate(Lt,{},M)*ge.textScaleFactor,bs=ge.layoutTextSize.evaluate(Lt,{},M)*ge.textScaleFactor,Ts=ge.layoutIconSize.evaluate(Lt,{},M,se)*ge.iconScaleFactor,Rs={horizontal:{},vertical:void 0},Es=Lt.text;let Ws,ls=[0,0];if(Es){const ca=Es.toString(),Ho=ae.get("text-letter-spacing").evaluate(Lt,{},M)*Ic,hi=ae.get("text-line-height").evaluate(Lt,{},M)*Ic,Za=bge(ca)?Ho:0,Ui=ae.get("text-anchor").evaluate(Lt,{},M),Io=ae.get("text-variable-anchor");if(!Io){const dl=ae.get("text-radial-offset").evaluate(Lt,{},M);if(dl)ls=nLe(Ui,[dl*Ic,Bye]);else{const qd=ae.get("text-offset").evaluate(Lt,{},M);ls=[qd[0]*Ic,qd[1]*Ic]}}let Lc=ft?"center":ae.get("text-justify").evaluate(Lt,{},M);const Lo=ut==="point",cl=Lo?ae.get("text-max-width").evaluate(Lt,{},M)*Ic:1/0,Pl=dl=>{g.allowVerticalPlacement&&xP(ca)&&(Rs.vertical=Tye(Es,u,f,C,Pt,cl,hi,Ui,dl,Za,ls,Hm.vertical,!0,bs,hs,U,ge.textScaleFactor))};if(!ft&&Io){const dl=Lc==="auto"?Io.map(Pc=>zye(Pc)):[Lc];let qd=!1;for(let Pc=0;Pc=0||!xP(ca)){const dl=Tye(Es,u,f,C,Pt,cl,hi,Ui,Lc,Za,ls,Hm.horizontal,!1,bs,hs,U,ge.textScaleFactor);dl&&(Rs.horizontal[Lc]=dl)}Pl(Lo?"left":Lc)}}let Ps,zs,Ks,tr,Ar,ur,dr=!1;const sr=ae.get("icon-text-fit").evaluate(Lt,{},M);if(Lt.icon&&Lt.icon.hasPrimary()){const ca=v6(Lt.icon,g.iconSizeData,me["icon-size"],M,g.zoom,Lt,U,ge.iconScaleFactor,ee,se);Ps=ca.iconPrimary,Ks=ca.iconSecondary;const Ho=Ps.toString();if(zs=_.get(Ho),zs&&(Ar=ae.get("icon-offset").evaluate(Lt,{},M),ur=ae.get("icon-anchor").evaluate(Lt,{},M),Ws=P7(C.get(Ho),Ks?C.get(Ks.toString()):void 0,Ar,ur),dr=zs.sdf,g.sdfIcons===void 0?g.sdfIcons=zs.sdf:g.sdfIcons!==zs.sdf&&Rr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(zs.pixelRatio!==g.pixelRatio||ae.get("icon-rotate").constantOr(1)!==0)&&(g.iconsNeedLinear=!0)),Ks){const hi=Ks.toString();tr=_.get(hi)}}Et=Et||!(!Lt.icon||!Lt.icon.hasSecondary());const Tr=$7(Rs.horizontal)||Rs.vertical;g.iconsInText||(g.iconsInText=!!Tr&&Tr.iconsInText);const zr=bs*ge.textScaleFactor/Ic,{defaultShapedIcon:mn,verticallyShapedIcon:Gr}=e1t(g,Ws,ae,Lt,M,Rs,zr,Ar,sr);sr!=="none"&&Ws&&(zIe(Ws)||$Ie(Ws))&&(z7(0,zs,Ps,Ws,mn,sr,W,_,C),z7(0,tr,Ks,Ws,mn,sr,W,_,C),Gr&&(z7(0,zs,Ps,Ws,Gr,sr,W,_,C),z7(0,tr,Ks,Ws,Gr,sr,W,_,C))),Ws=mn;const{iconBBox:Vn,iconVerticalBBox:$a,textBBox:Hn,textVerticalBBox:Va}=Yvt(g,Ws,Gr,ae,Lt,M,Ts,Ar,ge,C,ur,Rs,bs,ls,se);Ot.push({feature:Lt,shapedTextOrientations:Rs,shapedText:Tr,shapedIcon:Ws,iconPrimary:Ps,iconSecondary:Ks,iconOffset:Ar,iconAnchor:ur,verticallyShapedIcon:Gr,layoutTextSize:bs,layoutIconSize:Ts,textOffset:ls,isSDFIcon:dr,iconTextFit:sr,iconCollisionBounds:Vn,iconVerticalCollisionBounds:$a,textCollisionBounds:Hn,textVerticalCollisionBounds:Va})}return{featureData:Ot,sizes:ge,hasAnySecondaryIcon:Et,textAlongLine:ft,symbolPlacement:ut}},o.fr=Rye,o.fs=Pye,o.ft=ZIe,o.fu=XIe,o.fv=function(g,u,f,_,C,M,P,B,U,W){g.iconAtlasPositions=W.iconPositions;const{featureData:ee,hasAnySecondaryIcon:se,sizes:ae,textAlongLine:me,symbolPlacement:ge}=u;for(const we of ee){const{shapedIcon:Ee,verticallyShapedIcon:Fe,feature:Qe,shapedTextOrientations:Ve,shapedText:at,layoutTextSize:ut,textOffset:ft,isSDFIcon:Bt,iconPrimary:Et,iconSecondary:Ot,iconTextFit:Lt,iconOffset:Pt,iconCollisionBounds:hs,iconVerticalCollisionBounds:bs,textCollisionBounds:Ts}=we;lLe(Ee,W.iconPositions,Et,Ot),lLe(Fe,W.iconPositions,Et,Ot),Jvt(Ve,W.iconPositions),Qvt(Et,Ot,W.iconPositions),(at||Ee)&&t1t(g,Qe,Ve,Ee,Fe,U,ae,ut,0,ft,Bt,_,C,P,B,se,Lt,Pt,me,ge,hs,bs,Ts)}f&&g.generateCollisionDebugBuffers(M,g.collisionBoxArray,ae.textScaleFactor)},o.fw=M7,o.fx=ri,o.fy=function(g){return g<=1?1:Math.pow(2,Math.floor(Math.log2(g)))},o.fz=r9,o.g=ba,o.h=function(g,u){return Ky(Object.assign(g,{method:"GET"}),u)},o.i=function(g){return ba.API_STYLE_REGEX.test(g)&&!Xo(g)},o.j=function(g){return btoa(encodeURIComponent(g).replace(/%([0-9A-F]{2})/g,(u,f)=>String.fromCharCode(+("0x"+f))))},o.k=Lm,o.l=function(g){return decodeURIComponent(atob(g).split("").map(u=>"%"+("00"+u.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(g,u){return Ky(Object.assign(g,{type:"json"}),u)},o.n=Eg,o.o=ju,o.p=function(g,u){return Ky(Object.assign(g,{method:"POST"}),u)},o.q=cu,o.r=Wt,o.s=function(g){try{const u=self[g];return u.setItem("_mapbox_test_",1),u.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=At,o.u=function(){return function g(u){return u?(u^Math.random()*(16>>u/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,g)}()},o.v=function(g){return!!g&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g)},o.w=Rr,o.x=class{constructor(g){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(g&&g.maxTextureMemoryMB?g.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(u=>{this.cache.delete(u),this.clearExpiredTextures()})}calculateTextureMemory(g){return g.image?Math.ceil(g.image.width*g.image.height*4*(g.patternPositions.size>0?1.33:1)):0}evictTexture(g){const u=this.textures.get(g);if(u){const f=this.calculateTextureMemory(g);u.destroy(),this.textures.delete(g),this.textureAccessTimes.delete(g),this.textureMemoryUsed-=f}}evictTexturesIfNeeded(g){for(;this.textureMemoryUsed+g>this.maxTextureMemory&&this.textures.size>0;){let u=null,f=1/0;for(const[_]of this.textures.entries()){const C=this.textureAccessTimes.get(_)||0;Cthis._layers[xr.id]),Wt=Ft[0];if(Wt.visibility==="none")continue;const Vt=Wt.source||"";let Jt=this.familiesBySource[Vt];Jt||(Jt=this.familiesBySource[Vt]=Object.create(null));const qs=Wt.sourceLayer||"_geojsonTileLayer";let Cs=Jt[qs];Cs||(Cs=Jt[qs]=[]),Cs.push(Ft)}}}const v=1*c.fa;class w{constructor(Se){const ze={},st=[];for(const Wt in Se){const Vt=Se[Wt],Jt=ze[Wt]={};for(const qs in Vt.glyphs){const Cs=Vt.glyphs[+qs];if(!Cs||Cs.bitmap.width===0||Cs.bitmap.height===0)continue;const xr=Cs.metrics.localGlyph?v:1,Wr={x:0,y:0,w:Cs.bitmap.width+2*xr,h:Cs.bitmap.height+2*xr};st.push(Wr),Jt[qs]=Wr}}const{w:gt,h:At}=c.J(st),Ft=new c.f9({width:gt||1,height:At||1});for(const Wt in Se){const Vt=Se[Wt];for(const Jt in Vt.glyphs){const qs=Vt.glyphs[+Jt];if(!qs||qs.bitmap.width===0||qs.bitmap.height===0)continue;const Cs=ze[Wt][Jt],xr=qs.metrics.localGlyph?v:1;c.f9.copy(qs.bitmap,Ft,{x:0,y:0},{x:Cs.x+xr,y:Cs.y+xr},qs.bitmap)}}this.image=Ft,this.positions=ze}}function b(zt,Se,ze){zt[Se]?ze&&(zt[Se].center=ze):zt[Se]={floorIds:new Set,center:ze||[0,0],floors:{}}}function N(zt,Se,ze,st){for(const gt of Se)b(zt,gt),zt[gt].floors[ze]=st,zt[gt].floorIds.add(ze)}function S(zt){return{id:zt.properties.id.toString(),center:[zt.properties.center_lon||0,zt.properties.center_lat||0]}}function T(zt,Se){const ze=zt.properties.id.toString(),st=!!zt.properties.is_default&&zt.properties.is_default,gt=zt.properties.connected_floor_ids?new Set(zt.properties.connected_floor_ids.toString().split(";")):new Set,At=zt.properties.conflicted_floor_ids?new Set(zt.properties.conflicted_floor_ids.toString().split(";")):new Set,Ft=zt.properties.structure_ids?new Set(zt.properties.structure_ids.toString().split(";")):new Set,Wt=zt.properties.name.toString(),Vt=zt.properties.z_index,Jt=function(qs,Cs){const xr=qs.loadGeometry();if(!xr||xr.length===0)return;const Wr=xr.map(tn=>tn.map(Rr=>c.fb(Rr,Cs,qs.extent)));return Wr.length===0?void 0:{type:"Polygon",coordinates:[Wr[0]]}}(zt,Se);return{id:ze,isDefault:st,connections:gt,conflicts:At,buildings:Ft,name:Wt,zIndex:Vt,geometry:Jt}}function A(zt,Se){return Se.every(ze=>zt.properties&&zt.properties[ze]!=null)}function I(zt){return A(zt,["type","id","name"])&&zt.properties.type==="structure"}function D(zt){return A(zt,["type","id","name","z_index"])&&zt.properties.type==="floor"}c.f8(w,"GlyphAtlas");class R{constructor(Se){this.tileID=new c.aR(Se.tileID.overscaledZ,Se.tileID.wrap,Se.tileID.canonical.z,Se.tileID.canonical.x,Se.tileID.canonical.y),this.tileZoom=Se.tileZoom,this.uid=Se.uid,this.zoom=Se.zoom,this.lut=Se.lut,this.canonical=Se.tileID.canonical,this.pixelRatio=Se.pixelRatio,this.tileSize=Se.tileSize,this.source=Se.source,this.scope=Se.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Se.showCollisionBoxes,this.collectResourceTiming=!!Se.request&&Se.request.collectResourceTiming,this.promoteId=Se.promoteId,this.renderSourceType=Se.renderSourceType,this.tileTransform=c.fc(Se.tileID.canonical,Se.projection),this.projection=Se.projection,this.worldview=Se.worldview,this.localizableLayerIds=Se.localizableLayerIds,this.brightness=Se.brightness,this.extraShadowCaster=!!Se.extraShadowCaster,this.tessellationStep=Se.tessellationStep,this.scaleFactor=Se.scaleFactor,this.worldview=Se.worldview,this.indoor=Se.indoor}parse(Se,ze,st,gt,At,Ft){this.status="parsing",this.data=Se,this.collisionBoxArray=new c.fd;const Wt=new c.fe(Object.keys(Se.layers).sort()),Vt=new c.ff(this.tileID,this.promoteId);Vt.bucketLayerIDs=[];const Jt={},qs=new c.fg(256,256),Cs={featureIndex:Vt,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:qs,availableImages:st,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Cs.activeFloors=function(Rr,sn,rn,un){const fa=sn.indoorState.activeFloorsVisible;if(!sn.sourceLayers)return fa?sn.indoorState.activeFloors:void 0;const go=function(ia,Ji){if(!ia)return c.w("No source layers defined in indoor specification"),Ji;if(ia.size===0)return Ji;const il=ia.difference(Ji);for(const bi of il)c.w(`Missing source layer required in indoor specification: ${bi}`);return Ji.intersection(Ji)}(sn.sourceLayers,new Set(Object.keys(Rr.layers))),wo=sn.indoorState,co=function(ia,Ji,il,bi,eo){const no={};for(const ba of Ji){const ir=ia.layers[ba];if(ir)for(let ra=0;ra=bi.maxzoom||bi.visibility==="none")continue;$(il,this.zoom,Cs.brightness,st,this.worldview,Cs.activeFloors);const eo=Jt[bi.id]=bi.createBucket({index:Vt.bucketLayerIDs.length,layers:il,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:wo,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:gt,worldview:this.worldview,localizable:ia,availableImages:st,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});Vt.bucketLayerIDs.push(il.map(ba=>c.F(ba.id,ba.scope)));let no=eo.prepare?eo.prepare():null;no!=null?(no=no.then(()=>eo.populate(co,Cs,this.tileID.canonical,this.tileTransform)),xr.push(no)):eo.populate(co,Cs,this.tileID.canonical,this.tileTransform)}}const tn=()=>{qs.trim();const Rr=!(!Cs.elevationFeatures||!Cs.elevationFeatures.some(bi=>bi.heightRange.min<0));let sn,rn,un,fa,go,wo,co;const ia={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},Ji=()=>{if(sn)return this.status="done",Ft(sn);if(this.extraShadowCaster)this.status="done",Ft(null,{buckets:Object.values(Jt).filter(bi=>!bi.isEmpty()),featureIndex:Vt,collisionBoxArray:null,hasTunnelGeometry:Rr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Cs.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(rn&&un&&fa&&co){const eo=new w(rn),no=new Map;for(const[ra,Ci]of un.entries()){const{imagePosition:qo}=c.fn(ra,Ci,c.fo);no.set(ra,qo)}const ba={};for(const ra in Jt){const Ci=Jt[ra];Ci instanceof c.fp&&($(Ci.layers,this.zoom,Cs.brightness,st,this.worldview,Cs.activeFloors),ba[ra]=c.fq(Ci,rn,eo.positions,un,no,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,go,this.worldview,st))}const ir={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(At,un,go,()=>{ir.iconsPending=!1,il(ba,eo,ir,void 0,co)}),this.rasterizeIfNeeded(At,fa,wo,()=>{ir.patternsPending=!1,il(ba,eo,ir,void 0,co)})}},il=(bi,eo,no,ba,ir)=>{if(no.iconsPending||no.patternsPending)return;const ra=un.size>0||fa.size>0,Ci=Object.keys(bi).length>0;if(!ra&&!Ci)return this.status="done",void Ft(null,{buckets:Object.values(Jt).filter(Xo=>!Xo.isEmpty()),featureIndex:Vt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Rr,glyphAtlasImage:eo.image,lineAtlas:qs,imageAtlas:null,brightness:Cs.brightness});const qo=(Xo,ol)=>{for(const Kc in Jt){const nu=Jt[Kc];if(Kc in bi)c.fv(nu,bi[Kc],this.showCollisionBoxes,st,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,un,ol);else if(nu.hasPattern&&(nu instanceof c.fw||nu instanceof c.fl||nu instanceof c.e0)){$(nu.layers,this.zoom,Cs.brightness,st,this.worldview,Cs.activeFloors);const Nf=Object.fromEntries(ol.patternPositions);nu.addFeatures(Cs,this.tileID.canonical,Nf,st,this.tileTransform,this.brightness)}}this.status="done",Ft(null,{buckets:Object.values(Jt).filter(Kc=>!Kc.isEmpty()),featureIndex:Vt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Rr,glyphAtlasImage:eo.image,lineAtlas:qs,imageAtlas:Xo,brightness:Cs.brightness})};if(ra){const Xo=new Map,ol=c.fr(un,Xo),Kc=c.fr(fa,Xo),nu=new c.fs(ol,Kc,ir,this.lut,Xo);At.send("checkAtlasCache",{descriptor:nu,scope:this.scope},(Nf,Ah)=>{let kf,am;if(Nf&&c.w(`[Worker] Error checking atlas cache: ${Nf.message}`),Ah)kf=new c.ft(Ah.sourceHash),am=Ah;else{const ju=new c.fu(un,fa,this.lut,ir);kf=ju,am=ju}qo(kf,am)})}else qo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const bi=c.fk(Cs.glyphDependencies,ba=>Object.keys(ba).map(Number));Object.keys(bi).length?At.send("getGlyphs",{uid:this.uid,stacks:bi},(ba,ir)=>{sn||(sn=ba,rn=ir,Ji())},void 0,!1,ia):rn={},co=new Map;const eo=Array.from(Cs.iconDependencies.keys()).map(ba=>c.I.parse(ba));eo.length?At.send("getImages",{images:eo,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(ba,ir)=>{if(!sn){sn=ba,un=new Map,go=this.updateImageMapAndGetImageTaskQueue(un,ir.images,Cs.iconDependencies);for(const[ra,Ci]of ir.versions.entries())co.set(ra,Ci);Ji()}},void 0,!1,ia):(un=new Map,go=new Map);const no=Array.from(Cs.patternDependencies.keys()).map(ba=>c.I.parse(ba));no.length?At.send("getImages",{images:no,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(ba,ir)=>{if(!sn){sn=ba,fa=new Map,wo=this.updateImageMapAndGetImageTaskQueue(fa,ir.images,Cs.patternDependencies);for(const[ra,Ci]of ir.versions.entries())co.set(ra,Ci);Ji()}},void 0,!1,ia):(fa=new Map,wo=new Map)}if(Cs.elevationFeatures&&Cs.elevationFeatures.length>0){const bi=[];for(const no of Object.values(Jt))if(no instanceof c.fl){const ba=no.getUnevaluatedPortalGraph();ba&&bi.push(ba)}const eo=c.fm.evaluate(bi);for(const no of Object.values(Jt))if(no instanceof c.fl){const ba=Se.layers[Wt.decode(no.sourceLayerIndex)];no.setEvaluatedPortalGraph(eo,ba,this.tileID.canonical,Cs.availableImages,Cs.brightness)}}Ji()};xr.length>0?Promise.allSettled(xr).then(tn).catch(Ft):tn()}updateParameters(Se){this.scaleFactor=Se.scaleFactor,this.showCollisionBoxes=Se.showCollisionBoxes,this.projection=Se.projection,this.brightness=Se.brightness,this.tileTransform=c.fc(Se.tileID.canonical,Se.projection),this.extraShadowCaster=Se.extraShadowCaster,this.lut=Se.lut,this.worldview=Se.worldview,this.indoor=Se.indoor}rasterizeIfNeeded(Se,ze,st,gt){Array.from(ze.values()).some(At=>At.usvg)?this.rasterize(Se,ze,st,gt):gt()}updateImageMapAndGetImageTaskQueue(Se,ze,st){const gt=new Map;for(const At of ze.keys()){const Ft=st.get(At)||[];for(const Wt of Ft){const Vt=Wt.toString(),Jt=ze.get(Wt.id.toString());Jt.usvg?gt.has(Vt)||(gt.set(Vt,Wt),Se.set(Vt,Object.assign({},Jt))):Se.set(Vt,Jt)}}return gt}rasterize(Se,ze,st,gt){this.rasterizeTask=Se.send("rasterizeImages",{scope:this.scope,tasks:st},(At,Ft)=>{if(!At)for(const[Wt,Vt]of Ft.entries()){const Jt=Object.assign(ze.get(Wt),{data:Vt});ze.set(Wt,Jt)}gt()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function $(zt,Se,ze,st,gt,At){const Ft=new c.ae(Se,{brightness:ze,worldview:gt,activeFloors:At});for(const Wt of zt)Wt.recalculate(Ft,st)}class F extends c.E{constructor({actor:Se,layerIndex:ze,availableImages:st,availableModels:gt,isSpriteLoaded:At,tileProvider:Ft,brightness:Wt,maxUniformBufferBindings:Vt,maxUniformBlockSizeDwords:Jt,disableSymbolUBO:qs}){super(),this.actor=Se,this.layerIndex=ze,this.availableImages=st,this.availableModels=gt,this.loadVectorData=c.aO,this.tileProvider=Ft,this.loading={},this.loaded={},this.deduped=new c.aN(Se.scheduler),this.isSpriteLoaded=At,this.scheduler=Se.scheduler,this.brightness=Wt,this.maxUniformBufferBindings=Vt,this.maxUniformBlockSizeDwords=Jt,this.disableSymbolUBO=qs}loadTileData(Se,ze){if(!this.tileProvider)return this.loadVectorData(Se,ze);const st=new AbortController,{z:gt,x:At,y:Ft}=Se.tileID.canonical;return this.tileProvider.loadTile({z:gt,x:At,y:Ft},{request:Se.request,signal:st.signal}).then(Wt=>{if(st.signal.aborted)return;if(Wt==null){const Jt=new Error("Tile not found");return Jt.status=404,ze(Jt)}if(Wt.data===null)return ze(null,null);const Vt=new Map;Wt.expires&&Vt.set("expires",Wt.expires),Wt.cacheControl&&Vt.set("cache-control",Wt.cacheControl),ze(null,{rawData:Wt.data,responseHeaders:Vt})}).catch(Wt=>{st.signal.aborted||ze(Wt instanceof Error?Wt:new Error(String(Wt)))}),()=>st.abort()}loadTile(Se,ze){const st=Se.uid,gt=Se&&Se.request,At=gt&>.collectResourceTiming,Ft=this.loading[st]=new R(Se);Ft.maxUniformBufferBindings=this.maxUniformBufferBindings,Ft.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,Ft.disableSymbolUBO=this.disableSymbolUBO,Ft.abort=this.loadTileData(Se,(Wt,Vt)=>{const Jt=!this.loading[st];if(delete this.loading[st],Ft.cancelRasterize(),Jt||Wt||!Vt)return Ft.status="done",Jt||(this.loaded[st]=Ft),ze(Wt);const qs=Vt.rawData,Cs={},xr=c.aP(Vt.responseHeaders);xr&&xr.expires&&(Cs.expires=xr.expires),xr&&xr.cacheControl&&(Cs.cacheControl=xr.cacheControl),Ft.vectorTile=Vt.vectorTile||new c.fx(new c.a$(qs));const Wr=()=>{Ft.parse(Ft.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(tn,Rr)=>{if(tn||!Rr)return ze(tn);const sn={};if(At){const rn=d(gt);rn.length>0&&(sn.resourceTiming=JSON.parse(JSON.stringify(rn)))}ze(null,Object.assign({rawTileData:qs.slice(0),responseHeaders:Vt.responseHeaders},Rr,Cs,sn))})};this.isSpriteLoaded?Wr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Wr,{type:"parseTile",renderSourceType:Se.renderSourceType,zoom:Se.tileZoom}):Wr()}),this.loaded=this.loaded||{},this.loaded[st]=Ft})}reloadTile(Se,ze){const st=this.loaded,gt=Se.uid;if(st&&st[gt]){const At=st[gt];At.updateParameters(Se);const Ft=(Wt,Vt)=>{const Jt=At.reloadCallback;Jt&&(delete At.reloadCallback,At.parse(At.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Jt)),ze(Wt,Vt)};At.status==="parsing"?At.reloadCallback=Ft:At.status==="done"&&(At.vectorTile?At.parse(At.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ft):Ft())}else ze(null,void 0)}abortTile(Se,ze){const st=Se.uid,gt=this.loading[st];gt&&(gt.abort&>.abort(),delete this.loading[st]),ze()}removeTile(Se,ze){const st=this.loaded,gt=Se.uid;st&&st[gt]&&delete st[gt],ze()}}class z{constructor(Se){this.loading={}}loadTile(Se,ze){const st=Se.uid,{cancel:gt}=c.b1(Se.request,(At,Ft,Wt)=>{const Vt=!this.loading[st];if(delete this.loading[st],Vt||At||!Ft)return ze(At);this.decodeTile(st,Ft,Se.encoding).then(Jt=>{const{expires:qs,cacheControl:Cs}=c.aP(Wt);ze(null,Object.assign(Jt,{expires:qs,cacheControl:Cs}))}).catch(Jt=>ze(Jt))});this.loading[st]={cancel:gt}}async decodeTile(Se,ze,st){const gt=await createImageBitmap(new Blob([new Uint8Array(ze)],{type:"image/png"})),At=1-(gt.width-c.fy(gt.width))/2,Ft=At<1,Wt=this.getImageData(gt,At);return gt.close(),{dem:new c.fz(Se,Wt,st,Ft),borderReady:Ft}}reloadTile(Se,ze){ze(null,null)}abortTile(Se,ze){const st=Se.uid,gt=this.loading[st];gt&&(gt.cancel(),delete this.loading[st]),ze()}removeTile(Se,ze){ze()}getImageData(Se,ze){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Se.width,Se.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Se.width,this.offscreenCanvas.height=Se.height,this.offscreenCanvasContext.drawImage(Se,0,0,Se.width,Se.height);const st=this.offscreenCanvasContext.getImageData(-ze,-ze,Se.width+2*ze,Se.height+2*ze);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),st}}c.a_.setPbf(c.a$);class Q{constructor(Se){this._mrt=new c.a_(Se.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Se.uid,this.tileID=Se.tileID,this.source=Se.source}parse(Se,ze){const st=this._mrt;this.status="parsing",this._entireBuffer=Se;try{st.parseHeader(Se),this._isHeaderLoaded=!0;const gt=[];for(const At in st.layers){const Ft=st.getLayer(At),Wt=Ft.getDataRange(Ft.getBandList()),Vt=st.createDecodingTask(Wt),Jt=Se.slice(Wt.firstByte,Wt.lastByte+1),qs=c.a_.performDecoding(Jt,Vt).then(Cs=>Vt.complete(null,Cs)).catch(Cs=>Vt.complete(Cs,null));gt.push(qs)}Promise.allSettled(gt).then(()=>ze(null,st)).catch(At=>ze(At))}catch(gt){ze(gt)}}}class K{constructor({actor:Se}){this.actor=Se,this.loading={},this.loaded={}}loadTile(Se,ze){const st=Se.uid,gt=Se.request,At=this.loading[st]=new Q(Se),{cancel:Ft}=c.b1(gt,(Wt,Vt,Jt)=>{const qs=!this.loading[st];if(delete this.loading[st],qs||Wt||!Vt)return At.status="done",qs||(this.loaded[st]=At),ze(Wt);At.parse(Vt,(Cs,xr)=>{if(Cs||!xr)return ze(Cs);ze(null,xr,Jt)}),this.loaded[st]=At});At.abort=Ft}reloadTile(Se,ze){ze(null,void 0)}abortTile(Se,ze){const st=Se.uid,gt=this.loading[st];gt&&(gt.abort&>.abort(),delete this.loading[st]),ze()}removeTile(Se,ze){const st=Se.uid;this.loaded[st]&&delete this.loaded[st],ze()}decodeRasterArray(Se,ze){c.a_.performDecoding(Se.buffer,Se.task).then(st=>ze(null,st)).catch(st=>ze(st))}}const X=c.fA.prototype.toGeoJSON;class Z{constructor(Se){this._feature=Se,this.extent=c.an,this.type=Se.type,this.properties=Se.tags,"id"in Se&&!isNaN(Se.id)&&(this.id=parseInt(Se.id,10))}loadGeometry(){if(this._feature.type===1){const Se=[];for(const ze of this._feature.geometry)Se.push([new c.P(ze[0],ze[1])]);return Se}{const Se=[];for(const ze of this._feature.geometry){const st=[];for(const gt of ze)st.push(new c.P(gt[0],gt[1]));Se.push(st)}return Se}}toGeoJSON(Se,ze,st){return X.call(this,Se,ze,st)}}class re{constructor(Se,ze){this.name=Se,this.extent=c.an,this.length=ze.length,this._jsonFeatures=ze}feature(Se){return new Z(this._jsonFeatures[Se])}}class le{constructor(Se){this.layers={},this.extent=c.an;for(const ze of Object.keys(Se))this.layers[ze]=new re(ze,Se[ze])}}const oe=64/4096;class ne{constructor(){this.features=new Map}clear(){this.features.clear()}load(Se=[],ze){for(const st of Se){const gt=st.id;if(gt==null)continue;let At=this.features.get(gt);At&&this.updateCache(At,ze),st.geometry?(At=ye(st),this.updateCache(At,ze),this.features.set(gt,At)):this.features.delete(gt),this.updateCache(At,ze)}}updateCache(Se,ze){for(const{canonical:st,uid:gt}of Object.values(ze)){const{z:At,x:Ft,y:Wt}=st;ie(Se,Math.pow(2,At),Ft,Wt)&&delete ze[gt]}}getTile(Se,ze,st){const gt=Math.pow(2,Se),At=[];for(const Ft of this.features.values())ie(Ft,gt,ze,st)&&At.push(Ue(Ft,gt,ze,st));return{features:At}}getFeatures(){return[...this.features.values()]}}function ie({minX:zt,minY:Se,maxX:ze,maxY:st},gt,At,Ft){return zt<(At+1+oe)/gt&&Se<(Ft+1+oe)/gt&&ze>(At-oe)/gt&&st>(Ft-oe)/gt}function ye(zt){const{id:Se,geometry:ze,properties:st}=zt;if(!ze)return;if(ze.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:gt,coordinates:At}=ze,Ft={id:Se,type:1,geometry:[],tags:st,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Wt=Ft.geometry;if(gt==="Point")ce(At,Wt,Ft);else if(gt==="MultiPoint")for(const Vt of At)ce(Vt,Wt,Ft);else if(gt==="LineString")Ft.type=2,ve(At,Wt,Ft);else if(gt==="MultiLineString")Ft.type=2,be(At,Wt,Ft);else if(gt==="Polygon")Ft.type=3,be(At,Wt,Ft,!0);else{if(gt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Ft.type=3;for(const Vt of At)be(Vt,Wt,Ft,!0)}return Ft}function ce([zt,Se],ze,st){const gt=c.aH(zt);let At=c.aL(Se);At=At<0?0:At>1?1:At,ze.push(gt,At),st.minX=Math.min(st.minX,gt),st.minY=Math.min(st.minY,At),st.maxX=Math.max(st.maxX,gt),st.maxY=Math.max(st.maxY,At)}function ve(zt,Se,ze,st=!1,gt=!1){const At=[];for(const Ft of zt)ce(Ft,At,ze);Se.push(At),st&&function(Ft,Wt){let Vt=0;for(let Jt=0,qs=Ft.length,Cs=qs-2;Jt0===Wt)for(let Jt=0,qs=Ft.length;Jt=Ft&&Cs>=Ft||(Jt>=Ft?(qs+=Math.round(tn*((Ft-Jt)/Wr)),Jt=Ft):Cs>=Ft&&(xr=qs+Math.round(tn*((Ft-Jt)/Wr)),Cs=Ft),qs>=Ft&&xr>=Ft||(qs>=Ft?(Jt+=Math.round(Wr*((Ft-qs)/tn)),qs=Ft):xr>=Ft&&(Cs=Jt+Math.round(Wr*((Ft-qs)/tn)),xr=Ft),Wt&&Jt===Wt[Wt.length-1][0]&&qs===Wt[Wt.length-1][1]||(Wt=[[Jt,qs]],gt.push(Wt)),Wt.push([Cs,xr])))))}}function De(zt,Se,ze,st,gt){const At=(ze-oe)/Se,Ft=(st-oe)/Se,Wt=(ze+1+oe)/Se,Vt=(st+1+oe)/Se;function Jt(xr,Wr){let tn=0;return xrWt&&(tn|=2),WrVt&&(tn|=8),tn}let qs=[];for(let xr=1;xr<=8;xr*=2){let Wr=zt[zt.length-2],tn=zt[zt.length-1],Rr=!(Jt(Wr,tn)&xr);for(let sn=0;sn>31}function xe(zt,Se){const{geometry:ze,type:st}=zt;let gt=0,At=0;if(st===1){Se.writeVarint(Ie(1,ze.length));for(const Ft of ze){const Wt=Ft[0]-gt,Vt=Ft[1]-At;Se.writeVarint(Te(Wt)),Se.writeVarint(Te(Vt)),gt+=Wt,At+=Vt}}else for(const Ft of ze){if(Ft.length===0)continue;Se.writeVarint(Ie(1,1));const Wt=Ft.length-(st===3?1:0);for(let Vt=0;Vtzt},it=Math.fround||(Oe=new Float32Array(1),zt=>(Oe[0]=+zt,Oe[0]));var Oe;class Ye{constructor(Se){this.options=Object.assign(Object.create(fe),Se),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Se){const{log:ze,minZoom:st,maxZoom:gt}=this.options;ze&&console.time("total time");const At=`prepare ${Se.length} points`;ze&&console.time(At),this.points=Se;const Ft=[];for(let Vt=0;Vt=st;Vt--){const Jt=+Date.now();Wt=this.trees[Vt]=this._createTree(this._cluster(Wt,Vt)),ze&&console.log("z%d: %d clusters in %dms",Vt,Wt.numItems,+Date.now()-Jt)}return ze&&console.timeEnd("total time"),this}getClusters(Se,ze){let st=((Se[0]+180)%360+360)%360-180;const gt=Math.max(-90,Math.min(90,Se[1]));let At=Se[2]===180?180:((Se[2]+180)%360+360)%360-180;const Ft=Math.max(-90,Math.min(90,Se[3]));if(Se[2]-Se[0]>=360)st=-180,At=180;else if(st>At){const Cs=this.getClusters([st,gt,180,Ft],ze),xr=this.getClusters([-180,gt,At,Ft],ze);return Cs.concat(xr)}const Wt=this.trees[this._limitZoom(ze)],Vt=Wt.range(Re(st),tt(Ft),Re(At),tt(gt)),Jt=Wt.data,qs=[];for(const Cs of Vt){const xr=this.stride*Cs;qs.push(Jt[xr+5]>1?We(Jt,xr,this.clusterProps):this.points[Jt[xr+3]])}return qs}getChildren(Se){const ze=this._getOriginId(Se),st=this._getOriginZoom(Se),gt="No cluster with the specified id.",At=this.trees[st];if(!At)throw new Error(gt);const Ft=At.data;if(ze*this.stride>=Ft.length)throw new Error(gt);const Wt=this.options.radius/(this.options.extent*Math.pow(2,st-1)),Vt=At.within(Ft[ze*this.stride],Ft[ze*this.stride+1],Wt),Jt=[];for(const qs of Vt){const Cs=qs*this.stride;Ft[Cs+4]===Se&&Jt.push(Ft[Cs+5]>1?We(Ft,Cs,this.clusterProps):this.points[Ft[Cs+3]])}if(Jt.length===0)throw new Error(gt);return Jt}getLeaves(Se,ze,st){const gt=[];return this._appendLeaves(gt,Se,ze=ze||10,st=st||0,0),gt}getTile(Se,ze,st){const gt=this.trees[this._limitZoom(Se)],At=Math.pow(2,Se),{extent:Ft,radius:Wt}=this.options,Vt=Wt/Ft,Jt=(st-Vt)/At,qs=(st+1+Vt)/At,Cs={features:[]};return this._addTileFeatures(gt.range((ze-Vt)/At,Jt,(ze+1+Vt)/At,qs),gt.data,ze,st,At,Cs),ze===0&&this._addTileFeatures(gt.range(1-Vt/At,Jt,1,qs),gt.data,At,st,At,Cs),ze===At-1&&this._addTileFeatures(gt.range(0,Jt,Vt/At,qs),gt.data,-1,st,At,Cs),Cs.features.length?Cs:null}getClusterExpansionZoom(Se){let ze=this._getOriginZoom(Se)-1;for(;ze<=this.options.maxZoom;){const st=this.getChildren(Se);if(ze++,st.length!==1)break;Se=st[0].properties.cluster_id}return ze}_appendLeaves(Se,ze,st,gt,At){const Ft=this.getChildren(ze);for(const Wt of Ft){const Vt=Wt.properties;if(Vt&&Vt.cluster?At+Vt.point_count<=gt?At+=Vt.point_count:At=this._appendLeaves(Se,Vt.cluster_id,st,gt,At):At1;let qs,Cs,xr;if(Jt)qs=_e(ze,Vt,this.clusterProps),Cs=ze[Vt],xr=ze[Vt+1];else{const Rr=this.points[ze[Vt+3]];qs=Rr.properties;const[sn,rn]=Rr.geometry.coordinates;Cs=Re(sn),xr=tt(rn)}const Wr={type:1,geometry:[[Math.round(this.options.extent*(Cs*At-st)),Math.round(this.options.extent*(xr*At-gt))]],tags:qs};let tn;tn=Jt||this.options.generateId?ze[Vt+3]:this.points[ze[Vt+3]].id,tn!==void 0&&(Wr.id=tn),Ft.features.push(Wr)}}_limitZoom(Se){return Math.max(this.options.minZoom,Math.min(Math.floor(+Se),this.options.maxZoom+1))}_cluster(Se,ze){const{radius:st,extent:gt,reduce:At,minPoints:Ft}=this.options,Wt=st/(gt*Math.pow(2,ze)),Vt=Se.data,Jt=[],qs=this.stride;for(let Cs=0;Csze&&(sn+=Vt[un+5])}if(sn>Rr&&sn>=Ft){let rn,un=xr*Rr,fa=Wr*Rr,go=-1;const wo=(Cs/qs<<5)+(ze+1)+this.points.length;for(const co of tn){const ia=co*qs;if(Vt[ia+2]<=ze)continue;Vt[ia+2]=ze;const Ji=Vt[ia+5];un+=Vt[ia]*Ji,fa+=Vt[ia+1]*Ji,Vt[ia+4]=wo,At&&(rn||(rn=this._map(Vt,Cs,!0),go=this.clusterProps.length,this.clusterProps.push(rn)),At(rn,this._map(Vt,ia)))}Vt[Cs+4]=wo,Jt.push(un/sn,fa/sn,1/0,wo,-1,sn),At&&Jt.push(go)}else{for(let rn=0;rn1)for(const rn of tn){const un=rn*qs;if(!(Vt[un+2]<=ze)){Vt[un+2]=ze;for(let fa=0;fa>5}_getOriginZoom(Se){return(Se-this.points.length)%32}_map(Se,ze,st){if(Se[ze+5]>1){const Ft=this.clusterProps[Se[ze+6]];return st?Object.assign({},Ft):Ft}const gt=this.points[Se[ze+3]].properties,At=this.options.map(gt);return st&&At===gt?Object.assign({},At):At}}function We(zt,Se,ze){return{type:"Feature",id:zt[Se+3],properties:_e(zt,Se,ze),geometry:{type:"Point",coordinates:[(st=zt[Se],360*(st-.5)),Ke(zt[Se+1])]}};var st}function _e(zt,Se,ze){const st=zt[Se+5],gt=st>=1e4?`${Math.round(st/1e3)}k`:st>=1e3?Math.round(st/100)/10+"k":st,At=zt[Se+6],Ft=At===-1?{}:Object.assign({},ze[At]);return Object.assign(Ft,{cluster:!0,cluster_id:zt[Se+3],point_count:st,point_count_abbreviated:gt})}function Re(zt){return zt/360+.5}function tt(zt){const Se=Math.sin(zt*Math.PI/180),ze=.5-.25*Math.log((1+Se)/(1-Se))/Math.PI;return ze<0?0:ze>1?1:ze}function Ke(zt){const Se=(180-360*zt)*Math.PI/180;return 360*Math.atan(Math.exp(Se))/Math.PI-90}function Ze(zt,Se,ze,st){let gt=st;const At=Se+(ze-Se>>1);let Ft,Wt=ze-Se;const Vt=zt[Se],Jt=zt[Se+1],qs=zt[ze],Cs=zt[ze+1];for(let xr=Se+3;xrgt)Ft=xr,gt=Wr;else if(Wr===gt){const tn=Math.abs(xr-At);tnst&&(Ft-Se>3&&Ze(zt,Se,Ft,st),zt[Ft+2]=gt,ze-Ft>3&&Ze(zt,Ft,ze,st))}function lt(zt,Se,ze,st,gt,At){let Ft=gt-ze,Wt=At-st;if(Ft!==0||Wt!==0){const Vt=((zt-ze)*Ft+(Se-st)*Wt)/(Ft*Ft+Wt*Wt);Vt>1?(ze=gt,st=At):Vt>0&&(ze+=Ft*Vt,st+=Wt*Vt)}return Ft=zt-ze,Wt=Se-st,Ft*Ft+Wt*Wt}function xt(zt,Se,ze,st){const gt={id:zt??null,type:Se,geometry:ze,tags:st,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Se==="Point"||Se==="MultiPoint"||Se==="LineString")Xe(gt,ze);else if(Se==="Polygon")Xe(gt,ze[0]);else if(Se==="MultiLineString")for(const At of ze)Xe(gt,At);else if(Se==="MultiPolygon")for(const At of ze)Xe(gt,At[0]);return gt}function Xe(zt,Se){for(let ze=0;ze0&&(Ft+=st?(gt*qs-Jt*At)/2:Math.sqrt(Math.pow(Jt-gt,2)+Math.pow(qs-At,2))),gt=Jt,At=qs}const Wt=Se.length-3;Se[2]=1,Ze(Se,0,Wt,ze),Se[Wt+2]=1,Se.size=Math.abs(Ft),Se.start=0,Se.end=Se.size}function Ns(zt,Se,ze,st){for(let gt=0;gt1?1:ze}function bt(zt,Se,ze,st,gt,At,Ft,Wt){if(st/=Se,At>=(ze/=Se)&&Ft=st)return null;const Vt=[];for(const Jt of zt){const qs=Jt.geometry;let Cs=Jt.type;const xr=gt===0?Jt.minX:Jt.minY,Wr=gt===0?Jt.maxX:Jt.maxY;if(xr>=ze&&Wr=st)continue;let tn=[];if(Cs==="Point"||Cs==="MultiPoint")cs(qs,tn,ze,st,gt);else if(Cs==="LineString")yt(qs,tn,ze,st,gt,!1,Wt.lineMetrics);else if(Cs==="MultiLineString")Bs(qs,tn,ze,st,gt,!1);else if(Cs==="Polygon")Bs(qs,tn,ze,st,gt,!0);else if(Cs==="MultiPolygon")for(const Rr of qs){const sn=[];Bs(Rr,sn,ze,st,gt,!0),sn.length&&tn.push(sn)}if(tn.length){if(Wt.lineMetrics&&Cs==="LineString"){for(const Rr of tn)Vt.push(xt(Jt.id,Cs,Rr,Jt.tags));continue}Cs!=="LineString"&&Cs!=="MultiLineString"||(tn.length===1?(Cs="LineString",tn=tn[0]):Cs="MultiLineString"),Cs!=="Point"&&Cs!=="MultiPoint"||(Cs=tn.length===3?"Point":"MultiPoint"),Vt.push(xt(Jt.id,Cs,tn,Jt.tags))}}return Vt.length?Vt:null}function cs(zt,Se,ze,st,gt){for(let At=0;At=ze&&Ft<=st&&ps(Se,zt[At],zt[At+1],zt[At+2])}}function yt(zt,Se,ze,st,gt,At,Ft){let Wt=is(zt);const Vt=gt===0?lr:kr;let Jt,qs,Cs=zt.start;for(let sn=0;snze&&(qs=Vt(Wt,rn,un,go,wo,ze),Ft&&(Wt.start=Cs+Jt*qs)):co>st?ia=ze&&(qs=Vt(Wt,rn,un,go,wo,ze),Ji=!0),ia>st&&co<=st&&(qs=Vt(Wt,rn,un,go,wo,st),Ji=!0),!At&&Ji&&(Ft&&(Wt.end=Cs+Jt*qs),Se.push(Wt),Wt=is(zt)),Ft&&(Cs+=Jt)}let xr=zt.length-3;const Wr=zt[xr],tn=zt[xr+1],Rr=gt===0?Wr:tn;Rr>=ze&&Rr<=st&&ps(Wt,Wr,tn,zt[xr+2]),xr=Wt.length-3,At&&xr>=3&&(Wt[xr]!==Wt[0]||Wt[xr+1]!==Wt[1])&&ps(Wt,Wt[0],Wt[1],Wt[2]),Wt.length&&Se.push(Wt)}function is(zt){const Se=[];return Se.size=zt.size,Se.start=zt.start,Se.end=zt.end,Se}function Bs(zt,Se,ze,st,gt,At){for(const Ft of zt)yt(Ft,Se,ze,st,gt,At,!1)}function ps(zt,Se,ze,st){zt.push(Se,ze,st)}function lr(zt,Se,ze,st,gt,At){const Ft=(At-Se)/(st-Se);return ps(zt,At,ze+(gt-ze)*Ft,1),Ft}function kr(zt,Se,ze,st,gt,At){const Ft=(At-ze)/(gt-ze);return ps(zt,Se+(st-Se)*Ft,At,1),Ft}function Lr(zt,Se){const ze=[];for(let st=0;st0&&Se.size<(gt?Ft:st))return void(ze.numPoints+=Se.length/3);const Wt=[];for(let Vt=0;VtFt)&&(ze.numSimplified++,Wt.push(Se[Vt],Se[Vt+1])),ze.numPoints++;gt&&function(Vt,Jt){let qs=0;for(let Cs=0,xr=Vt.length,Wr=xr-2;Cs0===Jt)for(let Cs=0,xr=Vt.length;Cs24)throw new Error("maxZoom should be in the 0-24 range");if(ze.promoteId&&ze.generateId)throw new Error("promoteId and generateId cannot be used together.");let gt=function(At,Ft){const Wt=[];if(At.type==="FeatureCollection")for(let Vt=0;Vt1&&console.time("creation"),Wr=this.tiles[xr]=Cr(Se,ze,st,gt,Jt),this.tileCoords.push({z:ze,x:st,y:gt}),qs)){qs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",ze,st,gt,Wr.numFeatures,Wr.numPoints,Wr.numSimplified),console.timeEnd("creation"));const Ji=`z${ze}`;this.stats[Ji]=(this.stats[Ji]||0)+1,this.total++}if(Wr.source=Se,At==null){if(ze===Jt.indexMaxZoom||Wr.numPoints<=Jt.indexMaxPoints)continue}else{if(ze===Jt.maxZoom||ze===At)continue;if(At!=null){const Ji=At-ze;if(st!==Ft>>Ji||gt!==Wt>>Ji)continue}}if(Wr.source=null,Se.length===0)continue;qs>1&&console.time("clipping");const tn=.5*Jt.buffer/Jt.extent,Rr=.5-tn,sn=.5+tn,rn=1+tn;let un=null,fa=null,go=null,wo=null,co=bt(Se,Cs,st-tn,st+sn,0,Wr.minX,Wr.maxX,Jt),ia=bt(Se,Cs,st+Rr,st+rn,0,Wr.minX,Wr.maxX,Jt);Se=null,co&&(un=bt(co,Cs,gt-tn,gt+sn,1,Wr.minY,Wr.maxY,Jt),fa=bt(co,Cs,gt+Rr,gt+rn,1,Wr.minY,Wr.maxY,Jt),co=null),ia&&(go=bt(ia,Cs,gt-tn,gt+sn,1,Wr.minY,Wr.maxY,Jt),wo=bt(ia,Cs,gt+Rr,gt+rn,1,Wr.minY,Wr.maxY,Jt),ia=null),qs>1&&console.timeEnd("clipping"),Vt.push(un||[],ze+1,2*st,2*gt),Vt.push(fa||[],ze+1,2*st,2*gt+1),Vt.push(go||[],ze+1,2*st+1,2*gt),Vt.push(wo||[],ze+1,2*st+1,2*gt+1)}}getTile(Se,ze,st){Se=+Se,ze=+ze,st=+st;const gt=this.options,{extent:At,debug:Ft}=gt;if(Se<0||Se>24)return null;const Wt=1<1&&console.log("drilling down to z%d-%d-%d",Se,ze,st);let Jt,qs=Se,Cs=ze,xr=st;for(;!Jt&&qs>0;)qs--,Cs>>=1,xr>>=1,Jt=this.tiles[ss(qs,Cs,xr)];return Jt&&Jt.source?(Ft>1&&(console.log("found parent tile z%d-%d-%d",qs,Cs,xr),console.time("drilling down")),this.splitTile(Jt.source,qs,Cs,xr,Se,ze,st),Ft>1&&console.timeEnd("drilling down"),this.tiles[Vt]?Ur(this.tiles[Vt],At):null):null}}function ss(zt,Se,ze){return 32*((1<Jt.tags&&"3d_elevation_id"in Jt.tags&&"source"in Jt.tags&&Jt.tags.source==="elevation",At=st.features.filter(Jt=>gt(Jt));let Ft={_geojsonTileLayer:st.features};At.length>0&&(Ft={_geojsonTileLayer:st.features.filter(Jt=>!gt(Jt)),hd_road_elevation:At});const Wt=new le(Ft),Vt=function(Jt){const qs=new c.a$;for(const Cs of Object.keys(Jt))qs.writeMessage(3,Ae,{name:Cs,features:Jt[Cs]});return qs.finish()}(Ft).buffer;Se(null,{vectorTile:Wt,rawData:Vt})}class nn extends F{constructor(Se){super(Se),this.loadVectorData=ta,this._dynamicIndex=new ne}loadData(Se,ze){const st=Se&&Se.request,gt=st&&st.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Se,(At,Ft)=>{if(At||!Ft)return ze(At);if(typeof Ft!="object")return ze(new Error(`Input data given to '${Se.source}' is not a valid GeoJSON object.`));{try{if(Se.filter){const Vt=c.X(Se.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(Vt.result==="error")throw new Error(Vt.value.map(Jt=>`${Jt.key}: ${Jt.message}`).join(", "));Ft.features=Ft.features.filter(Jt=>Vt.value.evaluate({zoom:0},Jt))}Se.dynamic?(Ft.type==="Feature"&&(Ft={type:"FeatureCollection",features:[Ft]}),Se.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(Ft.features,this.loaded),Se.cluster&&(Ft.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Se.cluster?new Ye(function({superclusterOptions:Vt,clusterProperties:Jt}){if(!Jt||!Vt)return Vt;const qs={},Cs={},xr={accumulated:null,zoom:0},Wr={properties:null},tn=Object.keys(Jt);for(const Rr of tn){const[sn,rn]=Jt[Rr],un=c.X(rn),fa=c.X(typeof sn=="string"?[sn,["accumulated"],["get",Rr]]:sn);qs[Rr]=un.value,Cs[Rr]=fa.value}return Vt.map=Rr=>{Wr.properties=Rr;const sn={};for(const rn of tn)sn[rn]=qs[rn].evaluate(xr,Wr);return sn},Vt.reduce=(Rr,sn)=>{Wr.properties=sn;for(const rn of tn)xr.accumulated=Rr[rn],Rr[rn]=Cs[rn].evaluate(xr,Wr)},Vt}(Se)).load(Ft.features):Se.dynamic?this._dynamicIndex:function(Vt,Jt){return new Yr(Vt,Jt)}(Ft,Se.geojsonVtOptions)}catch(Vt){return ze(Vt)}const Wt={};if(gt){const Vt=d(st);Vt&&(Wt.resourceTiming={},Wt.resourceTiming[Se.source]=JSON.parse(JSON.stringify(Vt)))}ze(null,Wt)}})}reloadTile(Se,ze){const st=this.loaded;return st&&st[Se.uid]?Se.partial?ze(null,void 0):super.reloadTile(Se,ze):this.loadTile(Se,ze)}loadGeoJSON(Se,ze){if(Se.request)c.m(Se.request,ze);else{if(typeof Se.data!="string")return ze(new Error(`Input data given to '${Se.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return ze(null,JSON.parse(Se.data))}catch{return ze(new Error(`Input data given to '${Se.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Se,ze){try{ze(null,this._geoJSONIndex.getClusterExpansionZoom(Se.clusterId))}catch(st){ze(st)}}getClusterChildren(Se,ze){try{ze(null,this._geoJSONIndex.getChildren(Se.clusterId))}catch(st){ze(st)}}getClusterLeaves(Se,ze){try{ze(null,this._geoJSONIndex.getLeaves(Se.clusterId,Se.limit,Se.offset))}catch(st){ze(st)}}}class hr{constructor(Se,ze,st){this.tileID=new c.aR(Se.tileID.overscaledZ,Se.tileID.wrap,Se.tileID.canonical.z,Se.tileID.canonical.x,Se.tileID.canonical.y),this.tileZoom=Se.tileZoom,this.uid=Se.uid,this.zoom=Se.zoom,this.canonical=Se.tileID.canonical,this.pixelRatio=Se.pixelRatio,this.tileSize=Se.tileSize,this.source=Se.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Se.projection,this.brightness=ze,this.worldview=st}parse(Se,ze,st,gt){this.status="parsing";const At=new c.aR(st.tileID.overscaledZ,st.tileID.wrap,st.tileID.canonical.z,st.tileID.canonical.x,st.tileID.canonical.y),Ft=[],Wt=ze.familiesBySource[st.source],Vt=new c.ff(At,st.promoteId);Vt.bucketLayerIDs=[],Vt.is3DTile=!0,c.fB(Se).then(Jt=>{const qs=Jt.json.extensionsUsed&&Jt.json.extensionsUsed.includes("MAPBOX_mesh_features")||Jt.json.asset.extras&&Jt.json.asset.extras.MAPBOX_mesh_features,Cs=Jt.json.extensionsUsed&&Jt.json.extensionsUsed.includes("EXT_meshopt_compression"),xr=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Wr in Wt)for(const tn of Wt[Wr]){const Rr=tn[0];Vt.bucketLayerIDs.push(tn.map(un=>c.F(un.id,un.scope))),Rr.recalculate(xr,[]);const sn=c.fC(Jt,1/c.cS(st.tileID.canonical)),rn=new c.fD(tn,sn,At,qs,Cs,this.brightness,Vt,this.worldview);qs||(rn.needsUpload=!0),Ft.push(rn),rn.evaluate(Rr)}this.status="done",gt(null,{buckets:Ft,featureIndex:Vt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Jt=>gt(new Error(Jt.message)))}}class Pr{constructor({actor:Se,layerIndex:ze,availableImages:st,availableModels:gt,brightness:At,worldview:Ft}){this.actor=Se,this.layerIndex=ze,this.availableImages=st,this.availableModels=gt,this.brightness=At,this.loading={},this.loaded={},this.worldview=Ft}loadTile(Se,ze){const st=Se.uid,gt=this.loading[st]=new hr(Se,this.brightness,this.worldview);c.b1(Se.request,(At,Ft)=>{const Wt=!this.loading[st];return delete this.loading[st],Wt||At?(gt.status="done",Wt||(this.loaded[st]=gt),ze(At)):Ft&&Ft.byteLength!==0?void gt.parse(Ft,this.layerIndex,Se,(Vt,Jt)=>{gt.status="done",this.loaded=this.loaded||{},this.loaded[st]=gt,Vt||!Jt?ze(Vt):ze(null,Jt)}):(gt.status="done",this.loaded[st]=gt,ze())})}reloadTile(Se,ze){const st=this.loaded,gt=Se.uid;if(st&&st[gt]){const At=st[gt];At.projection=Se.projection,At.brightness=Se.brightness;const Ft=(Wt,Vt)=>{At.reloadCallback&&(delete At.reloadCallback,this.loadTile(Se,ze)),ze(Wt,Vt)};At.status==="parsing"?At.reloadCallback=Ft:At.status==="done"&&this.loadTile(Se,ze)}}abortTile(Se,ze){const st=Se.uid;this.loading[st]&&delete this.loading[st],ze()}removeTile(Se,ze){const st=this.loaded,gt=Se.uid;st&&st[gt]&&delete st[gt],ze()}}const Qn=new Map,Gt=new Map;class gr{constructor(Se){this.self=Se,this.actor=new c.A(Se,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:nn,"raster-dem":z,"raster-array":K,"batched-model":Pr},this.workerSources={},this.self.registerWorkerSource=(ze,st)=>{if(this.workerSourceTypes[ze])throw new Error(`Worker source with name "${ze}" already registered.`);this.workerSourceTypes[ze]=st},this.self.registerRTLTextPlugin=ze=>{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=ze.applyArabicShaping,c.fF.processBidirectionalText=ze.processBidirectionalText,c.fF.processStyledBidirectionalText=ze.processStyledBidirectionalText;for(const st of this.rtlPluginParsingListeners)st(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Se,ze,st){delete this.layerIndexes[Se],delete this.availableImages[Se],delete this.availableModels[Se],delete this.workerSources[Se],st()}checkIfReady(Se,ze,st){st()}setReferrer(Se,ze){this.referrer=ze}spriteLoaded(Se,ze){this.isSpriteLoaded[Se]||(this.isSpriteLoaded[Se]={});const{scope:st,isLoaded:gt}=ze;if(this.isSpriteLoaded[Se][st]=gt,this.workerSources[Se]&&this.workerSources[Se][st])for(const At in this.workerSources[Se][st]){const Ft=this.workerSources[Se][st][At];for(const Wt in Ft){const Vt=Ft[Wt];Vt instanceof F&&(Vt.isSpriteLoaded=gt,Vt.fire(new c.C("isSpriteLoaded")))}}}setImages(Se,ze,st){this.availableImages[Se]||(this.availableImages[Se]={});const{scope:gt,images:At}=ze;if(this.availableImages[Se][gt]=At,this.workerSources[Se]&&this.workerSources[Se][gt]){for(const Ft in this.workerSources[Se][gt]){const Wt=this.workerSources[Se][gt][Ft];for(const Vt in Wt)Wt[Vt].availableImages=At}st()}else st()}setModels(Se,{scope:ze,models:st},gt){if(this.availableModels[Se]||(this.availableModels[Se]={}),this.availableModels[Se][ze]=st,this.workerSources[Se]&&this.workerSources[Se][ze]){for(const At in this.workerSources[Se][ze]){const Ft=this.workerSources[Se][ze][At];for(const Wt in Ft)Ft[Wt].availableModels=st}gt()}else gt()}setProjection(Se,ze){this.projections[Se]=c.c0(ze)}setBrightness(Se,ze,st){this.brightness=ze,st()}setContextParams(Se,ze,st){this.maxUniformBufferBindings=ze.maxBindingPoints,this.maxUniformBlockSizeDwords=ze.maxUniformBlockSizeDwords,this.disableSymbolUBO=ze.disableSymbolUBO,st()}setWorldview(Se,ze,st){this.worldview=ze,st()}setLayers(Se,ze,st){this.getLayerIndex(Se,ze.scope).replace(ze.layers,ze.options),st()}updateLayers(Se,ze,st){this.getLayerIndex(Se,ze.scope).update(ze.layers,ze.removedIds,ze.options),st()}loadTile(Se,ze,st){ze.projection=this.projections[Se]||this.defaultProjection,this.getWorkerSource(Se,ze).loadTile(ze,st)}decodeRasterArray(Se,ze,st){this.getWorkerSource(Se,ze).decodeRasterArray(ze,st)}reloadTile(Se,ze,st){ze.projection=this.projections[Se]||this.defaultProjection,this.getWorkerSource(Se,ze).reloadTile(ze,st)}abortTile(Se,ze,st){this.getWorkerSource(Se,ze).abortTile(ze,st)}removeTile(Se,ze,st){this.getWorkerSource(Se,ze).removeTile(ze,st)}removeSource(Se,ze,st){if(!(this.workerSources[Se]&&this.workerSources[Se][ze.scope]&&this.workerSources[Se][ze.scope][ze.type]&&this.workerSources[Se][ze.scope][ze.type][ze.source]))return;const gt=this.workerSources[Se][ze.scope][ze.type][ze.source];delete this.workerSources[Se][ze.scope][ze.type][ze.source],gt.removeSource!==void 0?gt.removeSource(ze,st):st()}loadTileProvider(Se,ze,st){(async function(gt,At){const Ft=Gt.get(gt);if(Ft)return Ft;const Wt=Qn.get(gt);if(Wt!==void 0)return Wt;const Vt=import(At).then(Jt=>{const qs=Jt.default;if(typeof qs!="function")throw new Error(`TileProvider "${gt}" module must default-export a class`);if(typeof qs.prototype.loadTile!="function")throw new Error(`TileProvider "${gt}" class must have a loadTile method`);return Gt.set(gt,qs),qs}).finally(()=>{Qn.delete(gt)});return Qn.set(gt,Vt),Vt})(ze.name,ze.url).then(gt=>{const At=new gt(ze.options);return this.getWorkerSource(Se,{type:ze.type,source:ze.source,scope:ze.scope},At),At.load&&ze.request?At.load({request:ze.request}):null}).then(gt=>st(null,gt)).catch(gt=>st(gt instanceof Error?gt:new Error(typeof gt=="string"?gt:"Unknown error")))}loadWorkerSource(Se,ze,st){try{this.self.importScripts(ze.url),st()}catch(gt){st(gt)}}syncRTLPluginState(Se,ze,st){if(c.fF.isParsed())st(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(st);else try{c.fF.setState(ze);const gt=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||gt==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(gt),c.fF.isParsed()?st(null,!0):this.rtlPluginParsingListeners.push(st))}catch(gt){st(gt)}}setConfig(Se,ze){Object.assign(c.g,ze)}getAvailableImages(Se,ze){this.availableImages[Se]||(this.availableImages[Se]={});let st=this.availableImages[Se][ze];return st||(st=[]),st}getAvailableModels(Se,ze){this.availableModels[Se]||(this.availableModels[Se]={});let st=this.availableModels[Se][ze];return st||(st={}),st}getLayerIndex(Se,ze){this.layerIndexes[Se]||(this.layerIndexes[Se]={});let st=this.layerIndexes[Se][ze];return st||(st=this.layerIndexes[Se][ze]=new y,st.scope=ze),st}getWorkerSource(Se,ze,st){const{type:gt,source:At,scope:Ft}=ze,Wt=this.workerSources;if(Wt[Se]||(Wt[Se]={}),Wt[Se][Ft]||(Wt[Se][Ft]={}),Wt[Se][Ft][gt]||(Wt[Se][Ft][gt]={}),this.isSpriteLoaded[Se]||(this.isSpriteLoaded[Se]={}),!Wt[Se][Ft][gt][At]){const Vt={send:(qs,Cs,xr,Wr,tn,Rr)=>this.actor.send(qs,Cs,xr,Se,tn,Rr),scheduler:this.actor.scheduler},Jt=this.workerSourceTypes[gt];if(!Jt)throw new Error(`Unknown worker source type "${gt}".`);Wt[Se][Ft][gt][At]=new Jt({actor:Vt,layerIndex:this.getLayerIndex(Se,Ft),availableImages:this.getAvailableImages(Se,Ft),availableModels:this.getAvailableModels(Se,Ft),isSpriteLoaded:this.isSpriteLoaded[Se][Ft],tileProvider:st,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Wt[Se][Ft][gt][At]}rasterizeImagesWorker(Se,ze,st){const gt=new Map;for(const[At,{image:Ft,imageVariant:Wt}]of ze.tasks.entries()){const Vt=this.imageRasterizer.rasterize(Wt,Ft,ze.scope,Se);gt.set(At,Vt)}st(void 0,gt)}removeRasterizedImages(Se,ze,st){this.imageRasterizer.removeImagesFromCacheByIds(ze.imageIds,ze.scope,Se),st()}enforceCacheSizeLimit(Se,ze){c.fH(ze)}getWorkerPerformanceMetrics(Se,ze,st){st(void 0,void 0)}}return c.fE(self)&&(self.worker=new gr(self)),gr}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},h={mark(E){performance.mark(E)},measure(E,p,j){performance.measure(E,p,j)}};function m(E){const p=E.name.split("?")[0];return o.a(p)&&p.includes("mapbox-gl.js")?"javascript":o.a(p)&&p.includes("mapbox-gl.css")?"css":o.b(p)?"fontRange":o.c(p)?"sprite":o.i(p)?"style":o.d(p)?"tilejson":"other"}var x,y={},v=function(){if(x)return y;function E(L){return!p(L)}function p(L){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var q,H,Y=new Blob([""],{type:"text/javascript"}),te=URL.createObjectURL(Y);try{H=new Worker(te),q=!0}catch{q=!1}return H&&H.terminate(),URL.revokeObjectURL(te),q}()?function(){var q=document.createElement("canvas");q.width=q.height=1;var H=q.getContext("2d");if(!H)return!1;var Y=H.getImageData(0,0,1,1);return Y&&Y.width===q.width}()?(j[O=L&&L.failIfMajorPerformanceCaveat]===void 0&&(j[O]=function(q){var H,Y=function(te){var de=document.createElement("canvas"),pe=Object.create(E.webGLContextAttributes);return pe.failIfMajorPerformanceCaveat=te,de.getContext("webgl2",pe)}(q);if(!Y)return!1;try{H=Y.createShader(Y.VERTEX_SHADER)}catch{return!1}return!(!H||Y.isContextLost())&&(Y.shaderSource(H,"void main() {}"),Y.compileShader(H),Y.getShaderParameter(H,Y.COMPILE_STATUS)===!0)}(O)),j[O]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var O}x=1,y.supported=E,y.notSupportedReason=p;var j={};return E.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},y}();function w(E,p,j){const L=document.createElement(E);return p!=null&&(L.className=p),j&&j.appendChild(L),L}function b(E,p,j){const L=document.createElementNS("http://www.w3.org/2000/svg",E);for(const O of Object.keys(p))L.setAttributeNS(null,O,String(p[O]));return j&&j.appendChild(L),L}const N=typeof document<"u"?document.documentElement&&document.documentElement.style:null,S=N&&N.userSelect!==void 0?"userSelect":"WebkitUserSelect";let T;function A(){N&&S&&(T=N[S],N[S]="none")}function I(){N&&S&&(N[S]=T)}function D(E){E.preventDefault(),E.stopPropagation(),window.removeEventListener("click",D,!0)}function R(){window.addEventListener("click",D,!0),window.setTimeout(()=>{window.removeEventListener("click",D,!0)},0)}function $(E,p){const j=E.getBoundingClientRect();return Q(E,j,p)}function F(E,p){const j=E.getBoundingClientRect(),L=[];for(let O=0;Othis._skuTokenExpiresAt}transformRequest(p,j){return this._transformRequestFn&&this._transformRequestFn(p,j)||{url:p}}normalizeStyleURL(p,j){if(!o.e(p))return p;const L=le(p);return L.params.push(`sdk=js-${c}`),L.path=`/styles/v1${L.path}`,this._makeAPIURL(L,this._customAccessToken||j)}normalizeGlyphsURL(p,j){if(!o.e(p))return p;const L=le(p);return L.path=`/fonts/v1${L.path}`,this._makeAPIURL(L,this._customAccessToken||j)}normalizeModelURL(p,j){if(!o.e(p))return p;const L=le(p);return L.path=`/models/v1${L.path}`,this._makeAPIURL(L,this._customAccessToken||j)}normalizeSourceURL(p,j,L,O){if(!o.e(p))return p;const q=le(p);return q.path=`/v4/${q.authority}.json`,q.params.push("secure"),L&&q.params.push(`language=${L}`),O&&q.params.push(`worldview=${O}`),this._makeAPIURL(q,this._customAccessToken||j)}normalizeIconsetURL(p,j){const L=le(p);return o.e(p)?(L.path=`/styles/v1${L.path}/iconset.pbf`,this._makeAPIURL(L,this._customAccessToken||j)):oe(L)}normalizeSpriteURL(p,j,L,O){const q=le(p);return o.e(p)?(q.path=`/styles/v1${q.path}/sprite${j}${L}`,this._makeAPIURL(q,this._customAccessToken||O)):(q.path+=`${j}${L}`,oe(q))}normalizeTileURL(p,j,L){if(this._isSkuTokenExpired()&&this._createSkuToken(),p&&!o.e(p))return p;const O=le(p);O.path=O.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${j||L&&O.authority!=="raster"&&L===512?"@2x":""}${o.k.supported?".webp":"$1"}`),O.authority==="raster"?O.path=`/${o.g.RASTER_URL_PREFIX}${O.path}`:O.authority==="rasterarrays"?O.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${O.path}`:O.authority==="3dtiles"?O.path=`/${o.g.TILES3D_URL_PREFIX}${O.path}`:(O.path=O.path.replace(/^.+\/v4\//,"/"),O.path=`/${o.g.TILE_URL_VERSION}${O.path}`);const q=this._customAccessToken||function(H){for(const Y of H){const te=Y.match(/^access_token=(.*)$/);if(te)return te[1]}return null}(O.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&q&&this._skuToken&&O.params.push(`sku=${this._skuToken}`),this._makeAPIURL(O,q)}canonicalizeTileURL(p,j){const L=le(p);if(!L.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!L.path.match(/\.[\w]+$/))return p;let O="mapbox://";L.path.match(/^\/raster\/v1\//)?O+=`raster/${L.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:L.path.match(/^\/rasterarrays\/v1\//)?O+=`rasterarrays/${L.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:O+=`tiles/${L.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let q=L.params;return j&&(q=q.filter(H=>!H.match(/^access_token=/))),q.length&&(O+=`?${q.join("&")}`),O}canonicalizeTileset(p,j){const L=!!j&&o.e(j),O=[];for(const q of p.tiles||[])o.f(q)?O.push(this.canonicalizeTileURL(q,L)):O.push(q);return O}_makeAPIURL(p,j){const L="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",O=le(o.g.API_URL);if(p.protocol=O.protocol,p.authority=O.authority,p.protocol==="http"){const q=p.params.indexOf("secure");q>=0&&p.params.splice(q,1)}if(O.path!=="/"&&(p.path=`${O.path}${p.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return oe(p);if(j=j||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!j)throw new Error(`An API access token is required to use Mapbox GL. ${L}`);if(j[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${L}`)}return p.params=p.params.filter(q=>q.indexOf("access_token")===-1),p.params.push(`access_token=${j||""}`),oe(p)}}const re=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function le(E){const p=E.match(re);if(!p)throw new Error("Unable to parse URL object");return{protocol:p[1],authority:p[2],path:p[3]||"/",params:p[4]?p[4].split("&"):[]}}function oe(E){const p=E.params.length?`?${E.params.join("&")}`:"";return`${E.protocol}://${E.authority}${E.path}${p}`}const ne="mapbox.eventData";function ie(E){if(!E)return null;const p=E.split(".");if(!p||p.length!==3)return null;try{return JSON.parse(o.l(p[1]))}catch{return null}}function ye(E){return!(!o.g.EVENTS_URL||!E&&!o.g.ACCESS_TOKEN)}class ce{constructor(p){this.type=p,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(p){const j=ie(o.g.ACCESS_TOKEN);let L="";return L=j&&j.u?o.j(j.u):o.g.ACCESS_TOKEN||"",p?`${ne}.${p}:${L}`:`${ne}:${L}`}fetchEventData(){const p=o.s("localStorage"),j=this.getStorageKey(),L=this.getStorageKey("uuid"),O=this.getStorageKey("uuidTimestamp");if(p)try{const q=localStorage.getItem(j);q&&(this.eventData=JSON.parse(q));const H=localStorage.getItem(L);H&&(this.anonId=H);const Y=localStorage.getItem(O);Y&&(this.anonIdTimestamp=Number(Y));const te=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(j,JSON.stringify(this.eventData)),H&&localStorage.setItem(O,H.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(p){}postEvent(p,j,L,O){if(!o.g.EVENTS_URL)return;const q=le(o.g.EVENTS_URL);q.params.push(`access_token=${O||o.g.ACCESS_TOKEN||""}`);const H={event:this.type,created:new Date(p).toISOString()},Y=j?Object.assign(H,j):H,te={url:oe(q),headers:{"Content-Type":"text/plain"},body:JSON.stringify([Y])};this.pendingRequest=o.p(te,de=>{this.pendingRequest=null,L(de),this.saveEventData(),this.processRequests(O)})}queueRequest(p,j){this.queue.push(p),this.processRequests(j)}}class ve extends ce{constructor(p){super("metrics"),p&&(this.data=p)}postMetricsEvent(p){if(!ye(p))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const j=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:j},p)}processRequests(p){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:j,payload:L}=this.queue.shift();this.postEvent(j,L,()=>{},p)}}const be=new class extends ce{constructor(E){super("appUserTurnstile"),this._customAccessToken=E}postTurnstileEvent(E,p){ye(p)&&Array.isArray(E)&&E.some(j=>o.e(j)||o.f(j))&&this.queueRequest(Date.now(),p)}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const p=ie(o.g.ACCESS_TOKEN),j=p?p.u:o.g.ACCESS_TOKEN;let L=j!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),L=!0);const O=this.queue.shift();if(this.eventData.lastSuccess){const q=new Date(this.eventData.lastSuccess),H=new Date(O),Y=(O-this.eventData.lastSuccess)/864e5;L=L||Y>=1||Y<-1||q.getDate()!==H.getDate()}else L=!0;L?this.postEvent(O,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:K,"enabled.telemetry":!1,userId:this.anonId},q=>{q||(this.eventData.lastSuccess=O,this.eventData.tokenU=j)},E):this.processRequests()}},Ue=be.postTurnstileEvent.bind(be),Be=new class extends ce{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(E,p,j,L){this.skuToken=p,this.errorCb=L,o.g.EVENTS_URL&&(j||o.g.ACCESS_TOKEN?this.queueRequest({id:E,timestamp:Date.now()},j):this.errorCb(new Error(X)))}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{id:p,timestamp:j}=this.queue.shift();p&&this.success[p]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(j,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:K,skuToken:this.skuToken,userId:this.anonId},L=>{L?this.errorCb(L):p&&(this.success[p]=!0)},E))}remove(){this.errorCb=null}},De=Be.postMapLoadEvent.bind(Be),Ae=new class extends ce{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(E){let p=this.mapInstanceIdMap.get(E);return p||(p=o.u(),this.mapInstanceIdMap.set(E,p)),p}getEventId(E){const p=this.eventIdPerMapInstanceMap.get(E)||0;return this.eventIdPerMapInstanceMap.set(E,p+1),p}postStyleLoadEvent(E,p){const{map:j,style:L,importedStyles:O}=p;if(!ye(E))return;const q=this.getMapInstanceId(j),H={mapInstanceId:q,eventId:this.getEventId(q),style:L};O.length&&(H.importedStyles=O),this.queueRequest({timestamp:Date.now(),payload:H},E)}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:p,payload:j}=this.queue.shift();this.postEvent(p,j,()=>{},E)}},He=Ae.postStyleLoadEvent.bind(Ae),Le=new ve({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Ie=Le.postMetricsEvent.bind(Le),Te=new ve({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),xe=Te.postMetricsEvent.bind(Te),et=new class extends ce{constructor(){super("gljs.performance")}postPerformanceEvent(E,p){ye(E)&&this.queueRequest({timestamp:Date.now(),performanceData:p},E)}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:p,performanceData:j}=this.queue.shift(),L=function(O){const q=performance.getEntriesByType("resource"),H=performance.getEntriesByType("mark"),Y=function(Me){const qe={};if(Me){for(const $e in Me)if($e!=="other")for(const nt of Me[$e]){const rt=`${$e}ResolveRangeMin`,pt=`${$e}ResolveRangeMax`,vt=`${$e}RequestCount`,ot=`${$e}RequestCachedCount`;qe[rt]=Math.min(qe[rt]||1/0,nt.startTime),qe[pt]=Math.max(qe[pt]||-1/0,nt.responseEnd);const Ut=Tt=>{qe[Tt]===void 0&&(qe[Tt]=0),++qe[Tt]};nt.transferSize!==void 0&&nt.transferSize===0&&Ut(ot),Ut(vt)}}return qe}(function(Me,qe){const $e={};if(Me)for(const nt of Me){const rt=qe(nt);$e[rt]===void 0&&($e[rt]=[]),$e[rt].push(nt)}return $e}(q,m)),te=window.devicePixelRatio,de=navigator.connection||navigator.mozConnection||navigator.webkitConnection,pe=de?de.effectiveType:void 0,Ce={counters:[],metadata:[],attributes:[]},je=(Me,qe,$e)=>{$e!=null&&Me.push({name:qe,value:$e.toString()})};for(const Me in Y)je(Ce.counters,Me,Y[Me]);if(O.interactionRange[0]!==1/0&&O.interactionRange[1]!==-1/0&&(je(Ce.counters,"interactionRangeMin",O.interactionRange[0]),je(Ce.counters,"interactionRangeMax",O.interactionRange[1])),H)for(const Me of Object.values(d)){const qe=H.find($e=>$e.name===Me);qe&&je(Ce.counters,Me,qe.startTime)}return je(Ce.counters,"visibilityHidden",O.visibilityHidden),je(Ce.attributes,"style",function(Me){if(Me)for(const qe of Me){const $e=qe.name.split("?")[0];if(o.i($e)){const nt=$e.split("/").slice(-2);if(nt.length===2)return`mapbox://styles/${nt[0]}/${nt[1]}`}}}(q)),je(Ce.attributes,"terrainEnabled",O.terrainEnabled?"true":"false"),je(Ce.attributes,"fogEnabled",O.fogEnabled?"true":"false"),je(Ce.attributes,"projection",O.projection),je(Ce.attributes,"zoom",O.zoom),je(Ce.metadata,"devicePixelRatio",te),je(Ce.metadata,"connectionEffectiveType",pe),je(Ce.metadata,"navigatorUserAgent",navigator.userAgent),je(Ce.metadata,"screenWidth",window.screen.width),je(Ce.metadata,"screenHeight",window.screen.height),je(Ce.metadata,"windowWidth",window.innerWidth),je(Ce.metadata,"windowHeight",window.innerHeight),je(Ce.metadata,"mapWidth",O.width/te),je(Ce.metadata,"mapHeight",O.height/te),je(Ce.metadata,"webglRenderer",O.renderer),je(Ce.metadata,"webglVendor",O.vendor),je(Ce.metadata,"sdkVersion",c),je(Ce.metadata,"sdkIdentifier","mapbox-gl-js"),Ce}(j);for(const O of L.metadata);for(const O of L.counters);for(const O of L.attributes);this.postEvent(p,L,()=>{},E)}},fe=et.postPerformanceEvent.bind(et),it=new class extends ce{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(E,p,j,L){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const O=le(o.g.API_URL+o.g.SESSION_PATH);O.params.push(`sku=${p||""}`),O.params.push(`access_token=${L||o.g.ACCESS_TOKEN||""}`);const q={url:oe(O),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(q,H=>{this.pendingRequest=null,j(H),this.saveEventData(),this.processRequests(L)})}getSessionAPI(E,p,j,L){this.skuToken=p,this.errorCb=L,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(j||o.g.ACCESS_TOKEN?this.queueRequest({id:E,timestamp:Date.now()},j):this.errorCb(new Error(X)))}processRequests(E){if(this.pendingRequest||this.queue.length===0)return;const{id:p,timestamp:j}=this.queue.shift();p&&this.success[p]||this.getSession(j,this.skuToken,L=>{L?this.errorCb(L):p&&(this.success[p]=!0)},E)}remove(){this.errorCb=null}},Oe=it.getSessionAPI.bind(it),Ye=new Set;function We(E,p){p?Ye.add(E):Ye.delete(E)}class _e{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(p,j){this._updatedSourceCaches[p]=j,this.setDirty()}discardSourceCacheUpdate(p){delete this._updatedSourceCaches[p]}updateLayer(p){const j=p.scope;this._updatedLayers[j]=this._updatedLayers[j]||new Set,this._updatedLayers[j].add(p.id),this.setDirty()}removeLayer(p){const j=p.scope;this._removedLayers[j]=this._removedLayers[j]||{},this._updatedLayers[j]=this._updatedLayers[j]||new Set,this._removedLayers[j][p.id]=p,this._updatedLayers[j].delete(p.id),this._updatedPaintProps.delete(p.fqid),this.setDirty()}getRemovedLayer(p){return this._removedLayers[p.scope]?this._removedLayers[p.scope][p.id]:null}discardLayerRemoval(p){this._removedLayers[p.scope]&&delete this._removedLayers[p.scope][p.id]}getLayerUpdatesByScope(){const p={};for(const j in this._updatedLayers)p[j]=p[j]||{},p[j].updatedIds=Array.from(this._updatedLayers[j].values());for(const j in this._removedLayers)p[j]=p[j]||{},p[j].removedIds=Object.keys(this._removedLayers[j]);return p}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(p){this._updatedPaintProps.add(p.fqid),this.setDirty()}getUpdatedImages(p){return this._updatedImages[p]?Array.from(this._updatedImages[p].values()):[]}updateImage(p,j){this._updatedImages[j]=this._updatedImages[j]||new Set,this._updatedImages[j].add(o.I.toString(p)),this.setDirty()}resetUpdatedImages(p){this._updatedImages[p]&&this._updatedImages[p].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Re(E){const{userImage:p}=E;return!!(p&&p.render&&p.render())&&(E.data.replace(new Uint8Array(p.data.buffer)),!0)}const tt={workerUrl:"",workerClass:null,workerParams:void 0};function Ke(E){return tt.workerClass!=null?new tt.workerClass:new self.Worker(tt.workerUrl,Object.assign({name:E},tt.workerParams))}const Ze="mapboxgl_preloaded_worker_pool";class lt{constructor(p){this.active={},this.name=p}acquire(p,j=lt.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{j.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[Ze]}numActive(){return Object.keys(this.active).length}}lt.workerCount=2;class xt{constructor(p,j,L="Worker",O=lt.workerCount){this.workerPool=p,this.actors=[],this.currentActor=0,this.id=o.r();const q=this.workerPool.acquire(this.id,O);for(let H=0;H{this.ready=!0})}broadcast(p,j,L){o.t(this.actors,(O,q)=>{O.send(p,j,q)},L=L||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(p=>{p.remove()}),this.actors=[],this.workerPool.release(this.id)}}let Xe,Je;function jt(){return Xe||(Xe=new lt),Xe}xt.Actor=o.A;class ns extends o.E{constructor(p){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=p,p!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new xt((Je||(Je=new lt("ImageRasterizer")),Je),this,"Image Rasterizer Worker",1))}addScope(p){this.loaded.set(p,!1),this.imageProviders.set(p,new Map),this.images.set(p,new Map),this.updatedImages.set(p,new Set),this.callbackDispatchedThisFrame.set(p,new Set),this.imageVersions.set(p,new Map),this.patterns.set(p,new Map),this.atlasImage.set(p,new o.q({width:1,height:1}))}removeScope(p){this.loaded.delete(p),this.imageProviders.delete(p),this.images.delete(p),this.updatedImages.delete(p),this.callbackDispatchedThisFrame.delete(p),this.imageVersions.delete(p),this.patterns.delete(p),this.atlasImage.delete(p);const j=this.atlasTexture.get(p);j&&(j.destroy(),this.atlasTexture.delete(p))}addImageProvider(p,j){this.imageProviders.has(j)||this.imageProviders.set(j,new Map),this.imageProviders.get(j).set(p.id,p)}removeImageProvider(p,j){this.imageProviders.has(j)&&this.imageProviders.get(j).delete(p)}getPendingImageProviders(){const p=[];for(const j of this.imageProviders.values())for(const L of j.values())L.hasPendingRequests()&&p.push(L);return p}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const p of this.loaded.keys())if(!this.loaded.get(p))return!1;return!0}setLoaded(p,j){if(this.loaded.get(j)!==p&&(this.loaded.set(j,p),p)){for(const{ids:L,callback:O}of this.requestors)this._notify(L,j,O);this.requestors=[]}}hasImage(p,j){return!!this.getImage(p,j)}getImage(p,j){return this.images.get(j).get(p.toString())}addImage(p,j,L){if(this._validate(p,L)){this.images.get(j).set(p.toString(),L);const O=this.imageVersions.get(j),q=O.get(p.toString())||0;O.set(p.toString(),q+1)}}_validate(p,j){let L=!0;return this._validateStretch(j.stretchX,j.data&&j.data.width)||(this.fire(new o.B(new Error(`Image "${p.name}" has invalid "stretchX" value`))),L=!1),this._validateStretch(j.stretchY,j.data&&j.data.height)||(this.fire(new o.B(new Error(`Image "${p.name}" has invalid "stretchY" value`))),L=!1),this._validateContent(j.content,j)||(this.fire(new o.B(new Error(`Image "${p.name}" has invalid "content" value`))),L=!1),L}_validateStretch(p,j){if(!p)return!0;let L=0;for(const O of p){if(O[0]o.I.from(j))}getImageVersions(p){const j=this.imageVersions.get(p);if(j)return j}getImages(p,j,L){const O=[],q=[],H=this.imageProviders.get(j);for(const pe of p){if(!pe.iconsetId){O.push(pe);continue}const Ce=H.get(pe.iconsetId);Ce&&(this.getImage(pe,j)?q.push(pe):Ce.addPendingRequest(pe))}if(O.length===0)return void this._notify(q,j,L);let Y=!0;const te=!!this.loaded.get(j),de=this.images.get(j);if(!te)for(const pe of O)de.has(pe.toString())||(Y=!1);te||Y?this._notify(O,j,L):this.requestors.push({ids:O,scope:j,callback:L})}rasterizeImages(p,j){const L=new Map,{tasks:O,scope:q}=p;for(const[H,Y]of O.entries()){const te=this.getImage(Y.id,q);te&&L.set(H,{image:te,imageVariant:Y})}this._rasterizeImages(q,L,j)}_rasterizeImages(p,j,L){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:j,scope:p},L);else{const O=new Map;for(const[q,{image:H,imageVariant:Y}]of j.entries())O.set(q,this.imageRasterizer.rasterize(Y,H,p,0));L(void 0,O)}}getUpdatedImages(p){return this.updatedImages.get(p)||new Set}_notify(p,j,L){const O=this.images.get(j),q=new Map;for(const H of p){if(!O.get(H.toString())){if(H.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:H.name}))}const Y=O.get(H.toString());if(!Y){o.w(`Image "${H.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 te={data:Y.usvg?null:Y.data.clone(),pixelRatio:Y.pixelRatio,sdf:Y.sdf,usvg:Y.usvg,stretchX:Y.stretchX,stretchY:Y.stretchY,content:Y.content,hasRenderCallback:!!(Y.userImage&&Y.userImage.render)};Y.usvg&&Object.assign(te,{width:Y.icon.usvg_tree.width,height:Y.icon.usvg_tree.height}),q.set(o.I.toString(H),te)}L(null,{images:q,versions:this.getImageVersions(j)})}getPixelSize(p){const{width:j,height:L}=this.atlasImage.get(p);return{width:j,height:L}}getPattern(p,j,L){const O=p.toString(),q=this.patterns.get(j),H=q.get(O),Y=this.getImage(p,j);if(!Y)return null;if(H){if(H.position.version===Y.version)return H.position;H.position.version=Y.version}else{if(Y.usvg&&!Y.data){const te=this.getPatternInFlightId(O,j);if(this.patternsInFlight.has(te))return null;this.patternsInFlight.add(te);const de=new o.D(p).scaleSelf(o.o.devicePixelRatio),pe=new Map([[de.toString(),{image:Y,imageVariant:de}]]);return this._rasterizeImages(j,pe,(Ce,je)=>this.storePatternImage(de,j,Y,L,je)),null}this.storePattern(p,j,Y)}return this._updatePatternAtlas(j,L),q.get(O).position}getPatternInFlightId(p,j){return o.F(p,j)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(p,j,L,O,q){const H=p.toString(),Y=q?q.get(H):void 0;Y&&(L.data=Y,this.storePattern(p.id,j,L),this._updatePatternAtlas(j,O),this.patternsInFlight.delete(this.getPatternInFlightId(p.id.toString(),j)))}storePattern(p,j,L){const O={w:L.data.width+2*o.G,h:L.data.height+2*o.G,x:0,y:0},q=new o.H(O,L,o.G);this.patterns.get(j).set(p.toString(),{bin:O,position:q})}destroyAtlasTextures(){for(const p of this.atlasTexture.values())p&&p.destroy();this.atlasTexture.clear()}bind(p,j){const L=p.gl;let O=this.atlasTexture.get(j);O?this.dirty&&(O.update(this.atlasImage.get(j)),this.dirty=!1):(O=new o.T(p,this.atlasImage.get(j),L.RGBA8),this.atlasTexture.set(j,O)),O.bind(L.LINEAR,L.CLAMP_TO_EDGE)}_updatePatternAtlas(p,j){const L=this.patterns.get(p),O=Array.from(L.values()).map(({bin:de})=>de),{w:q,h:H}=o.J(O),Y=this.atlasImage.get(p);Y.resize({width:q||1,height:H||1});const te=this.images.get(p);for(const[de,{bin:pe,position:Ce}]of L.entries()){let je=Ce.padding;const Me=pe.x+je,qe=pe.y+je,$e=te.get(de).data,nt=$e.width,rt=$e.height;je=je>1?je-1:je,o.q.copy($e,Y,{x:0,y:0},{x:Me,y:qe},{width:nt,height:rt},j),o.q.copy($e,Y,{x:0,y:rt-je},{x:Me,y:qe-je},{width:nt,height:je},j),o.q.copy($e,Y,{x:0,y:0},{x:Me,y:qe+rt},{width:nt,height:je},j),o.q.copy($e,Y,{x:nt-je,y:0},{x:Me-je,y:qe},{width:je,height:rt},j),o.q.copy($e,Y,{x:0,y:0},{x:Me+nt,y:qe},{width:je,height:rt},j),o.q.copy($e,Y,{x:nt-je,y:rt-je},{x:Me-je,y:qe-je},{width:je,height:je},j),o.q.copy($e,Y,{x:0,y:rt-je},{x:Me+nt,y:qe-je},{width:je,height:je},j),o.q.copy($e,Y,{x:0,y:0},{x:Me+nt,y:qe+rt},{width:je,height:je},j),o.q.copy($e,Y,{x:nt-je,y:0},{x:Me-je,y:qe+rt},{width:je,height:je},j)}this.dirty=!0}beginFrame(){for(const p of this.images.keys())this.callbackDispatchedThisFrame.set(p,new Set)}dispatchRenderCallbacks(p,j){const L=this.images.get(j);for(const O of p){if(this.callbackDispatchedThisFrame.get(j).has(O.toString()))continue;this.callbackDispatchedThisFrame.get(j).add(O.toString());const q=L.get(O.toString());Re(q)&&this.updateImage(O,j,q)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Ns(E){const p=E.value,j=E.valueSpec,L=E.style,O=E.styleSpec,q=E.key,H=E.arrayElementValidator||nn;if(!Array.isArray(p))return[new o.V(q,p,`array expected, ${o.M(p)} found`)];if(j.length&&p.length!==j.length)return[new o.V(q,p,`array length ${j.length} expected, length ${p.length} found`)];if(j["min-length"]&&p.lengthO)return[new o.V(p,j,`${j} is greater than the maximum value ${O}`)]}return[]}function rs(E){const p=E.key,j=E.value;if(!o.K(j))return[new o.V(p,j,`object expected, ${o.M(j)} found`)];const L=E.valueSpec,O=o.L(j.type);let q,H,Y,te={};const de=O!=="categorical"&&j.property===void 0,pe=!de,Ce=function($e){const nt=$e.stops;return Array.isArray(nt)&&Array.isArray(nt[0])&&o.K(nt[0][0])}(j),je=hr({key:E.key,value:E.value,valueSpec:E.styleSpec.function,style:E.style,styleSpec:E.styleSpec,objectElementValidators:{stops:function($e){if(O==="identity")return[new o.V($e.key,$e.value,'identity function may not have a "stops" property')];let nt=[];const rt=$e.value;return nt=nt.concat(Ns({key:$e.key,value:rt,valueSpec:$e.valueSpec,style:$e.style,styleSpec:$e.styleSpec,arrayElementValidator:Me})),Array.isArray(rt)&&rt.length===0&&nt.push(new o.V($e.key,rt,"array must have at least one stop")),nt},default:function($e){return nn({key:$e.key,value:$e.value,valueSpec:L,style:$e.style,styleSpec:$e.styleSpec})}}});return O==="identity"&&de&&je.push(new o.V(E.key,E.value,'missing required property "property"')),O==="identity"||j.stops||je.push(new o.V(E.key,E.value,'missing required property "stops"')),O==="exponential"&&L.expression&&!o.O(L)&&je.push(new o.V(E.key,E.value,"exponential functions not supported")),E.styleSpec.$version>=8&&(pe&&!o.Q(L)?je.push(new o.V(E.key,E.value,"property functions not supported")):de&&!o.S(L)&&je.push(new o.V(E.key,E.value,"zoom functions not supported"))),O!=="categorical"&&!Ce||j.property!==void 0||je.push(new o.V(E.key,E.value,'"property" property is required')),je;function Me($e){let nt=[];const rt=$e.value,pt=$e.key;if(!Array.isArray(rt))return[new o.V(pt,rt,`array expected, ${o.M(rt)} found`)];if(rt.length!==2)return[new o.V(pt,rt,`array length 2 expected, length ${rt.length} found`)];if(Ce){if(!o.K(rt[0]))return[new o.V(pt,rt,`object expected, ${o.M(rt[0])} found`)];const vt=rt[0];if(vt.zoom===void 0)return[new o.V(pt,rt,"object stop key must have zoom")];if(vt.value===void 0)return[new o.V(pt,rt,"object stop key must have value")];const ot=o.L(vt.zoom);if(typeof ot!="number")return[new o.V(pt,vt.zoom,"stop zoom values must be numbers")];if(Y&&Y>ot)return[new o.V(pt,vt.zoom,"stop zoom values must appear in ascending order")];ot!==Y&&(Y=ot,H=void 0,te={}),nt=nt.concat(hr({key:`${pt}[0]`,value:rt[0],valueSpec:{zoom:{}},style:$e.style,styleSpec:$e.styleSpec,objectElementValidators:{zoom:Ys,value:qe}}))}else nt=nt.concat(qe({key:`${pt}[0]`,value:rt[0],style:$e.style,styleSpec:$e.styleSpec},rt));return o.U(o.W(rt[1]))?nt.concat([new o.V(`${pt}[1]`,rt[1],"expressions are not allowed in function stops.")]):nt.concat(nn({key:`${pt}[1]`,value:rt[1],valueSpec:L,style:$e.style,styleSpec:$e.styleSpec}))}function qe($e,nt){const rt=o.M($e.value),pt=o.L($e.value),vt=$e.value!==null?$e.value:nt;if(q){if(rt!==q)return[new o.V($e.key,vt,`${rt} stop domain type must match previous stop domain type ${q}`)]}else q=rt;if(rt!=="number"&&rt!=="string"&&rt!=="boolean"&&typeof pt!="number"&&typeof pt!="string"&&typeof pt!="boolean")return[new o.V($e.key,vt,"stop domain value must be a number, string, or boolean")];if(rt!=="number"&&O!=="categorical"){let ot=`number expected, ${rt} found`;return o.Q(L)&&O===void 0&&(ot+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V($e.key,vt,ot)]}return O!=="categorical"||rt!=="number"||typeof pt=="number"&&isFinite(pt)&&Math.floor(pt)===pt?O!=="categorical"&&rt==="number"&&typeof pt=="number"&&typeof H=="number"&&H!==void 0&&ptnew o.V(`${E.key}${L.key}`,E.value,L.message));const j=p.value.expression||p.value._styleExpression.expression;if(E.expressionContext==="property"&&E.propertyKey==="text-font"&&!j.outputDefined())return[new o.V(E.key,E.value,`Invalid data expression for "${E.propertyKey}". Output values must be contained as literals within the expression.`)];if(E.expressionContext==="property"&&E.propertyType==="layout"&&!o.$(j))return[new o.V(E.key,E.value,'"feature-state" data expressions are not supported with layout properties.')];if(E.expressionContext==="filter")return cs(j,E);if(E.expressionContext==="appearance")return yt(j,E);if(E.expressionContext&&E.expressionContext.indexOf("cluster")===0){if(!o.Z(j,["zoom","feature-state"]))return[new o.V(E.key,E.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(E.expressionContext==="cluster-initial"&&!o._(j))return[new o.V(E.key,E.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function cs(E,p){const j=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(p.valueSpec&&p.valueSpec.expression)for(const O of p.valueSpec.expression.parameters)j.delete(O);if(j.size===0)return[];const L=[];return E instanceof o.a0&&j.has(E.name)?[new o.V(p.key,p.value,`["${E.name}"] expression is not supported in a filter for a ${p.object.type} layer with id: ${p.object.id}`)]:(E.eachChild(O=>{L.push(...cs(O,p))}),L)}function yt(E,p){const j=new Set;if(p.valueSpec&&p.valueSpec.expression)for(const O of p.valueSpec.expression.parameters)j.add(O);if(j.size===0)return[];const L=[];return E instanceof o.a0&&!j.has(E.name)?[new o.V(p.key,p.value,`["${E.name}"] is not an allowed parameter`)]:(E.eachChild(O=>{L.push(...yt(O,p))}),L)}function is(E){const p=E.key,j=E.value,L=E.valueSpec,O=[];return Array.isArray(L.values)?L.values.indexOf(o.L(j))===-1&&O.push(new o.V(p,j,`expected one of [${L.values.join(", ")}], ${JSON.stringify(j)} found`)):Object.keys(L.values).indexOf(o.L(j))===-1&&O.push(new o.V(p,j,`expected one of [${Object.keys(L.values).join(", ")}], ${JSON.stringify(j)} found`)),O}function Bs(E){return o.a4(o.W(E.value))?bt(Object.assign({},E,{expressionContext:"filter",valueSpec:E.styleSpec[`filter_${E.layerType||"fill"}`]})):ps(E)}function ps(E){const p=E.value,j=E.key;if(!Array.isArray(p))return[new o.V(j,p,`array expected, ${o.M(p)} found`)];if(p.length<1)return[new o.V(j,p,"filter array must have at least 1 element")];const L=E.styleSpec;let O=is({key:`${j}[0]`,value:p[0],valueSpec:L.filter_operator});const q=()=>{p.length>=2&&(o.a2(p[1])||O.push(new o.V(`${j}[1]`,p[1],`string expected, ${o.M(p[1])} found`)));for(let H=2;H":case">=":p.length>=2&&o.L(p[1])==="$type"&&O.push(new o.V(j,p,`"$type" cannot be use with operator "${p[0]}"`)),p.length!==3&&O.push(new o.V(j,p,`filter array for operator "${p[0]}" must have 3 elements`)),q();break;case"==":case"!=":p.length!==3&&O.push(new o.V(j,p,`filter array for operator "${p[0]}" must have 3 elements`)),q();break;case"in":case"!in":q();break;case"any":case"all":case"none":for(let H=1;H{de in j&&p.push(new o.V(L,j[de],`"${de}" is prohibited for ref layers`))}),O.layers.forEach(de=>{o.L(de.id)===Y&&(te=de)}),te?te.ref?p.push(new o.V(L,j.ref,"ref cannot reference another ref layer")):H=o.L(te.type):typeof Y=="string"&&p.push(new o.V(L,j.ref,`ref layer "${Y}" not found`))}else if(H!=="background"&&H!=="sky"&&H!=="slot")if(j.source)if(o.a2(j.source)){const te=O.sources&&O.sources[j.source],de=te&&o.L(te.type);te?de==="vector"&&H==="raster"?p.push(new o.V(L,j.source,`layer "${j.id}" requires a raster source`)):de==="raster"&&H!=="raster"?p.push(new o.V(L,j.source,`layer "${j.id}" requires a vector source`)):de!=="vector"||j["source-layer"]?de==="raster-dem"&&H!=="hillshade"?p.push(new o.V(L,j.source,"raster-dem source can only be used with layer type 'hillshade'.")):de!=="raster-array"||["raster","raster-particle"].includes(H)?H==="line"&&j.paint&&(j.paint["line-gradient"]||j.paint["line-trim-offset"])&&de==="geojson"&&!te.lineMetrics?p.push(new o.V(L,j,`layer "${j.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):H==="raster-particle"&&de!=="raster-array"&&p.push(new o.V(L,j.source,`layer "${j.id}" requires a 'raster-array' source.`)):p.push(new o.V(L,j.source,"raster-array source can only be used with layer type 'raster'.")):p.push(new o.V(L,j,`layer "${j.id}" must specify a "source-layer"`)):p.push(new o.V(L,j.source,`source "${j.source}" not found`))}else p.push(new o.V(`${L}.source`,j.source,'"source" must be a string'));else p.push(new o.V(L,j,'missing required property "source"'));return p=p.concat(hr({key:L,value:j,valueSpec:q.layer,style:E.style,styleSpec:E.styleSpec,objectElementValidators:{"*":()=>[],type:()=>nn({key:`${L}.type`,value:j.type,valueSpec:q.layer.type,style:E.style,styleSpec:E.styleSpec,object:j,objectKey:"type"}),filter:te=>Bs(Object.assign({layerType:H},te)),layout:te=>hr({layer:j,key:te.key,value:te.value,valueSpec:{},style:te.style,styleSpec:te.styleSpec,objectElementValidators:{"*":de=>Lr(Object.assign({layerType:H},de))}}),paint:te=>hr({layer:j,key:te.key,value:te.value,valueSpec:{},style:te.style,styleSpec:te.styleSpec,objectElementValidators:{"*":de=>kr(Object.assign({layerType:H,layer:j},de))}}),appearances(te){const de=Ns({key:te.key,value:te.value,valueSpec:te.valueSpec,style:te.style,styleSpec:te.styleSpec,arrayElementValidator:je=>function(Me){const{key:qe,layer:$e,layerType:nt}=Me,rt=o.L(Me.value),pt=o.L(rt.name),vt=o.L(rt.condition),ot=hr({key:qe,value:rt,valueSpec:Me.styleSpec.appearance,style:Me.style,styleSpec:Me.styleSpec,objectElementValidators:{condition:Ut=>function(Tt){const $t=[];return $t.push(...bt({key:Tt.key,value:Tt.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),$t}(Object.assign({layer:$e,layerType:nt},Ut)),properties:Ut=>function(Tt){const $t=[],{styleSpec:_t,layer:St,layerType:Rt}=Tt,Zt=_t[`paint_${Rt}`],qt=_t[`layout_${Rt}`],xs=Tt.object[Tt.objectKey];for(const as in xs){const Os=as in Zt?"paint":as in qt?"layout":void 0;if(!Os){$t.push(new o.V(Tt.key,as,`unknown property "${as}" for layer type "${Rt}"`));continue}const Hs=Object.assign({},Tt,{key:`${Tt.key}.${as}`,object:xs,objectKey:as,layer:St,layerType:Rt,value:xs[as],valueSpec:Os==="paint"?Zt[as]:qt[as]});$t.push(...lr(Hs,Os))}return $t}(Object.assign({layer:$e,layerType:nt},Ut))}});return pt!=="hidden"&&vt===void 0&&ot.push(new o.V(Me.key,"name",'Appearance with name different than "hidden" must have a condition')),ot}(Object.assign({layerType:H,layer:j},je))}),pe=Array.isArray(te.value)?te.value:[],Ce=new Set;return pe.forEach((je,Me)=>{const qe=o.L(je.name);if(qe)if(Ce.has(qe)){const $e=o.L(j.id);de.push(new o.V(te.key,qe,`Duplicated appearance name "${qe}" for layer "${$e}"`))}else Ce.add(qe)}),de}}})),p}function Ur({key:E,value:p}){return o.a2(p)?[]:[new o.V(E,p,`string expected, ${o.M(p)} found`)]}const Mr={promoteId:function E({key:p,value:j}){if(o.a2(j))return Ur({key:p,value:j});if(Array.isArray(j)){const O=[],q=o.W(j),H=o.X(q);return H.result==="error"?(H.value.forEach(Y=>{O.push(new o.V(`${p}${Y.key}`,null,`${Y.message}`))}),O):(o.Z(H.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"])||O.push(new o.V(`${p}`,null,"promoteId expression should be only feature dependent")),O)}if(!o.K(j))return[new o.V(p,j,`string, expression or object expected, "${o.M(j)}" found`)];const L=[];for(const O in j)L.push(...E({key:`${p}.${O}`,value:j[O]}));return L}};function Cr(E){const p=E.value,j=E.key,L=E.styleSpec,O=E.style;if(!o.K(p))return[new o.V(j,p,`object expected, ${o.M(p)} found`)];if(!("type"in p))return[new o.V(j,p,'"type" is required')];const q=o.L(p.type);let H=[];switch(["vector","raster","raster-dem","raster-array"].includes(q)&&("url"in p||"tiles"in p||H.push(new o.a5(j,p,'Either "url" or "tiles" is required.'))),q){case"vector":case"raster":case"raster-dem":case"raster-array":return H=H.concat(hr({key:j,value:p,valueSpec:L[`source_${q.replace("-","_")}`],style:E.style,styleSpec:L,objectElementValidators:Mr})),H;case"geojson":if(H=hr({key:j,value:p,valueSpec:L.source_geojson,style:O,styleSpec:L,objectElementValidators:Mr}),"cluster"in p&&"clusterProperties"in p){if(!o.K(p.clusterProperties))return[new o.V(`${j}.clusterProperties`,p,`object expected, ${o.M(p)} found`)];for(const Y in p.clusterProperties){const te=p.clusterProperties[Y];if(!Array.isArray(te))return[new o.V(`${j}.clusterProperties.${Y}`,te,"array expected")];const[de,pe]=te,Ce=typeof de=="string"?[de,["accumulated"],["get",Y]]:de;H.push(...bt({key:`${j}.${Y}.map`,value:pe,expressionContext:"cluster-map"})),H.push(...bt({key:`${j}.${Y}.reduce`,value:Ce,expressionContext:"cluster-reduce"}))}}return H;case"video":return hr({key:j,value:p,valueSpec:L.source_video,style:O,styleSpec:L});case"image":return hr({key:j,value:p,valueSpec:L.source_image,style:O,styleSpec:L});case"canvas":return[new o.V(j,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return is({key:`${j}.type`,value:p.type,valueSpec:{values:Xr(L)}})}}function Xr(E){return E.source.reduce((p,j)=>{const L=E[j];return L.type.type==="enum"&&(p=p.concat(Object.keys(L.type.values||{}))),p},[])}function Ln(E){const p=E.value,j=E.styleSpec,L=j.light,O=E.style;if(p===void 0)return[];if(!o.K(p))return[new o.V("light",p,`object expected, ${o.M(p)} found`)];let q=[];for(const H in p){const Y=H.match(/^(.*)-transition$/),te=H.match(/^(.*)-use-theme$/);q=q.concat(te&&L[te[1]]?nn({key:H,value:p[H],valueSpec:{type:"string"},style:O,styleSpec:j}):Y&&L[Y[1]]&&L[Y[1]].transition?nn({key:H,value:p[H],valueSpec:j.transition,style:O,styleSpec:j}):L[H]?nn({key:H,value:p[H],valueSpec:L[H],style:O,styleSpec:j}):[new o.V(H,p[H],`unknown property "${H}"`)])}return q}function Zs(E){const p=E.value;if(!p)return[];const j=E.key;if(!o.K(p))return[new o.V(j,p,`object expected, ${o.M(p)} found`)];let L=[];const O=E.styleSpec,q=O["light-3d"],H=E.style,Y=E.style.lights;for(const pe of["type","id"])if(!(pe in p))return L=L.concat([new o.V(j,p,`missing property "${pe}"`)]),L;if(!o.a2(p.type))return L=L.concat([new o.V(`${j}.type`,p.type,"string expected")]),L;if(Y)for(let pe=0;pe[],array:Ns,boolean:function(E){const p=E.value,j=E.key;return o.a1(p)?[]:[new o.V(j,p,`boolean expected, ${o.M(p)} found`)]},number:Ys,color:function({key:E,value:p}){return o.a2(p)?o.a3.parseCSSColor(p)===null?[new o.V(E,p,`color expected, "${p}" found`)]:[]:[new o.V(E,p,`color expected, ${o.M(p)} found`)]},enum:is,filter:Bs,function:rs,layer:qr,object:hr,source:Cr,model:o.a9,light:Ln,"light-3d":Zs,terrain:Yr,fog:ss,string:Ur,formatted:function(E){return Ur(E).length===0?[]:bt(E)},resolvedImage:function(E){return Ur(E).length===0?[]:bt(E)},projection:function(E){const p=E.value,j=E.styleSpec,L=j.projection,O=E.style;if(o.K(p)){let q=[];for(const H in p)q=q.concat(nn({key:H,value:p[H],valueSpec:L[H],style:O,styleSpec:j}));return q}return o.a2(p)?[]:[new o.V("projection",p,`object or string expected, ${o.M(p)} found`)]},import:function(E){const p=E.key,{value:j,styleSpec:L}=E;if(!o.K(j))return[new o.V(p,j,"import must be an object")];const{data:O,...q}=j;Object.defineProperty(q,"__line__",{value:j.__line__,enumerable:!1});let H=hr(Object.assign({},E,{value:q,valueSpec:L.import}));return o.L(q.id)===""&&H.push(new o.V(`${E.key}.id`,q,"import id can't be an empty string")),O&&(H=H.concat(Qn(O,L,{key:`${E.key}.data`}))),H},iconset:function(E){const p=E.value,j=E.key,L=E.styleSpec,O=E.style;if(!o.K(p))return[new o.V(j,p,"object expected")];if(!p.type)return[new o.V(j,p,'"type" is required')];const q=o.L(p.type);let H=[];if(H=H.concat(hr({key:j,value:p,valueSpec:L[`iconset_${q}`],style:O,styleSpec:L})),function(Y,te){return!(Y!=="source"||!te.source)}(q,p)){const Y=O.sources&&O.sources[p.source],te=Y&&o.L(Y.type);Y?te!=="raster-array"&&H.push(new o.V(j,p.source,`iconset cannot be used with a source of type ${String(te)}, it only be used with a "raster-array" source type`)):H.push(new o.V(j,p.source,`source "${p.source}" not found`))}return H}};function nn(E,p=!1){const j=E.value,L=E.valueSpec,O=E.styleSpec;if(L.expression){if(o.a6(o.L(j)))return rs(E);if(o.U(o.W(j)))return bt(E)}if(L.type&&ta[L.type]){const q=ta[L.type](E);return p===!0&&q.length>0&&Array.isArray(E.value)?bt(E):q}return hr(Object.assign({},E,{valueSpec:L.type?O[L.type]:L}))}function hr(E){const p=E.key,j=E.value,L=E.valueSpec||{},O=E.objectElementValidators||{},q=E.style,H=E.styleSpec;if(!o.K(j))return[new o.V(p,j,`object expected, ${o.M(j)} found`)];let Y=[];for(const te in j){const de=te.split(".")[0];let pe;O[de]?pe=O[de]:L[de]?pe=nn:O["*"]?pe=O["*"]:L["*"]&&(pe=nn),pe?Y=Y.concat(pe({key:(p&&`${p}.`)+te,value:j[te],valueSpec:L[de]||L["*"],style:q,styleSpec:H,object:j,objectKey:te},j)):Y.push(new o.a5(p,j[te],`unknown property "${te}"`))}for(const te in L){if(O[te])continue;const de=L[te];de.required&&de.default===void 0&&j[te]===void 0&&Y.push(new o.V(p,j,`missing required property "${te}"`))}return Y}function Pr({key:E,value:p}){const j=Ur({key:E,value:p});if(j.length)return j;const L=p;return L.indexOf("{fontstack}")===-1&&j.push(new o.V(E,p,'"glyphs" url must include a "{fontstack}" token')),L.indexOf("{range}")===-1&&j.push(new o.V(E,p,'"glyphs" url must include a "{range}" token')),j}function Qn(E,p=o.a8,j={}){return hr({key:j.key||"",value:E,valueSpec:Object.assign(p.$root,{"*":{type:"*"}}),styleSpec:p,style:E,objectElementValidators:{glyphs:Pr}})}function Gt(E,p=o.a8){return Cs(Qn(E,p))}const gr=E=>Cs(Cr(E)),zt=E=>Cs(Ln(E)),Se=E=>Cs(Zs(E)),ze=E=>Cs(Yr(E)),st=E=>Cs(ss(E)),gt=E=>Cs(function(p){const j=p.value,L=p.style,O=p.styleSpec,q=O.snow;if(j===void 0)return[];if(!o.K(j))return[new o.V("snow",j,`object expected, ${o.M(j)} found`)];let H=[];for(const Y in j){const te=Y.match(/^(.*)-transition$/);H=H.concat(te&&q[te[1]]&&q[te[1]].transition?nn({key:Y,value:j[Y],valueSpec:O.transition,style:L,styleSpec:O}):q[Y]?nn({key:Y,value:j[Y],valueSpec:q[Y],style:L,styleSpec:O}):[new o.a5(Y,j[Y],`unknown property "${Y}"`)])}return H}(E)),At=E=>Cs(function(p){const j=p.value,L=p.style,O=p.styleSpec,q=O.rain;if(j===void 0)return[];if(!o.K(j))return[new o.V("rain",j,`object expected, ${o.M(j)} found`)];let H=[];for(const Y in j){const te=Y.match(/^(.*)-transition$/);H=H.concat(te&&q[te[1]]&&q[te[1]].transition?nn({key:Y,value:j[Y],valueSpec:O.transition,style:L,styleSpec:O}):q[Y]?nn({key:Y,value:j[Y],valueSpec:q[Y],style:L,styleSpec:O}):[new o.a5(Y,j[Y],`unknown property "${Y}"`)])}return H}(E)),Ft=E=>Cs(qr(E)),Wt=E=>Cs(Bs(E)),Vt=E=>Cs(kr(E)),Jt=E=>Cs(Lr(E)),qs=E=>Cs(o.a9(E));function Cs(E){return E.slice().sort((p,j)=>p.line&&j.line?p.line-j.line:0)}function xr(E,p){let j=!1;if(p&&p.length)for(const L of p)L instanceof o.a5?o.w(L.message):(E.fire(new o.B(new Error(L.message))),j=!0);return j}const Wr=o.a8.light;let tn;class Rr extends o.E{constructor(p,j="flat"){super(),this._transitionable=new o.aa(tn||(tn=new o.ab({anchor:new o.ac(Wr.anchor),position:new o.ad(Wr.position),color:new o.ac(Wr.color),intensity:new o.ac(Wr.intensity)}))),this.setLight(p,j),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(p,j,L={}){this._validate(zt,p,L)||(this._transitionable.setTransitionOrValue(p),this.id=j)}updateTransitions(p){this._transitioning=this._transitionable.transitioned(p,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(p){this.properties=this._transitioning.possiblyEvaluate(p)}_validate(p,j,L){return(!L||L.validate!==!1)&&xr(this,p.call(Gt,Object.assign({value:j,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const sn=o.a8.terrain;let rn=class extends o.E{constructor(E,p,j,L,O){super(),this.scope=j,this._transitionable=new o.aa(new o.ab({source:new o.ac(sn.source),exaggeration:new o.ac(sn.exaggeration)}),j,L),this._transitionable.setTransitionOrValue(E,L),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=p,this.worldview=O}get(){return this._transitionable.serialize()}set(E,p){this._transitionable.setTransitionOrValue(E,p)}updateTransitions(E){this._transitioning=this._transitionable.transitioned(E,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(E){this.properties=this._transitioning.possiblyEvaluate(E)}getExaggeration(E){return this._transitioning.possiblyEvaluate(new o.ae(E,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const E=this._transitionable._values.exaggeration;if(!E)return null;const p=E.value.expression;if(!p)return null;let j=-1,L=-1,O=1;for(const q of p.zoomStops)O=p.evaluate(new o.ae(q,{worldview:this.worldview})),O>.01?(j=q,L=-1):L=q;return O<.01&&j>0&&L>j?[j,L]:null}isZoomDependent(){const E=this._transitionable._values.exaggeration;return E!=null&&E.value!=null&&E.value.expression!=null&&E.value.expression instanceof o.af}};const un=.05;function fa(E,p,j,L){const O=o.aj(45,65,j),[q,H]=go(E,L);let Y=1-Math.min(1,Math.exp((p-q)/(H-q)*-6));return Y*=Y*Y,Y=Math.min(1,1.00747*Y),Y*O*E.alpha}function go(E,p){const j=.5/Math.tan(.5*p);return[E.range[0]+j,E.range[1]+j]}function wo(E,p,j,L,O){const q=o.ah([],[p,j,L],O.mercatorFogMatrix);return fa(E,o.ai(q),O.pitch,O._fov)}function co(E,p,j,L,O,q,H){const Y=[[j,L,0],[O,L,0],[O,q,0],[j,q,0]];let te=Number.MAX_VALUE,de=-Number.MAX_VALUE;for(const pe of Y){const Ce=o.ah([],pe,p),je=o.ai(Ce);te=Math.min(te,je),de=Math.max(de,je)}return[fa(E,te,H.pitch,H._fov),fa(E,de,H.pitch,H._fov)]}const ia=o.a8.fog;class Ji extends o.E{constructor(p,j,L,O){super();const q=new o.ab({range:new o.ac(ia.range),color:new o.ac(ia.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(ia["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(ia["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(ia["horizon-blend"]),"star-intensity":new o.ac(ia["star-intensity"]),"vertical-range":new o.ac(ia["vertical-range"])});this._transitionable=new o.aa(q,L,new Map(O)),this.set(p,O),this._transitioning=this._transitionable.untransitioned(),this._transform=j,this.properties=new o.ak(q),this.scope=L}get state(){const p=this._transform,j=p.projection.name==="globe",L=o.al(p.zoom),O=this.properties.get("range"),q=[.5,3];return{range:j?[o.am(q[0],O[0],L),o.am(q[1],O[1],L)]:O,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(p,j,L={}){if(this._validate(st,p,L))return;const O=Object.assign({},p);for(const q of Object.keys(ia))O[q]===void 0&&(O[q]=ia[q].default);this._options=O,this._transitionable.setTransitionOrValue(this._options,j)}getOpacity(p){if(!this._transform.projection.supportsFog)return 0;const j=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,p))*j.a}getOpacityAtLatLng(p,j){return this._transform.projection.supportsFog?function(L,O,q){const H=o.ag.fromLngLat(O),Y=q.elevation?q.elevation.getAtPointOrZero(H):0;return wo(L,H.x,H.y,Y,q)}(this.state,p,j):0}getOpacityForTile(p){if(!this._transform.projection.supportsFog)return[1,1];const j=this._transform.calculateFogTileMatrix(p.toUnwrapped());return co(this.state,j,0,0,o.an,o.an,this._transform)}getOpacityForBounds(p,j,L,O,q){return this._transform.projection.supportsFog?co(this.state,p,j,L,O,q,this._transform):[1,1]}getFovAdjustedRange(p){return this._transform.projection.supportsFog?go(this.state,p):[0,1]}isVisibleOnFrustum(p){if(!this._transform.projection.supportsFog)return!1;const j=[4,5,6,7];for(const L of j){const O=p.points[L];let q;if(O[2]>=0)q=O;else{const H=p.points[L-4];q=o.ao(H,O,H[2]/(H[2]-O[2]))}if(wo(this.state,q[0],q[1],0,this._transform)>=un)return!0}return!1}updateConfig(p){this._transitionable.setTransitionOrValue(this._options,new Map(p))}updateTransitions(p){this._transitioning=this._transitionable.transitioned(p,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(p){this.properties=this._transitioning.possiblyEvaluate(p)}_validate(p,j,L){return(!L||L.validate!==!1)&&xr(this,p.call(Gt,Object.assign({value:j,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let il,bi,eo,no=class extends o.E{constructor(E,p,j,L){super();const O=il||(il=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(O,j,new Map(L)),this.set(E,L),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(O),this.scope=j}get state(){const E=this.properties.get("opacity"),p=this.properties.get("color"),j=this.properties.get("direction"),L=o.ap(j[0]),O=-Math.max(o.ap(j[1]),.01),q=[Math.cos(L)*Math.cos(O),Math.sin(L)*Math.cos(O),Math.sin(O)],H=this.properties.get("vignette"),Y=this.properties.get("vignette-color");return Y.a=H,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(p.r,p.g,p.b,p.a*E),direction:q,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:Y}}get(){return this._transitionable.serialize()}set(E,p,j={}){if(this._validate(gt,E,j))return;const L=Object.assign({},E),O=o.a8.snow;for(const q of Object.keys(O))L[q]===void 0&&(L[q]=O[q].default);this._options=L,this._transitionable.setTransitionOrValue(this._options,p)}updateConfig(E){this._transitionable.setTransitionOrValue(this._options,new Map(E))}updateTransitions(E){this._transitioning=this._transitionable.transitioned(E,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(E){this.properties=this._transitioning.possiblyEvaluate(E)}_validate(E,p,j){return(!j||j.validate!==!1)&&xr(this,E.call(Gt,Object.assign({value:p,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},ba=class extends o.E{constructor(E,p,j,L){super();const O=bi||(bi=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(O,j,new Map(L)),this.set(E,L),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(O),this.scope=j}get state(){const E=this.properties.get("opacity"),p=this.properties.get("color"),j=this.properties.get("direction"),L=o.ap(j[0]),O=-Math.max(o.ap(j[1]),.01),q=[Math.cos(L)*Math.cos(O),Math.sin(L)*Math.cos(O),Math.sin(O)],H=this.properties.get("vignette-color");return H.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(p.r,p.g,p.b,p.a*E),direction:q,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:H}}get(){return this._transitionable.serialize()}set(E,p,j={}){if(this._validate(At,E,j))return;const L=Object.assign({},E),O=o.a8.rain;for(const q of Object.keys(O))L[q]===void 0&&(L[q]=O[q].default);this._options=L,this._transitionable.setTransitionOrValue(this._options,p)}updateConfig(E){this._transitionable.setTransitionOrValue(this._options,new Map(E))}updateTransitions(E){this._transitioning=this._transitionable.transitioned(E,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(E){this.properties=this._transitioning.possiblyEvaluate(E)}_validate(E,p,j){return(!j||j.validate!==!1)&&xr(this,E.call(Gt,Object.assign({value:p,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class ir extends o.E{constructor(p,j,L,O){super(),this.scope=L,this._options=p,this.properties=new o.ak(j),this._transitionable=new o.aa(j,L,new Map(O)),this._transitionable.setTransitionOrValue(p.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(p){this._transitionable.setTransitionOrValue(this._options.properties,new Map(p))}updateTransitions(p){this._transitioning=this._transitionable.transitioned(p,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(p){this.properties=this._transitioning.possiblyEvaluate(p)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(p,j){this._options=p,this._transitionable.setTransitionOrValue(p.properties,j)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const ra=()=>eo||(eo=new o.ab({color:new o.ac(o.a8.properties_light_ambient.color),"color-use-theme":new o.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ac(o.a8.properties_light_ambient.intensity)}));let Ci;const qo=()=>Ci||(Ci=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 Xo{constructor(p,j,L){this.screenBounds=p,this.cameraPoint=L.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=j,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,L)}static createFromScreenPoints(p,j){let L,O;if(p instanceof o.P||typeof p[0]=="number"){const q=o.P.convert(p);L=[q],O=j.isPointAboveHorizon(q)}else{const q=o.P.convert(p[0]),H=o.P.convert(p[1]),Y=q.add(H)._div(2);L=[q,H],O=o.as(q,H).every(te=>j.isPointAboveHorizon(te))&&j.isPointAboveHorizon(Y)}return new Xo(L,O,j)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(p){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],p)}bufferedCameraGeometry(p){const j=this.screenBounds[0],L=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],O=o.as(j,L,0,!1);return this.cameraPoint.y>L.y&&(this.cameraPoint.x>j.x&&this.cameraPoint.x=L.x?O[2]=this.cameraPoint:this.cameraPoint.x<=j.x&&(O[3]=this.cameraPoint)),o.at(O,p)}bufferedCameraGeometryGlobe(p){const j=this.screenBounds[0],L=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],O=o.as(j,L,p),q=this.cameraPoint.clone(),H=+(q.x>j.x)+ +(q.x>L.x);switch(3*(+(q.y>j.y)+ +(q.y>L.y))+H){case 0:O[0]=q,O[4]=q.clone();break;case 1:O.splice(1,0,q);break;case 2:O[1]=q;break;case 3:O.splice(4,0,q);break;case 5:O.splice(2,0,q);break;case 6:O[3]=q;break;case 7:O.splice(3,0,q);break;case 8:O[2]=q}return O}containsTile(p,j,L,O=0){const q=Math.max(p.queryPadding,p.evaluateQueryRenderedFeaturePadding())/j._pixelsPerMercatorPixel+1,H=L?this._bufferedCameraMercator(q,j):this._bufferedScreenMercator(q,j);let Y=p.tileID.wrap+(H.unwrapped?O:0);const te=H.polygon.map(nt=>o.au(p.tileTransform,nt,Y));if(!o.av(te,0,0,o.an,o.an))return;Y=p.tileID.wrap+(this.screenGeometryMercator.unwrapped?O:0);const de=this.screenGeometryMercator.polygon.map(nt=>o.aw(p.tileTransform,nt,Y)),pe=de.map(nt=>new o.P(nt[0],nt[1])),Ce=j.getFreeCameraOptions().position||new o.ag(0,0,0),je=o.aw(p.tileTransform,Ce,Y),Me=de.map(nt=>{const rt=o.ax(nt,nt,je);return o.ay(rt,rt),new o.az(je,rt)}),qe=o.aA(p,1,j.zoom)*j._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:pe,tilespaceRays:Me,bufferedTilespaceGeometry:te,bufferedTilespaceBounds:($e=o.aB(te),$e.min.x=o.aC($e.min.x,0,o.an),$e.min.y=o.aC($e.min.y,0,o.an),$e.max.x=o.aC($e.max.x,0,o.an),$e.max.y=o.aC($e.max.y,0,o.an),$e),tile:p,tileID:p.tileID,pixelToTileUnitsFactor:qe};var $e}_bufferedScreenMercator(p,j){const L=nu(p);if(this._screenRaycastCache[L])return this._screenRaycastCache[L];{let O;return O=j.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(p),j):{polygon:this.bufferedScreenGeometry(p).map(q=>j.pointCoordinate3D(q)),unwrapped:!0},this._screenRaycastCache[L]=O,O}}_bufferedCameraMercator(p,j){const L=nu(p);if(this._cameraRaycastCache[L])return this._cameraRaycastCache[L];{let O;return O=j.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(p),j):{polygon:this.bufferedCameraGeometry(p).map(q=>j.pointCoordinate3D(q)),unwrapped:!0},this._cameraRaycastCache[L]=O,O}}_projectAndResample(p,j){const L=function(q,H){const Y=o.aD([],H.pixelMatrix,H.globeMatrix),te=[0,-o.aF,0,1],de=[0,o.aF,0,1],pe=[0,0,0,1];o.aE(te,te,Y),o.aE(de,de,Y),o.aE(pe,pe,Y);const Ce=new o.P(te[0]/te[3],te[1]/te[3]),je=new o.P(de[0]/de[3],de[1]/de[3]),Me=o.aG(q,Ce)&&te[3]1?ol(q.slice(0,nt),H):[],vt=ntnew o.P(Kc($t.x),$t.y)),vt=vt.map($t=>new o.P(Kc($t.x),$t.y));const ot=[...pt];ot.length===0&&ot.push(vt[vt.length-1]);const Ut=o.am(ot[ot.length-1].y,(vt.length===0?pt[0]:vt[0]).y,rt);let Tt;return Tt=Me?[new o.P(0,Ut),new o.P(0,0),new o.P(1,0),new o.P(1,Ut)]:[new o.P(1,Ut),new o.P(1,1),new o.P(0,1),new o.P(0,Ut)],ot.push(...Tt),vt.length===0?ot.push(pt[0]):ot.push(...vt),{polygon:ot.map($t=>new o.ag($t.x,$t.y)),unwrapped:!1}}(p,j);if(L)return L;const O=function(q,H){let Y=!1,te=-1/0,de=0;for(let Ce=0;Cete&&(te=q[Ce].x,de=Ce);for(let Ce=0;Ce.5&&(Me.x{Ce.x-=1}),{polygon:q,unwrapped:Y}}(ol(p,j).map(q=>new o.P(Kc(q.x),q.y)),j);return{polygon:O.polygon.map(q=>new o.ag(q.x,q.y)),unwrapped:O.unwrapped}}}function ol(E,p){return o.aI(E,j=>{const L=p.pointCoordinate3D(j);j.x=L.x,j.y=L.y},1/256)}function Kc(E){return E<0?1+E%1:E%1}function nu(E){return 100*E|0}function Nf(E,p,j){try{p=function(O){if(!O.variants)return O;if(!Array.isArray(O.variants))throw new Error("variants must be an array");for(const q of O.variants){if(q==null||typeof q!="object"||q.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(q.capabilities))throw new Error("capabilities must be an array");if(q.capabilities.length===1&&q.capabilities[0]==="meshopt")return Object.assign(O,q)}return O}(p)}catch(O){return new Error("Failed to process TileJSON variants",{cause:O})}const L=o.aJ(Object.assign({},p,E),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return E.url&&p.tiles&&E.tiles&&(L.tiles=p.tiles),L.tiles=j.canonicalizeTileset(L,E.url),L}function Ah(E,p,j,L,O){const q=function(Y,te){if(Y)return O(Y);if(te){E.url&&te.tiles&&E.tiles&&delete E.tiles;const de=Nf(E,te,p);if(de instanceof Error)return O(de);O(null,de)}},H=function(Y,te,de){if(!Y)return null;if(!te&&!de)return Y;de=de||Y.worldview_default;const pe=Object.values(Y.language||{});if(pe.length===0)return null;const Ce=Object.values(Y.worldview||{});if(Ce.length===0)return null;const je=pe.every(qe=>qe===te),Me=Ce.every(qe=>qe===de);return je&&Me?Y:te in(Y.language_options||{})||de in(Y.worldview_options||{})?null:Y.language_options&&Y.worldview_options?Y:null}(E.data,j,L);return H?o.o.frame(()=>q(null,H)):E.url?o.m(p.transformRequest(p.normalizeSourceURL(E.url,null,j,L),o.R.Source),q):o.o.frame(()=>{const{data:Y,...te}=E;q(null,te)})}function kf(E,p){const j=Math.pow(2,p.z),L=Math.floor(o.aH(E.getWest())*j),O=Math.floor(o.aL(E.getNorth())*j),q=Math.ceil(o.aH(E.getEast())*j),H=Math.ceil(o.aL(E.getSouth())*j);return p.x>=L&&p.x=O&&p.ythis.maxzoom||p.z{this._tileJSONRequest=null,this._loaded=!0,H?(j&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${j}`),L&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${L}`),this.fire(new o.B(H))):Y&&(this._setTileJSON(Y),Ue(Y.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"}))),p&&p(H)};this.provider=this._options.provider;const q=function(H){if("provider"in H&&!H.provider)return null;let Y=H.provider;if(!Y&&"url"in H&&H.url&&(Y=o.aM(H.url)),!Y)return null;const te=o.g.TILE_PROVIDER_URLS[Y];if(!te)return null;let de;try{de=new URL(te,o.g.API_URL).href}catch{return o.w(`TileProvider "${Y}" has an invalid URL: "${te}"`),null}return{name:Y,url:de}}(this._options);if(this.provider&&!q)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(p&&p());this._tileJSONRequest=q?this._loadWithProvider(q,O):Ah(this._options,this.map._requestManager,j,L,O)}_loadWithProvider(p,j){this.provider=p.name;const L=new AbortController,O=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,q=O?Object.assign({},this._options,{url:O.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:p.name,url:p.url,source:this.id,scope:this.scope,type:this.type,options:q,request:O},(H,Y)=>{if(L.signal.aborted)return;if(H)return void j(H);const te=Y?Y.find(de=>de!=null):null;if(te){const de=Nf(this._options,te,this.map._requestManager);de instanceof Error?j(de):j(null,de)}else j(null,{tiles:this._options.tiles})}),{cancel:()=>{L.abort()}}}_setTileJSON(p){if(Object.assign(this,p),this.hasWorldviews=!!p.worldview_options,p.worldview_default&&(this.worldviewDefault=p.worldview_default),p.vector_layers){this.vectorLayers=p.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const j of p.vector_layers)this.vectorLayerIds.push(j.id),p.worldview&&p.worldview[j.source]&&this.localizableLayerIds.add(j.id)}this.tileBounds=am.fromTileJSON(p)}loaded(){return this._loaded}hasTile(p){return!this.tileBounds||this.tileBounds.contains(p.canonical)}onAdd(p){this.map=p,this.load()}reload(){this.cancelTileJSONRequest();const p=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(p))}setTiles(p){return this._options.tiles=p,this.reload(),this}setUrl(p){return this.url=p,this._options.url=p,this.reload(),this}onRemove(p){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(p,j){const L=p.tileID.canonical.url(this.tiles,this.scheme),O=this.map._requestManager.normalizeTileURL(L),q=this.map._requestManager.transformRequest(O,o.R.Tile),H=this.map.style?this.map.style.getLut(this.scope):null,Y=H?{image:H.image.clone()}:null,te={request:q,data:void 0,uid:p.uid,tileID:p.tileID,tileZoom:p.tileZoom,zoom:p.tileID.overscaledZ,maxZoom:this.maxzoom,lut:Y,tileSize:this.tileSize*p.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:p.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:p.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(L)&&(te.localizableLayerIds=this.localizableLayerIds),te.request.collectResourceTiming=this._collectResourceTiming,p.actor&&p.state!=="expired")p.state==="loading"?p.reloadCallback=j:p.request=p.actor.send("reloadTile",te,de.bind(this));else if(p.actor=this._tileWorkers[O]=this._tileWorkers[O]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)p.request=p.actor.send("loadTile",te,de.bind(this),void 0,!0);else{const pe=o.aO.call({deduped:this._deduped},te,(Ce,je)=>{if(Ce||!je)de.call(this,Ce);else{const Me=o.aP(je.responseHeaders);te.data={rawData:je.rawData.slice(0),expires:Me.expires,cacheControl:Me.cacheControl},p.actor&&p.actor.send("loadTile",te,de.bind(this),void 0,!0)}},!0);p.request={cancel:pe}}function de(pe,Ce){return delete p.request,p.aborted?j(null):pe?j(pe):(Ce&&Ce.resourceTiming&&(p.resourceTiming=Ce.resourceTiming),this.map._refreshExpiredTiles&&Ce&&p.setExpiryData(Ce),p.loadVectorData(Ce,this.map.painter),o.aQ(this.dispatcher),j(null,Ce),void(p.reloadCallback&&(this.loadTile(p,p.reloadCallback),p.reloadCallback=null)))}}abortTile(p){p.request&&(p.request.cancel(),delete p.request),p.actor&&p.actor.send("abortTile",{uid:p.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(p,j){p.actor&&p.actor.send("removeTile",{uid:p.uid,type:this.type,source:this.id,scope:this.scope}),p.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class Wv extends o.E{constructor(p,j,L,O){super(),this.id=p,this.dispatcher=L,this.setEventedParent(O),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"},j),Object.assign(this,o.aJ(j,["url","scheme","tileSize"]))}load(p){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const j=this.map.getWorldview();this._tileJSONRequest=Ah(this._options,this.map._requestManager,null,j,(L,O)=>{this._tileJSONRequest=null,this._loaded=!0,L?this.fire(new o.B(L)):O&&(Object.assign(this,O),O.raster_layers&&(this.rasterLayers=O.raster_layers,this.rasterLayerIds=this.rasterLayers.map(q=>q.id)),this.tileBounds=am.fromTileJSON(O),Ue(O.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),p&&p(L)})}loaded(){return this._loaded}onAdd(p){this.map=p,this.load()}reload(){this.cancelTileJSONRequest();const p=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(p))}setTiles(p){return this._options.tiles=p,this.reload(),this}setUrl(p){return this.url=p,this._options.url=p,this.reload(),this}onRemove(p){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(p){return!this.tileBounds||this.tileBounds.contains(p.canonical)}loadTile(p,j){const L=o.o.devicePixelRatio>=2,O=this.map._requestManager.normalizeTileURL(p.tileID.canonical.url(this.tiles,this.scheme),L,this.tileSize);p.request=o.n(this.map._requestManager.transformRequest(O,o.R.Tile),(q,H,Y)=>{if(delete p.request,p.aborted)return p.state="unloaded",j(null);if(q)return p.state="errored",j(q);if(!H)return j(null);const te=o.aP(Y);this.map._refreshExpiredTiles&&p.setExpiryData(te),p.setTexture(H,this.map.painter),p.state="loaded",o.aQ(this.dispatcher),j(null)})}abortTile(p,j){p.request&&(p.request.cancel(),delete p.request),j&&j()}unloadTile(p,j){p.texture&&p.texture instanceof o.T?(p.destroy(!1),p.texture&&p.texture instanceof o.T&&this.map.painter.saveTileTexture(p.texture)):p.destroy(),j&&j()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function m2([E,p],j,L,{scaled:O=!0}={}){const{tileSize:q,buffer:H}=L,{x:Y,y:te,z:de}=j;if(!isFinite(Y)||!isFinite(te)||!isFinite(de))throw new Error("Invalid MRT header");const pe=2**de,Ce=pe*o.aH(E),je=pe*o.aL(p);return function([Me,qe],$e,{scaled:nt=!0}={}){if(!$e)throw new Error("bandView is undefined");const{data:rt,tileSize:pt,buffer:vt,offset:ot,scale:Ut,dimension:Tt}=$e;if(Me<-vt||Me>pt+vt||qe<-vt||qe>pt+vt)throw new Error(`Point (${Me}, ${qe}) out of bounds for tileSize=${pt}, buffer=${vt}`);const $t=(qe+vt)*(pt+2*vt)+(Me+vt);if(new Uint32Array(rt.buffer)[$t]===4294967295)return null;let _t=[];_t=nt?[]:new $e.data.constructor(Tt);for(let St=0;St{if(delete p.request,p.aborted)return p.state="unloaded",j(null);if(Y)return Y.name==="AbortError"?void 0:(p.state="errored",j(Y));if(this.map._refreshExpiredTiles&&te){const pe=o.aP(de);p.setExpiryData(pe)}if(this.partial&&p.state!=="expired")p.state="empty";else if(!this.partial){if(!te)return j(null);p.state="loaded",p._isHeaderLoaded=!0,p._mrt=te}j(null)};p.request=this.partial?p.fetchHeader(void 0,H.bind(this)):p.actor.send("loadTile",q,H.bind(this),void 0,!0)}abortTile(p){p.request&&(p.request.cancel(),delete p.request),p.actor&&p.actor.send("abortTile",{uid:p.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(p,j){const L=p.texturePerLayer;if(p.flushAllQueues(),L.size){p.destroy(!1);for(const O of L.values())this.map.painter.saveTileTexture(O)}else p.destroy()}prepareTile(p,j,L,O){p._isHeaderLoaded&&(p.state!=="empty"&&(p.state="reloading"),p.fetchBandForRender(j,L,O,(q,H)=>{q?(p.state="errored",this.fire(new o.B(q))):H&&(p._isHeaderLoaded=!0,p.setTexturePerLayer(L,H,this.map.painter),p.state="loaded"),this.triggerRepaint(p)}))}getInitialBand(p){if(!this.rasterLayers)return 0;const j=this.rasterLayers.find(({id:q})=>q===p),L=j&&j.fields,O=L&&L.bands&&L.bands;return O?O[0]:0}getTextureDescriptor(p,j,L){if(!p)return;const O=j.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!O)return;let q=null;j instanceof o.aS?q=j.paint.get("raster-array-band"):j instanceof o.aT&&(q=j.paint.get("raster-particle-array-band"));const H=q||this.getInitialBand(O);if(H==null)return;if(!p.textureDescriptorPerLayer.get(j.id))return void this.prepareTile(p,O,j.id,H);if(p.updateNeeded(j.id,H)&&!L)return;const Y=p.textureDescriptorPerLayer.get(j.id);return Object.assign({},Y,{texture:p.texturePerLayer.get(j.id)})}getImages(p,j){const L=new Map;for(const O of p)for(const q of j){const[H,Y]=q.split("/"),te=O.getLayer(H);if(!te||!te.hasBand(Y)||!te.hasDataForBand(Y))continue;const{bytes:de,tileSize:pe,buffer:Ce}=te.getBandView(Y),je=pe+2*Ce,Me={data:new o.q({width:je,height:je},de),pixelRatio:2,sdf:!1,usvg:!1,version:0};L.set(q,Me)}return L}queryRasterArrayValueByBandId(p,j,L){const O=j._mrt;return new Promise(q=>{const H={},Y=new Set;for(const[te,de]of Object.entries(O.layers)){if(L.layerName&&te!==L.layerName)continue;const pe={};H[te]=pe;for(const{bands:Ce}of de.dataIndex)for(const je of Ce)L.bands&&!L.bands.includes(je)||(Y.add(o.F(te,je)),j.fetchBand(te,null,je,Me=>{o.o.frame(()=>{pe[je]=Me?null:m2([p.lng,p.lat],O,de.getBandView(je)),Y.delete(o.F(te,je)),Y.size===0&&q(H)})},!1))}Y.size===0&&q(H)})}_loadTileForQuery(p,j){if(this._loadTileLoaded[p.uid])return void j(null,p._mrt);if(this._loadTilePending[p.uid])return void this._loadTilePending[p.uid].push(j);this._loadTilePending[p.uid]=[j];const L=this.map._requestManager.normalizeTileURL(p.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),O=this.map._requestManager.transformRequest(L,o.R.Tile);p.actor.send("loadTile",{request:O,uid:p.uid,tileID:p.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(q,H,Y)=>{if(q)return this._loadTilePending[p.uid].forEach(te=>te(q,null)),void delete this._loadTilePending[p.uid];if(!H)return this._loadTilePending[p.uid].forEach(te=>te(null,null)),void delete this._loadTilePending[p.uid];if(this.map._refreshExpiredTiles&&H){const te=o.aP(Y);p.setExpiryData(te)}p._mrt=H,p._isHeaderLoaded=!0,p.state="loaded",this._loadTilePending[p.uid].forEach(te=>te(null,H)),this._loadTileLoaded[p.uid]=!0,delete this._loadTilePending[p.uid]},void 0,!0)}queryRasterArrayValueByAllBands(p,j,L){return new Promise((O,q)=>{this._loadTileForQuery(j,(H,Y)=>{H?q(H):O(Y?this.queryRasterArrayValueByBandId(p,j,L):null)})})}queryRasterArrayValue(p,j){const L=o.aU.convert(p),O=this.findLoadedParent(L);return O&&O._mrt?j.bands||!this.partial?this.queryRasterArrayValueByBandId(L,O,j):this.queryRasterArrayValueByAllBands(L,O,j):Promise.resolve(null)}findLoadedParent(p){const j=o.ag.fromLngLat(p,this.map.transform.tileSize),L=this.maxzoom+1,O=1<0&&(Y[new o.aR(E.overscaledZ,O,p.z,L,p.y-1).key]={backfilled:!1},Y[new o.aR(E.overscaledZ,E.wrap,p.z,p.x,p.y-1).key]={backfilled:!1},Y[new o.aR(E.overscaledZ,H,p.z,q,p.y-1).key]={backfilled:!1}),p.y+1{if(this._loaded=!0,this._pendingLoad=null,L)this.fire(new o.B(L));else{const q={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&O&&O.resourceTiming&&O.resourceTiming[this.id]&&(q.resourceTiming=O.resourceTiming[this.id]),E&&(this._partialReload=!0),this.fire(new o.C("data",q)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(E),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const E=o.F(this.id,this.scope);this.map.style.clearSource(E),this._updateWorkerData()}loadTile(E,p){const j=E.actor?"reloadTile":"loadTile";E.actor=this.actor;const L=this.map.style?this.map.style.getLut(this.scope):null,O=L?{image:L.image.clone()}:null,q=this._partialReload,H={type:this.type,uid:E.uid,tileID:E.tileID,tileZoom:E.tileZoom,zoom:E.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:O,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:E.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:q,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};E.request=this.actor.send(j,H,(Y,te)=>q&&!te?(E.state="loaded",p(null)):(delete E.request,E.destroy(!1),E.aborted?p(null):Y?p(Y):(E.loadVectorData(te,this.map.painter,j==="reloadTile"),p(null))),void 0,j==="loadTile")}abortTile(E){E.request&&(E.request.cancel(),delete E.request),E.aborted=!0}unloadTile(E,p){this.actor.send("removeTile",{uid:E.uid,type:this.type,source:this.id,scope:this.scope}),E.destroy()}onRemove(E){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(E,p,j,L){super(E,p,j,L),this.roundZoom=!0,this.type="video",this.options=p}load(){this._loaded=!1;const E=this.options;this.urls=[];for(const p of E.urls)this.urls.push(this.map._requestManager.transformRequest(p,o.R.Source).url);o.aW(this.urls,(p,j)=>{this._loaded=!0,p?this.fire(new o.B(p)):j&&(this.video=j,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(E){if(this.video){const p=this.video.seekable;Ep.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${p.start(0)} and ${p.end(0)}-second mark.`))):this.video.currentTime=E}}getVideo(){return this.video}onAdd(E){this.map||(this.map=E,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 E=this.map.painter.context,p=E.gl;this.texture?this.video.paused||(this.texture.bind(p.LINEAR,p.CLAMP_TO_EDGE),p.texSubImage2D(p.TEXTURE_2D,0,0,0,p.RGBA,p.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(E,this.video,p.RGBA8),this.texture.bind(p.LINEAR,p.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(E)}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(E,p,j,L){super(),this.type="batched-model",this.id=E,this.tileSize=512,this._options=p,this.tiles=this._options.tiles,this.maxzoom=p.maxzoom||19,this.minzoom=p.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=j,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(L)}onAdd(E){this.map=E,this.load()}reload(){this.cancelTileJSONRequest();const E=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(E))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(E){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const p=Array.isArray(this.map._language)?this.map._language.join():this.map._language,j=this.map.getWorldview();this._tileJSONRequest=Ah(this._options,this.map._requestManager,p,j,(L,O)=>{this._tileJSONRequest=null,this._loaded=!0,L?(p&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${p}`),j&&j.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${j}`),this.fire(new o.B(L))):O&&(Object.assign(this,O),O.bounds&&(this.tileBounds=new am(O.bounds,this.minzoom,this.maxzoom)),Ue(O.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"}))),E&&E(L)})}hasTransition(){return!1}hasTile(E){return!this.tileBounds||this.tileBounds.contains(E.canonical)}loaded(){return this._loaded}loadTile(E,p){const j=this.map._requestManager.normalizeTileURL(E.tileID.canonical.url(this.tiles,this.scheme)),L={request:this.map._requestManager.transformRequest(j,o.R.Tile),data:void 0,uid:E.uid,tileID:E.tileID,tileZoom:E.tileZoom,zoom:E.tileID.overscaledZ,tileSize:this.tileSize*E.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:E.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(E.actor&&E.state!=="expired")if(E.state==="loading")E.reloadCallback=p;else{if(E.buckets){const q=Object.values(E.buckets);for(const H of q)H.dirty=!0;return void(E.state="loaded")}E.request=E.actor.send("reloadTile",L,O.bind(this))}else E.actor=this.dispatcher.getActor(),E.request=E.actor.send("loadTile",L,O.bind(this),void 0,!0);function O(q,H){return E.aborted?p(null):q&&q.status!==404?p(q):(this.map._refreshExpiredTiles&&H&&E.setExpiryData(H),E.loadModelData(H,this.map.painter),E.state="loaded",void p(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(E,p,j,L){super(E,p,j,L),p.coordinates?Array.isArray(p.coordinates)&&p.coordinates.length===4&&!p.coordinates.some(O=>!Array.isArray(O)||O.length!==2||O.some(q=>typeof q!="number"))||this.fire(new o.B(new o.V(`sources.${E}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${E}`,null,'missing required property "coordinates"'))),p.animate&&typeof p.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${E}`,null,'optional "animate" property must be a boolean value'))),p.canvas?typeof p.canvas=="string"||p.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${E}`,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.${E}`,null,'missing required property "canvas"'))),this.options=p,this.animate=p.animate===void 0||p.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(E){this.map=E,this.load(),this.canvas&&this.animate&&this.play()}onRemove(E){this.pause()}prepare(){let E=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,E=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,E=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const p=this.map.painter.context;this.texture?!E&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(p,this.canvas,p.gl.RGBA8,{premultiply:!0}),this._prepareData(p)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const E of[this.canvas.width,this.canvas.height])if(isNaN(E)||E<=0)return!0;return!1}},custom:class extends o.E{constructor(E,p,j,L){super(),this.id=E,this.type="custom",this._dataType="raster",this._dispatcher=j,this._implementation=p,this.setEventedParent(L),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 am(this._implementation.bounds,this.minzoom,this.maxzoom));const O=p;O.update=this._update.bind(this),O.clearTiles=this._clearTiles.bind(this),O.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(p,["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(E){this.map=E,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(E),this.load()}onRemove(E){this._implementation.onRemove&&this._implementation.onRemove(E)}hasTile(E){if(this._implementation.hasTile){const{x:p,y:j,z:L}=E.canonical;return this._implementation.hasTile({x:p,y:j,z:L})}return!this.tileBounds||this.tileBounds.contains(E.canonical)}loadTile(E,p){const{x:j,y:L,z:O}=E.tileID.canonical,q=new AbortController,H=Promise.resolve(this._implementation.loadTile({x:j,y:L,z:O},{signal:q.signal})).then((function(Y){return delete E.request,E.aborted?(E.state="unloaded",p(null)):Y===void 0?(E.state="errored",p(null)):Y===null?(this.loadTileData(E,{width:this.tileSize,height:this.tileSize,data:null}),E.state="loaded",p(null)):function(te){return te instanceof ImageData||te instanceof HTMLCanvasElement||te instanceof ImageBitmap||te instanceof HTMLImageElement}(Y)?(this.loadTileData(E,Y),E.state="loaded",void p(null)):(E.state="errored",p(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(Y=>{Y.name!=="AbortError"&&(E.state="errored",p(Y))});H.cancel=()=>q.abort(),E.request=H}loadTileData(E,p){E.setTexture(p,this.map.painter)}unloadTile(E,p){if(E.texture&&E.texture instanceof o.T?(E.destroy(!1),E.texture&&E.texture instanceof o.T&&this.map.painter.saveTileTexture(E.texture)):E.destroy(),this._implementation.unloadTile){const{x:j,y:L,z:O}=E.tileID.canonical;this._implementation.unloadTile({x:j,y:L,z:O})}p&&p()}abortTile(E,p){E.request&&E.request.cancel&&(E.request.cancel(),delete E.request),p&&p()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(E=>({x:E.canonical.x,y:E.canonical.y,z:E.canonical.z}))}_clearTiles(){const E=o.F(this.id,this.scope);this.map.style.clearSource(E)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},Zb=function(E,p,j,L){const O=new Kv[p.type](E,p,j,L);if(O.id!==E)throw new Error(`Expected Source id to be ${E} instead of ${O.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],O),O};function Wy(E,p,j=""){return`${j}:${p.id||""}:${p.layer.id}:${function(L){if("layerId"in L)return`layer:${L.layerId}`;{const{featuresetId:O,importId:q}=L;return`featureset:${O}${q?`:import:${q}`:""}`}}(E.target)}`}function Nu(E,p,j,L=""){if(E.uniqueFeatureID){const O=Wy(E,p,L);if(j.has(O))return!0;j.add(O)}return!1}function Cg(E,p,j,L,O=!1,q=void 0){const H=p.sourceCache.transform,Y=p.sourceCache.tilesIn(E,p.has3DLayers,O);Y.sort(Lm);const te=[];for(const de of Y){const pe=de.tile.queryRenderedFeatures(p,de,j,L,H,O,q);Object.keys(pe).length&&te.push({wrappedTileID:de.tile.tileID.wrapped().key,queryResults:pe})}for(const de in p.layers){const pe=p.layers[de];if(pe.styleLayer){const Ce=pe.styleLayer.queryRenderedFeatures(E,p.sourceCache,L);Object.keys(Ce).length&&te.push({wrappedTileID:0,queryResults:Ce})}}return te.length===0?{}:function(de){const pe={},Ce={};for(const je of de){const Me=je.queryResults,qe=je.wrappedTileID,$e=Ce[qe]=Ce[qe]||{};for(const nt in Me){const rt=Me[nt],pt=$e[nt]=$e[nt]||{},vt=pe[nt]=pe[nt]||[];for(const ot of rt)pt[ot.featureIndex]||(pt[ot.featureIndex]=!0,vt.push(ot))}}return pe}(te)}function lp(E,p,j,L,O,q){const H={},Y=L.queryRenderedSymbols(E),te=[];for(const de of Object.keys(Y).map(Number))te.push(O[de]);te.sort(Lm);for(const de of te){const pe=de.featureIndex.lookupSymbolFeatures(Y[de.bucketInstanceId],de.bucketIndex,de.sourceLayerIndex,p,j,q);for(const Ce in pe){const je=H[Ce]=H[Ce]||[],Me=pe[Ce];Me.sort((qe,$e)=>{const nt=de.featureSortOrder;if(nt){const rt=nt.indexOf(qe.featureIndex);return nt.indexOf($e.featureIndex)-rt}return $e.featureIndex-qe.featureIndex});for(const qe of Me)je.push(qe)}}return H}function f2(E,p){const j=E.getRenderableIds().map(q=>E.getTileByID(q)),L=[],O={};for(let q=0;q{if(q)j(q);else try{const te=L.getHeaderLength(H);if(te>p)return void(this.request=this.fetchHeader(te,j));L.parseHeader(H),this._isHeaderLoaded=!0;let de=0;for(const pe of Object.values(L.layers))de=Math.max(de,pe.dataIndex[pe.dataIndex.length-1].lastByte);H.byteLength>=de&&(this.entireBuffer=H),j(null,this.entireBuffer||H,Y)}catch(te){j(te)}}),this.request}fetchBandForRender(p,j,L,O){this.fetchBand(p,j,L,q=>{if(q)return void O(q);this.updateTextureDescriptor(p,j,L);const H=this.textureDescriptorPerLayer.get(j);O(null,H?H.img:null)})}fetchBand(p,j,L,O,q=!0){const H=this._mrt;if(!this._isHeaderLoaded||!H)return void O(new Error("Tile header is not ready"));const Y=this.actor;if(!Y)return void O(new Error("Can't fetch tile band without an actor"));let te;const de=o.F(String(L),o.F(this.tileID.key,p));let pe=this._taskQueue.get(de);pe?pe.add(O):(pe=new Set,pe.add(O),this._taskQueue.set(de,pe));const Ce=($e,nt)=>{te.complete($e,nt),$e?O($e):(pe.forEach(rt=>rt(null,nt)),this._taskQueue.delete(de))},je=($e,nt)=>{if($e)return O($e);const rt=Y.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:nt,task:te},Ce,void 0,!0);if(j!==null){const pt=this._workQueuePerLayer.get(j)||[];pt.push(()=>{rt&&rt.cancel(),te.cancel()}),this._workQueuePerLayer.has(j)||this._workQueuePerLayer.set(j,pt)}};let Me;try{Me=H.getLayer(p)}catch($e){if(this.state==="reloading")return;throw $e}if(!Me)return void O(new Error(`Unknown sourceLayer "${p}"`));if(Me.hasDataForBand(L))return pe.forEach($e=>$e(null,null)),void this._taskQueue.delete(de);const qe=Me.getDataRange([L]);if(te=H.createDecodingTask(qe),!te||te.tasks.length)if(j!==null&&this.flushQueues(j),this.entireBuffer)je(null,this.entireBuffer.slice(qe.firstByte,qe.lastByte+1));else{const $e=Object.assign({},this.requestParams,{headers:{Range:`bytes=${qe.firstByte}-${qe.lastByte}`}}),nt=o.b1($e,je);if(j!==null){const rt=this._fetchQueuePerLayer.get(j)||[];rt.push(()=>{nt.cancel(),te.cancel()}),this._fetchQueuePerLayer.has(j)||this._fetchQueuePerLayer.set(j,rt)}}}updateNeeded(p,j){return(!this.textureDescriptorPerLayer.get(p)||this.textureDescriptorPerLayer.get(p).band!==j||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(p,j,L){if(!this._mrt)return;const O=this._mrt.getLayer(p);if(!O||!O.hasBand(L)||!O.hasDataForBand(L))return;const{bytes:q,tileSize:H,buffer:Y,offset:te,scale:de}=O.getBandView(L),pe=H+2*Y,Ce=new o.q({width:pe,height:pe},q),je=this.texturePerLayer.get(j);je&&je instanceof o.T&&je.update(Ce,{premultiply:!1}),this.textureDescriptorPerLayer.set(j,{layer:p,band:L,img:Ce,buffer:Y,offset:te,tileSize:H,format:O.pixelFormat,mix:[de,256*de,65536*de,16777216*de]})}destroy(p=!1){if(super.destroy(p),delete this._mrt,!p)for(const j of this.texturePerLayer.values())j&&j instanceof o.T&&j.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 cp{constructor(p,j){this.max=p,this.onRemove=j,this.reset()}reset(){for(const p in this.data)for(const j of this.data[p])j.timeout&&clearTimeout(j.timeout),this.onRemove(j.value);return this.data={},this.order=[],this}add(p,j,L){const O=p.wrapped().key;this.data[O]===void 0&&(this.data[O]=[]);const q={value:j,timeout:void 0};if(L!==void 0&&(q.timeout=setTimeout(()=>{this.remove(p,q)},L)),this.data[O].push(q),this.order.push(O),this.order.length>this.max){const H=this._getAndRemoveByKey(this.order[0]);H&&this.onRemove(H)}return this}has(p){return p.wrapped().key in this.data}getAndRemove(p){return this.has(p)?this._getAndRemoveByKey(p.wrapped().key):null}_getAndRemoveByKey(p){const j=this.data[p].shift();return j.timeout&&clearTimeout(j.timeout),this.data[p].length===0&&delete this.data[p],this.order.splice(this.order.indexOf(p),1),j.value}getByKey(p){const j=this.data[p];return j?j[0].value:null}get(p){return this.has(p)?this.data[p.wrapped().key][0].value:null}remove(p,j){if(!this.has(p))return this;const L=p.wrapped().key,O=j===void 0?0:this.data[L].indexOf(j),q=this.data[L][O];return this.data[L].splice(O,1),q.timeout&&clearTimeout(q.timeout),this.data[L].length===0&&delete this.data[L],this.onRemove(q.value),this.order.splice(this.order.indexOf(L),1),this}setMaxSize(p){for(this.max=p;this.order.length>this.max;){const j=this._getAndRemoveByKey(this.order[0]);j&&this.onRemove(j)}return this}filter(p){const j=[];for(const L in this.data)for(const O of this.data[L])p(O.value)||j.push(O);for(const L of j)this.remove(L.value.tileID,L)}}class au{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(p,j,L){const O=String(j);if(this.stateChanges[p]=this.stateChanges[p]||{},this.stateChanges[p][O]=this.stateChanges[p][O]||{},Object.assign(this.stateChanges[p][O],L),this.deletedStates[p]===null){this.deletedStates[p]={};for(const q in this.state[p])q!==O&&(this.deletedStates[p][q]=null)}else if(this.deletedStates[p]&&this.deletedStates[p][O]===null){this.deletedStates[p][O]={};for(const q in this.state[p][O])L[q]||(this.deletedStates[p][O][q]=null)}else for(const q in L)this.deletedStates[p]&&this.deletedStates[p][O]&&this.deletedStates[p][O][q]===null&&delete this.deletedStates[p][O][q]}removeFeatureState(p,j,L){if(this.deletedStates[p]===null)return;const O=String(j);if(this.deletedStates[p]=this.deletedStates[p]||{},L&&j!==void 0)this.deletedStates[p][O]!==null&&(this.deletedStates[p][O]=this.deletedStates[p][O]||{},this.deletedStates[p][O][L]=null);else if(j!==void 0)if(this.stateChanges[p]&&this.stateChanges[p][O])for(L in this.deletedStates[p][O]={},this.stateChanges[p][O])this.deletedStates[p][O][L]=null;else this.deletedStates[p][O]=null;else this.deletedStates[p]=null}getState(p,j){const L=this.state[p]||{},O=this.stateChanges[p]||{},q=this.deletedStates[p];if(q===null)return{};if(j!==void 0){const Y=String(j),te=Object.assign({},L[Y],O[Y]);if(q){const de=q[j];if(de===null)return{};for(const pe in de)delete te[pe]}return te}const H=Object.assign({},L,O);if(q)for(const Y in q)delete H[Y];return H}initializeTileState(p,j){p.refreshFeatureState(j)}coalesceChanges(p,j){const L={};for(const O in this.stateChanges){this.state[O]=this.state[O]||{};const q={};for(const H in this.stateChanges[O])this.state[O][H]||(this.state[O][H]={}),Object.assign(this.state[O][H],this.stateChanges[O][H]),q[H]=this.state[O][H];L[O]=q}for(const O in this.deletedStates){this.state[O]=this.state[O]||{};const q={};if(this.deletedStates[O]===null)for(const H in this.state[O])q[H]={},this.state[O][H]={};else for(const H in this.deletedStates[O]){if(this.deletedStates[O][H]===null)this.state[O][H]={};else if(this.state[O][H])for(const Y of Object.keys(this.deletedStates[O][H]))delete this.state[O][H][Y];q[H]=this.state[O][H]}L[O]=L[O]||{},Object.assign(L[O],q)}if(this.stateChanges={},this.deletedStates={},Object.keys(L).length!==0)for(const O in p)p[O].refreshFeatureState(j,L)}}class ku extends o.E{constructor(p,j,L){super(),this.id=p,this._renderSourceType=L,this._maxzoomOverride=null,j.on("data",O=>{O.dataType==="source"&&O.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&O.dataType==="source"&&O.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),j.on("error",()=>{this._sourceErrored=!0}),this._source=j,this._tiles={},this._cache=new cp(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=j.minTileCacheSize,this._maxTileCacheSize=j.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new au,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(p){this.map=p,this._minTileCacheSize=this._minTileCacheSize===void 0&&p?p._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&p?p._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const p in this._tiles)if(!this._tiles[p].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const p=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,p&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(p){this._maxzoomOverride=p}_loadTile(p,j){return p.renderSourceType=this._renderSourceType,p.isExtraShadowCaster=this._shadowCasterTiles[p.tileID.key],this._source.loadTile(p,j)}_unloadTile(p){if(this._source.unloadTile)return this._source.unloadTile(p)}_abortTile(p){if(this._source.abortTile)return this._source.abortTile(p)}serialize(){return this._source.serialize()}prepare(p){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const j in this._tiles){const L=this._tiles[j];L.upload(p,this.map?this.map.painter:void 0),L.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(p=>p.tileID).sort(Yv).map(p=>p.key)}getRenderableIds(p,j){const L=[];for(const O in this._tiles)this._isIdRenderable(+O,p,j)&&L.push(this._tiles[O]);return p?L.sort((O,q)=>{const H=O.tileID,Y=q.tileID,te=new o.P(H.canonical.x,H.canonical.y)._rotate(this.transform.angle),de=new o.P(Y.canonical.x,Y.canonical.y)._rotate(this.transform.angle);return H.overscaledZ-Y.overscaledZ||de.y-te.y||de.x-te.x}).map(O=>O.tileID.key):L.map(O=>O.tileID).sort(Yv).map(O=>O.key)}hasRenderableParent(p){const j=this.findLoadedParent(p,0);return!!j&&this._isIdRenderable(j.tileID.key)}_isIdRenderable(p,j,L){return this._tiles[p]&&this._tiles[p].hasData()&&!this._coveredTiles[p]&&(j||!this._tiles[p].holdingForFade())&&(L||!this._shadowCasterTiles[p])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const p in this._tiles)this._tiles[p].state!=="errored"&&this._reloadTile(+p,"reloading")}}_reloadTile(p,j){const L=this._tiles[p];L&&(L.state!=="loading"&&(L.state=j),this._loadTile(L,this._tileLoaded.bind(this,L,p,j)))}_tileLoaded(p,j,L,O,q){if(O){if(p.state="errored",o.b2(O)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:p})),!(p.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const Y=this.map.painter.terrain;this.update(this.transform,Y.getScaledDemTileSize(),!0),Y.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(O,{tile:p}));return}p.timeAdded=o.o.now(),L==="expired"&&(p.refreshedUponExpiration=!0),this._setTileReloadTimer(j,p),this._source.type==="raster-dem"&&p.dem&&this._backfillDEM(p),this._state.initializeTileState(p,this.map?this.map.painter:null);let H=new Map;q&&q.responseHeaders&&(H=q.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:p,coord:p.tileID,sourceCacheId:this.id,responseHeaders:H}))}_hasTunnelGeometry(){for(const p in this._tiles){const j=this._tiles[p];if(j&&j.hasTunnelGeometry)return!0}return!1}_backfillDEM(p){const j=this.getRenderableIds();for(let O=0;O1||(Math.abs(H)>1&&(Math.abs(H+te)===1?H+=te:Math.abs(H-te)===1&&(H-=te)),q.dem&&O.dem&&(O.dem.backfillBorder(q.dem,H,Y),O.neighboringTiles&&O.neighboringTiles[de]&&(O.neighboringTiles[de].backfilled=!0)))}}getTile(p){return this.getTileByID(p.key)}getTileByID(p){return this._tiles[p]}_retainLoadedChildren(p,j,L,O){for(const q in this._tiles){let H=this._tiles[q];if(O[q]||!H.hasData()||H.tileID.overscaledZ<=j||H.tileID.overscaledZ>L)continue;let Y=H.tileID;for(;H&&H.tileID.overscaledZ>j+1;){const de=H.tileID.scaledTo(H.tileID.overscaledZ-1);H=this._tiles[de.key],H&&H.hasData()&&(Y=de)}let te=Y;for(;te.overscaledZ>j;)if(te=te.scaledTo(te.overscaledZ-1),p[te.key]){O[Y.key]=Y;break}}}findLoadedParent(p,j){if(p.key in this._loadedParentTiles){const L=this._loadedParentTiles[p.key];return L&&L.tileID.overscaledZ>=j?L:null}for(let L=p.overscaledZ-1;L>=j;L--){const O=p.scaledTo(L),q=this._getLoadedTile(O);if(q)return q}}_getLoadedTile(p){const j=this._tiles[p.key];return j&&j.hasData()?j:this._cache.getByKey(this._source.reparseOverscaled?p.wrapped().key:p.canonical.key)}updateCacheSize(p,j){j=j||this._source.tileSize;const L=Math.ceil(p.width/j)+1,O=Math.ceil(p.height/j)+1,q=Math.floor(L*O*5),H=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,q):q,Y=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,H):H;this._cache.setMaxSize(Y)}handleWrapJump(p){const j=Math.round((p-(this._prevLng===void 0?p:this._prevLng))/360);if(this._prevLng=p,j){const L={};for(const O in this._tiles){const q=this._tiles[O];q.tileID=q.tileID.unwrapTo(q.tileID.wrap+j),L[q.tileID.key]=q}this._tiles=L;for(const O in this._timers)clearTimeout(this._timers[O]),delete this._timers[O];for(const O in this._tiles)this._setTileReloadTimer(+O,this._tiles[O])}}update(p,j,L,O,q){if(this.transform=p,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!L)return;this.updateCacheSize(p,j),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const H=this._source.type==="batched-model";let Y,te=this._source.maxzoom;this._maxzoomOverride!==null&&(te=Math.min(te,this._maxzoomOverride));const de=this.map&&this.map.painter?this.map.painter._terrain:null;if(de&&de.sourceCache===this&&de.attenuationRange()){const Me=de.attenuationRange()[0],qe=Math.floor(Me)-Math.log2(de.getDemUpscale());te>qe&&(te=qe)}const pe=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)Y=p.getVisibleUnwrappedCoordinates(this._source.tileID).map(Me=>new o.aR(Me.canonical.z,Me.wrap,Me.canonical.z,Me.canonical.x,Me.canonical.y));else if(this.tileCoverLift!==0){const Me=p.clone();Me.tileCoverLift=this.tileCoverLift,Y=Me.coveringTiles({tileSize:j||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:te,roundZoom:this._source.roundZoom&&!L,reparseOverscaled:pe,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:H}),this._source.minzoom<=1&&p.projection.name==="globe"&&(Y.push(new o.aR(1,0,1,0,0)),Y.push(new o.aR(1,0,1,1,0)),Y.push(new o.aR(1,0,1,0,1)),Y.push(new o.aR(1,0,1,1,1)))}else if(Y=p.coveringTiles({tileSize:j||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:te,roundZoom:this._source.roundZoom&&!L,reparseOverscaled:pe,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:H}),this._source.hasTile){const Me=this._source.hasTile.bind(this._source);Y=Y.filter(qe=>Me(qe))}}else Y=[];if(Y.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const Me=p.coveringZoomLevel({tileSize:j||this._source.tileSize,roundZoom:this._source.roundZoom&&!L}),qe=Math.min(Me,te);if(H){const $e=p.extendTileCover(Y,qe);for(const nt of $e)Y.push(nt)}else if(q){const $e=this.transform.getFrustum(qe),nt=p.extendTileCoverToNearPlane(Y,$e,qe);for(const rt of nt)Y.push(rt);if(qe>=18&&this._hasTunnelGeometry()){const rt=p.extendTileCoverForTunnels(Y,$e,qe,20);for(const pt of rt)Y.push(pt)}}else if(this.castsShadows&&O){const $e=p.extendTileCover(Y,qe,O,16);for(const nt of $e)this._shadowCasterTiles[nt.key]=!0,Y.push(nt)}}const Ce=this._updateRetainedTiles(Y);if(this._supportsFading&&Y.length!==0){const Me={},qe={},$e=o.o.now(),nt=Object.keys(Ce);for(const pt of nt){const vt=Ce[pt],ot=this._tiles[pt];if(!ot||ot.fadeEndTime!==void 0&&ot.fadeEndTime<=$e)continue;const Ut=this.findLoadedParent(vt,Math.max(vt.overscaledZ-ku.maxOverzooming,this._source.minzoom));Ut&&(this._addTile(Ut.tileID),Me[Ut.tileID.key]=Ut.tileID),qe[pt]=vt}const rt=Y[Y.length-1].overscaledZ;for(const pt in this._tiles){const vt=this._tiles[pt];if(Ce[pt]||!vt.hasData())continue;let ot=vt.tileID;for(;ot.overscaledZ>rt;){ot=ot.scaledTo(ot.overscaledZ-1);const Ut=this._tiles[ot.key];if(Ut&&Ut.hasData()&&qe[ot.key]){Ce[pt]=vt.tileID;break}}}for(const pt in Me)Ce[pt]||(this._coveredTiles[pt]=!0,Ce[pt]=Me[pt])}for(const Me in Ce)this._tiles[Me].clearFadeHold();const je=o.b3(this._tiles,Ce);for(const Me of je){const qe=this._tiles[Me];qe.hasSymbolBuckets&&!qe.holdingForFade()?qe.setHoldDuration(this.map._fadeDuration):qe.hasSymbolBuckets&&!qe.symbolFadeFinished()||this._removeTile(+Me)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const p in this._tiles)this._tiles[p].holdingForFade()&&this._removeTile(+p)}_updateRetainedTiles(p){const j={};if(p.length===0)return j;const L={},O=p.reduce((de,pe)=>Math.min(de,pe.overscaledZ),1/0),q=p[0].overscaledZ,H=Math.max(q-ku.maxOverzooming,this._source.minzoom),Y=Math.max(q+ku.maxUnderzooming,this._source.minzoom),te={};for(const de of p){const pe=this._addTile(de);j[de.key]=de,pe.hasData()||O=this._source.maxzoom){const je=de.children(this._source.maxzoom)[0],Me=this.getTile(je);if(Me&&Me.hasData()){j[je.key]=je;continue}}else{const je=de.children(this._source.maxzoom);if(j[je[0].key]&&j[je[1].key]&&j[je[2].key]&&j[je[3].key])continue}let Ce=pe.wasRequested();for(let je=de.overscaledZ-1;je>=H;--je){const Me=de.scaledTo(je);if(L[Me.key]||(L[Me.key]=!0,pe=this.getTile(Me),!pe&&Ce&&(pe=this._addTile(Me)),pe&&(j[Me.key]=Me,Ce=pe.wasRequested(),pe.hasData())))break}}return j}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const p in this._tiles){const j=[];let L,O=this._tiles[p].tileID;for(;O.overscaledZ>0;){if(O.key in this._loadedParentTiles){L=this._loadedParentTiles[O.key];break}j.push(O.key);const q=O.scaledTo(O.overscaledZ-1);if(L=this._getLoadedTile(q),L)break;O=q}for(const q of j)this._loadedParentTiles[q]=L}}_addTile(p){let j=this._tiles[p.key];if(j)return j.isExtraShadowCaster!==!0||this._shadowCasterTiles[p.key]||this._reloadTile(p.key,"reloading"),j;j=this._cache.getAndRemove(p),j&&(this._setTileReloadTimer(p.key,j),j.tileID=p,this._state.initializeTileState(j,this.map?this.map.painter:null),this._cacheTimers[p.key]&&(clearTimeout(this._cacheTimers[p.key]),delete this._cacheTimers[p.key],this._setTileReloadTimer(p.key,j)));const L=!!j;if(!L){const O=this.map?this.map.painter:null,q=this._source.tileSize*p.overscaleFactor();j=this._source.type==="raster-array"?new Mh(p,q,this.transform.tileZoom,O,this._isRaster):new o.b0(p,q,this.transform.tileZoom,O,this._isRaster,this._source.worldview),this._loadTile(j,this._tileLoaded.bind(this,j,p.key,j.state))}return j.uses++,this._tiles[p.key]=j,L||this._source.fire(new o.C("dataloading",{tile:j,coord:j.tileID,dataType:"source"})),j}_setTileReloadTimer(p,j){p in this._timers&&(clearTimeout(this._timers[p]),delete this._timers[p]);const L=j.getExpiryTimeout();L&&(this._timers[p]=setTimeout(()=>{this._reloadTile(p,"expired"),delete this._timers[p]},L))}_removeTile(p){const j=this._tiles[p];j&&(j.uses--,delete this._tiles[p],this._timers[p]&&(clearTimeout(this._timers[p]),delete this._timers[p]),j.uses>0||(j.hasData()&&j.state!=="reloading"||j.state==="empty"?this._cache.add(j.tileID,j,j.getExpiryTimeout()):(j.aborted=!0,this._abortTile(j),this._unloadTile(j))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const p in this._tiles)this._removeTile(+p);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(p,j,L){const O=[],q=this.transform;if(!q)return O;const H=q.projection.name==="globe",Y=o.aH(q.center.lng);for(const te in this._tiles){const de=this._tiles[te];if(L&&de.clearQueryDebugViz(),de.holdingForFade())continue;let pe;if(H){const Ce=de.tileID.canonical;if(Ce.z===0){const je=[Math.abs(o.aC(Y,...zd(Ce,-1))-Y),Math.abs(o.aC(Y,...zd(Ce,1))-Y)];pe=[0,2*je.indexOf(Math.min(...je))-1]}else{const je=[Math.abs(o.aC(Y,...zd(Ce,-1))-Y),Math.abs(o.aC(Y,...zd(Ce,0))-Y),Math.abs(o.aC(Y,...zd(Ce,1))-Y)];pe=[je.indexOf(Math.min(...je))-1]}}else pe=[0];for(const Ce of pe){const je=p.containsTile(de,q,j,Ce);je&&O.push(je)}}return O}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(p){return this._getRenderableCoordinates(p)}_getRenderableCoordinates(p,j){const L=this.getRenderableIds(p,j).map(q=>this._tiles[q].tileID),O=this.transform.projection.name==="globe";for(const q of L)q.projMatrix=this.transform.calculateProjMatrix(q.toUnwrapped()),q.expandedProjMatrix=O?this.transform.calculateProjMatrix(q.toUnwrapped(),!1,!0):q.projMatrix;return L}sortCoordinatesByDistance(p){const j=p.slice(),L=this.transform._camera.position,O=this.transform._camera.forward(),q={};for(const H of j){const Y=1/(1<q[H.key]-q[Y.key]),j}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const p=o.o.now();for(const j in this._tiles){const L=this._tiles[j];if(L.fadeEndTime!==void 0&&L.fadeEndTime>=p)return!0}}return!1}setFeatureState(p,j,L){this._state.updateState(p=p||"_geojsonTileLayer",j,L)}removeFeatureState(p,j,L){this._state.removeFeatureState(p=p||"_geojsonTileLayer",j,L)}getFeatureState(p,j){return this._state.getState(p=p||"_geojsonTileLayer",j)}setDependencies(p,j,L){const O=this._tiles[p];O&&O.setDependencies(j,L)}reloadTilesForDependencies(p,j){for(const L in this._tiles)this._tiles[L].hasDependency(p,j)&&this._reloadTile(+L,"reloading");this._cache.filter(L=>!L.hasDependency(p,j))}_preloadTiles(p,j){if(!this._sourceLoaded){const te=()=>{this._sourceLoaded&&(this._source.off("data",te),this._preloadTiles(p,j))};return void this._source.on("data",te)}const L=new Map,O=Array.isArray(p)?p:[p],q=this.map.painter.terrain,H=this.usedForTerrain&&q?q.getScaledDemTileSize():this._source.tileSize;for(const te of O){const de=te.coveringTiles({tileSize:H,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const pe of de)L.set(pe.key,pe);this.usedForTerrain&&te.updateElevation(!1)}const Y=Array.from(L.values());o.t(Y,(te,de)=>{const pe=new o.b0(te,this._source.tileSize*te.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(pe,Ce=>{this._source.type==="raster-dem"&&pe.dem&&this._backfillDEM(pe),de(Ce,pe)})},j)}}function Yv(E,p){const j=Math.abs(2*E.wrap)-+(E.wrap<0),L=Math.abs(2*p.wrap)-+(p.wrap<0);return E.overscaledZ-p.overscaledZ||L-j||p.canonical.y-E.canonical.y||p.canonical.x-E.canonical.x}function zd(E,p){const j=1<0:L.type==="building"?O=!L.isHidden(p)&&L.paint.get("building-opacity")>0:L.type==="model"&&(O=!L.isHidden(p)&&L.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!O&&j.visible,j.visible=O}}updateZOffset(p,j){this.currentBuildingBuckets=[];for(const O of this.layers){const q=O.layer,H=this.style.getLayerSourceCache(q);let Y=1;q.type==="fill-extrusion"?Y=O.visible?q.paint.get("fill-extrusion-vertical-scale"):0:q.type==="building"&&(Y=O.visible?q.paint.get("building-vertical-scale"):0);let te=H?H.getTile(j):null;if(!te&&H)for(const de in H._tiles){const pe=H._tiles[de];if(j.canonical.isChildOf(pe.tileID.canonical)){te=pe;break}}this.currentBuildingBuckets.push({bucket:te?te.getBucket(q):null,tileID:te?te.tileID:j,verticalScale:Y})}p.hasAnyZOffset=!1;let L=!1;for(let O=0;O{L in p&&(j[L]=p[L])}),j}function Tg(E){E=E.slice();const p=Object.create(null);for(const j of E)p[j.id]=j;for(let j=0;j0?(O-H)/Y:0;return this.points[q].mult(1-te).add(this.points[j].mult(te))}}class x2{constructor(p,j,L){const O=this.boxCells=[],q=this.circleCells=[];this.xCellCount=Math.ceil(p/L),this.yCellCount=Math.ceil(j/L);for(let H=0;Hthis.width||O<0||j>this.height)return!q&&[];const Y=[];if(p<=0&&j<=0&&this.width<=L&&this.height<=O){if(q)return!0;for(let te=0;te0:Y}_queryCircle(p,j,L,O,q){const H=p-L,Y=p+L,te=j-L,de=j+L;if(Y<0||H>this.width||de<0||te>this.height)return!O&&[];const pe=[];return this._forEachCell(H,te,Y,de,this._queryCellCircle,pe,{hitTest:O,circle:{x:p,y:j,radius:L},seenUids:{box:{},circle:{}}},q),O?pe.length>0:pe}query(p,j,L,O,q){return this._query(p,j,L,O,!1,q)}hitTest(p,j,L,O,q){return this._query(p,j,L,O,!0,q)}hitTestCircle(p,j,L,O){return this._queryCircle(p,j,L,!0,O)}_queryCell(p,j,L,O,q,H,Y,te){const de=Y.seenUids,pe=this.boxCells[q];if(pe!==null){const je=this.bboxes;for(const Me of pe)if(!de.box[Me]){de.box[Me]=!0;const qe=4*Me;if(p<=je[qe+2]&&j<=je[qe+3]&&L>=je[qe+0]&&O>=je[qe+1]&&(!te||te(this.boxKeys[Me]))){if(Y.hitTest)return H.push(!0),!0;H.push({key:this.boxKeys[Me],x1:je[qe],y1:je[qe+1],x2:je[qe+2],y2:je[qe+3]})}}}const Ce=this.circleCells[q];if(Ce!==null){const je=this.circles;for(const Me of Ce)if(!de.circle[Me]){de.circle[Me]=!0;const qe=3*Me;if(this._circleAndRectCollide(je[qe],je[qe+1],je[qe+2],p,j,L,O)&&(!te||te(this.circleKeys[Me]))){if(Y.hitTest)return H.push(!0),!0;{const $e=je[qe],nt=je[qe+1],rt=je[qe+2];H.push({key:this.circleKeys[Me],x1:$e-rt,y1:nt-rt,x2:$e+rt,y2:nt+rt})}}}}}_queryCellCircle(p,j,L,O,q,H,Y,te){const de=Y.circle,pe=Y.seenUids,Ce=this.boxCells[q];if(Ce!==null){const Me=this.bboxes;for(const qe of Ce)if(!pe.box[qe]){pe.box[qe]=!0;const $e=4*qe;if(this._circleAndRectCollide(de.x,de.y,de.radius,Me[$e+0],Me[$e+1],Me[$e+2],Me[$e+3])&&(!te||te(this.boxKeys[qe])))return H.push(!0),!0}}const je=this.circleCells[q];if(je!==null){const Me=this.circles;for(const qe of je)if(!pe.circle[qe]){pe.circle[qe]=!0;const $e=3*qe;if(this._circlesCollide(Me[$e],Me[$e+1],Me[$e+2],de.x,de.y,de.radius)&&(!te||te(this.circleKeys[qe])))return H.push(!0),!0}}}_forEachCell(p,j,L,O,q,H,Y,te){const de=this._convertToXCellCoord(p),pe=this._convertToYCellCoord(j),Ce=this._convertToXCellCoord(L),je=this._convertToYCellCoord(O);for(let Me=de;Me<=Ce;Me++)for(let qe=pe;qe<=je;qe++)if(q.call(this,p,j,L,O,this.xCellCount*qe+Me,H,Y,te))return}_convertToXCellCoord(p){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(p*this.xScale)))}_convertToYCellCoord(p){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(p*this.yScale)))}_circlesCollide(p,j,L,O,q,H){const Y=O-p,te=q-j,de=L+H;return de*de>Y*Y+te*te}_circleAndRectCollide(p,j,L,O,q,H,Y){const te=(H-O)/2,de=Math.abs(p-(O+te));if(de>te+L)return!1;const pe=(Y-q)/2,Ce=Math.abs(j-(q+pe));if(Ce>pe+L)return!1;if(de<=te||Ce<=pe)return!0;const je=de-te,Me=Ce-pe;return je*je+Me*Me<=L*L}}const PL=Math.tan(85*Math.PI/180);function yx(E,p,j,L,O,q,H){const Y=o.bb();if(j)if(q.name==="globe"){const te=o.bc(O,p);o.aD(Y,Y,te)}else{const te=o.bd([],H);Y[0]=te[0],Y[1]=te[1],Y[4]=te[2],Y[5]=te[3],L||o.ba(Y,Y,O.angle)}else o.aD(Y,O.labelPlaneMatrix,E);return Y}function Pm(E,p,j,L,O,q,H){const Y=yx(E,p,j,L,O,q,H);return q.name==="globe"&&j||(Y[2]=Y[6]=Y[10]=Y[14]=0),Y}function Zy(E,p,j,L,O,q,H){if(j){if(q.name==="globe"){const Y=yx(E,p,j,L,O,q,H);return o.b7(Y,Y),o.aD(Y,E,Y),Y}{const Y=o.b8(E),te=o.b9([]);return te[0]=H[0],te[1]=H[1],te[4]=H[2],te[5]=H[3],o.aD(Y,Y,te),L||o.ba(Y,Y,-O.angle),Y}}return O.glCoordMatrix}function Ih(E,p,j,L){const O=[E,p,j,1];j?o.aE(O,O,L):hn(O,O,L);const q=O[3];return O[0]/=q,O[1]/=q,O[2]/=q,O}function Jb(E,p){return Math.min(.5+E/p*.5,1.5)}function Qv(E,p){const j=E[0]/E[3],L=E[1]/E[3];return j>=-p[0]&&j<=p[0]&&L>=-p[1]&&L<=p[1]}function kt(E,p,j,L,O,q,H,Y,te,de,pe=1){const Ce=j.transform,je=L?E.textSizeData:E.iconSizeData,Me=o.bj(je,j.transform.zoom,pe),qe=Ce.projection.name==="globe",$e=[256/j.width*2+1,256/j.height*2+1],nt=L?E.text.dynamicLayoutVertexArray:E.icon.dynamicLayoutVertexArray;nt.clear();let rt=null;qe&&(rt=L?E.text.globeExtVertexArray:E.icon.globeExtVertexArray);const pt=E.lineVertexArray,vt=L?E.text.placedSymbolArray:E.icon.placedSymbolArray,ot=j.transform.width/j.transform.height;let Ut,Tt=!1;for(let $t=0;$tMath.abs(j)?{useVertical:!0}:E===o.bk.vertical?L>0?{needsFlipping:!0}:null:p!==0&&function(O,q){return O===0||Math.abs(q/O)>PL}(j,L)?p===1?{needsFlipping:!0}:null:j<0?{needsFlipping:!0}:null}function An(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt,pt,vt){const ot=p/24,Ut=E.lineOffsetX*ot,Tt=E.lineOffsetY*ot,{lineStartIndex:$t,glyphStartIndex:_t,numGlyphs:St,segment:Rt,writingMode:Zt,flipState:qt}=E,xs=$t+E.lineLength,as=Os=>{if(pe){const[us,vs,ks]=Os.up,cr=de.length;o.bm(pe,cr+0,us,vs,ks),o.bm(pe,cr+1,us,vs,ks),o.bm(pe,cr+2,us,vs,ks),o.bm(pe,cr+3,us,vs,ks)}const[Hs,Qt,Ht]=Os.point;o.bn(de,Hs,Qt,Ht,Os.angle)};if(St>1){const Os=Gs(ot,Y,Ut,Tt,j,Ce,je,E,te,q,Me,$e,!1,nt,rt,pt,vt);if(!Os)return{notEnoughRoom:!0};if(L&&!j){let[Hs,Qt,Ht]=Os.first.point,[us,vs,ks]=Os.last.point;[Hs,Qt]=Ih(Hs,Qt,Ht,H),[us,vs]=Ih(us,vs,ks,H);const cr=mr(Zt,qt,(us-Hs)*qe,vs-Qt);if(E.flipState=cr&&cr.needsFlipping?1:2,cr)return cr}as(Os.first);for(let Hs=_t+1;Hs<_t+St-1;Hs++){const Qt=Ia(ot*Y.getoffsetX(Hs),Ut,Tt,j,Ce,je,Rt,$t,xs,te,q,Me,$e,!1,!1,nt,rt,pt,vt);if(!Qt)return de.length-=4*(Hs-_t),{notEnoughRoom:!0};as(Qt)}as(Os.last)}else{if(L&&!j){const Hs=Ih(je.x,je.y,0,O),Qt=$t+Rt+1,Ht=new o.P(te.getx(Qt),te.gety(Qt)),us=Ih(Ht.x,Ht.y,0,O),vs=us[3]>0?us:Oa(je,Ht,Hs,1,O,void 0,nt,rt.canonical),ks=mr(Zt,qt,(vs[0]-Hs[0])*qe,vs[1]-Hs[1]);if(E.flipState=ks&&ks.needsFlipping?1:2,ks)return ks}const Os=Ia(ot*Y.getoffsetX(_t),Ut,Tt,j,Ce,je,Rt,$t,xs,te,q,Me,$e,!1,!1,nt,rt,pt,vt);if(!Os)return{notEnoughRoom:!0};as(Os)}return{}}function wr(E,p,j,L,O){const{x:q,y:H,z:Y}=L.projectTilePoint(E.x,E.y,p);if(!O)return Ih(q,H,Y,j);const[te,de,pe]=O.getElevation(E,O.elevation,O.elevationFeature);return Ih(q+te,H+de,Y+pe,j)}function Oa(E,p,j,L,O,q,H,Y){const te=wr(E.sub(p)._unit()._add(E),Y,O,H,q);return o.ax(te,j,te),o.ay(te,te),o.bg(te,j,te,L)}function Ia(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt,pt){const vt=L?E-p:E+p;let ot=vt>0?1:-1,Ut=0;L&&(ot*=-1,Ut=Math.PI),ot<0&&(Ut+=Math.PI);let Tt=Y+H+(ot>0?0:1)|0,$t=O,_t=O,St=0,Rt=0;const Zt=Math.abs(vt),qt=[],xs=[];let as=q,Os=as,Hs=o.be([]);const Qt=()=>Oa(Os,as,_t,Zt-St+1,pe,je,$e,nt.canonical);for(;St+Rt<=Zt;){if(Tt+=ot,Tt=te)return null;if(_t=$t,Os=as,qt.push(_t),Me&&xs.push(Os),as=new o.P(de.getx(Tt),de.gety(Tt)),$t=Ce[Tt],!$t){const Kr=wr(as,nt.canonical,pe,$e,je);$t=Kr[3]>0?Ce[Tt]=Kr:Qt()}St+=Rt;const Us=o.ax([],$t,_t),Br=o.bf(_t,$t);if(j&&Br>0&&Rt>0&&o.bi(Hs,Us)/(Rt*Br)0,vt),$t=de*Tt.perspectiveRatio,_t=(L.x1*j+Y.x-L.padding)*$t+Tt.point.x,St=(L.y1*j+Y.y-L.padding)*$t+Tt.point.y,Rt=(L.x2*j+Y.x+L.padding)*$t+Tt.point.x,Zt=(L.y2*j+Y.y+L.padding)*$t+Tt.point.y,qt=Tt.perspectiveRatio<=.55||Tt.occluded;return!this.isInsideGrid(_t,St,Rt,Zt)||!te&&this.grid.hitTest(_t,St,Rt,Zt,Ce)||qt?{box:[],offscreen:!1,occluded:Tt.occluded}:{box:[_t,St,Rt,Zt],offscreen:this.isOffscreen(_t,St,Rt,Zt),occluded:!1}}placeCollisionCircles(p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt){const rt=[],pt=this.transform.elevation,vt=p.getProjection(),ot=p.elevationType==="road",Ut=!!pt||ot,Tt=o.bu.getAtTileOffsetFunc(nt,this.transform.center.lat,this.transform.worldSize,vt),$t=new o.P(L.tileAnchorX,L.tileAnchorY),_t=new o.P(L.tileAnchorX,L.tileAnchorY);let{x:St,y:Rt,z:Zt}=vt.projectTilePoint(_t.x,_t.y,nt.canonical),qt=null;if(Ut){const Br=ot?p.getElevationFeatureForText(O):null;qt={getElevation:Tt,elevation:pt,elevationFeature:Br};const[Kr,Er,Fr]=Tt($t,pt,Br);St+=Kr,Rt+=Er,Zt+=Fr}const xs=vt.name==="globe",as=this.projectAndGetPerspectiveRatio(te,St,Rt,Zt,nt,xs||!!pt||this.transform.pitch>0,vt),{perspectiveRatio:Os}=as,Hs=(je?Y/Os:Y*Os)/o.by,Qt=Ih(St,Rt,Zt,de),Ht=L.lineOffsetX*Hs,us=L.lineOffsetY*Hs,vs=o.ap(p.layers[0].layout.get("text-max-angle")),ks=Math.cos(vs),cr=as.signedDistanceFromCamera>0?Gs(Hs,H,Ht,us,ot&&L.flipState===1,Qt,_t,L,q,de,{},Ut&&!je?qt:null,je&&Ut,vt,nt,je,ks):null;let Js=!1,er=!1,Us=!0;if(cr&&!as.occluded){const Br=.5*qe*Os+$e,Kr=new o.P(-100,-100),Er=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Fr=new Xv,{first:_n,last:Fn}=cr,Pn=_n.path.length;let oa=[];for(let Dn=Pn-1;Dn>=1;Dn--)oa.push(_n.path[Dn]);for(let Dn=1;Dn(Ut&&!xs&&(Ti=Tt(yoDn[3]<=0)&&(oa=[]));let la=[];if(oa.length>0){let Dn=1/0,Wa=-1/0,Ti=1/0,yo=-1/0;for(const zi of oa)Dn=Math.min(Dn,zi[0]),Ti=Math.min(Ti,zi[1]),Wa=Math.max(Wa,zi[0]),yo=Math.max(yo,zi[1]);Wa>=Kr.x&&Dn<=Er.x&&yo>=Kr.y&&Ti<=Er.y&&(la=[oa.map(zi=>new o.P(zi[0],zi[1]))],(DnEr.x||TiEr.y)&&(la=o.bv(la,Kr.x,Kr.y,Er.x,Er.y)))}for(const Dn of la){Fr.reset(Dn,.25*Br);let Wa=0;Wa=Fr.length<=.5*Br?1:Math.ceil(Fr.paddedLength/pn)+1;for(let Ti=0;Ti0?(o.aE(te,te,p),this.fogState&&q&&Y.name!=="globe"&&(de=function(je,Me,qe,$e,nt,rt){const pt=rt.calculateFogTileMatrix(nt),vt=[Me,qe,$e];return o.ah(vt,vt,pt),fa(je,o.ai(vt),rt.pitch,rt._fov)}(this.fogState,j,L,O,q.toUnwrapped(),this.transform)>.9)):hn(te,te,p);const pe=te[3];return{point:new o.P((te[0]/pe+1)/2*this.transform.width+gd,(-te[1]/pe+1)/2*this.transform.height+gd),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(Y)/pe*.5,1.5),signedDistanceFromCamera:pe,occluded:H&&te[2]>pe||de}}isOffscreen(p,j,L,O){return L=this.screenRightBoundary||Othis.screenBottomBoundary}isInsideGrid(p,j,L,O){return L>=0&&p=0&&jL.collisionGroupID===j}}return this.collisionGroups[p]}}function rh(E,p,j,L,O){const{horizontalAlign:q,verticalAlign:H}=o.bF(E),Y=-(q-.5)*p,te=-(H-.5)*j,de=o.bG(E,L);return new o.P(Y+de[0]*O,te+de[1]*O)}function Xy(E,p,j,L,O){const q=new o.P(E,p);return j&&q._rotate(L?O:-O),q}class wi{constructor(p,j,L,O,q,H){this.transform=p.clone(),this.projection=p.projection.name,this.collisionIndex=new Dm(this.transform,q),this.buildingIndex=H,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=j,this.retainedQueryData={},this.collisionGroups=new _i(L),this.collisionCircleArrays={},this.prevPlacement=O,O&&(O.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(p,j,L,O,q=1){const H=L.getBucket(j),Y=L.latestFeatureIndex;if(!H||!Y||j.fqid!==H.layerIds[0])return;const te=H.layers[0].layout,de=H.layers[0].paint,pe=L.collisionBoxArray,Ce=Math.pow(2,this.transform.zoom-L.tileID.overscaledZ),je=L.tileSize/o.an,Me=L.tileID.toUnwrapped();this.transform.setProjection(H.projection);const qe=($e=L.tileID,nt=H.getProjection(),rt=this.transform,nt.name===this.projection?rt.calculateProjMatrix($e.toUnwrapped()):Qb(rt,nt,$e));var $e,nt,rt;const pt=te.get("text-pitch-alignment")==="map",vt=te.get("text-rotation-alignment")==="map";j.compileFilter(j.options);const ot=j.dynamicFilter(),Ut=j.dynamicFilterNeedsFeature(),Tt=j.dynamicFilterNeedsGeometry(),$t=this.transform.calculatePixelsToTileUnitsMatrix(L),_t=Pm(qe,L.tileID.canonical,pt,vt,this.transform,H.getProjection(),$t);let St=null;const Rt=H.getProjection().createInversionMatrix(this.transform,L.tileID.canonical);if(pt){const us=Zy(qe,L.tileID.canonical,pt,vt,this.transform,H.getProjection(),$t);St=o.aD([],this.transform.labelPlaneMatrix,us)}let Zt=null;ot&&L.latestFeatureIndex&&(Zt={unwrappedTileID:Me,dynamicFilter:ot,dynamicFilterNeedsFeature:Ut,needGeometry:Tt}),this.retainedQueryData[H.bucketInstanceId]=new gi(H.bucketInstanceId,Y,H.sourceLayerIndex,H.index,L.tileID);const[qt,xs]=H.layers[0].layout.get("text-size-scale-range"),as=o.aC(q,qt,xs),[Os,Hs]=te.get("icon-size-scale-range"),Qt=o.aC(q,Os,Hs),Ht={bucket:H,layout:te,paint:de,posMatrix:qe,invMatrix:Rt,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:_t,labelToScreenMatrix:St,clippingData:Zt,scale:Ce,textPixelRatio:je,holdingForFade:L.holdingForFade(),collisionBoxArray:pe,partiallyEvaluatedTextSize:o.bj(H.textSizeData,this.transform.zoom,as),partiallyEvaluatedIconSize:o.bj(H.iconSizeData,this.transform.zoom,Qt),collisionGroup:this.collisionGroups.get(H.sourceID),latestFeatureIndex:L.latestFeatureIndex};if(O)for(const us of H.sortKeyRanges){const{sortKey:vs,symbolInstanceStart:ks,symbolInstanceEnd:cr}=us;p.push({sortKey:vs,symbolInstanceStart:ks,symbolInstanceEnd:cr,parameters:Ht})}else p.push({symbolInstanceStart:0,symbolInstanceEnd:H.symbolInstances.length,parameters:Ht})}attemptAnchorPlacement(p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt,pt,vt,ot,Ut){const{textOffset0:Tt,textOffset1:$t,crossTileID:_t}=$e,St=[Tt,$t],Rt=rh(p,H,Y,St,te),Zt=this.collisionIndex.placeCollisionBox(rt,te,j,L,O,q,Xy(Rt.x,Rt.y,de,pe,this.transform.angle),qe,Ce,je,Me.predicate);if(vt){const qt=rt.getSymbolInstanceIconSize(Ut,this.transform.zoom,$e.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(rt,qt,vt,L,O,q,Xy(Rt.x,Rt.y,de,pe,this.transform.angle),qe,Ce,je,Me.predicate).box.length===0)return}if(Zt.box.length>0){let qt;return this.prevPlacement&&this.prevPlacement.variableOffsets[_t]&&this.prevPlacement.placements[_t]&&this.prevPlacement.placements[_t].text&&(qt=this.prevPlacement.variableOffsets[_t].anchor),this.variableOffsets[_t]={textOffset:St,width:H,height:Y,anchor:p,textScale:te,prevAnchor:qt},this.markUsedJustification(rt,p,$e,pt),rt.allowVerticalPlacement&&(this.markUsedOrientation(rt,pt,$e),this.placedOrientations[_t]=pt),{shift:Rt,placedGlyphBoxes:Zt}}}placeLayerBucketPart(p,j,L,O,q=1){const{bucket:H,layout:Y,paint:te,posMatrix:de,textLabelPlaneMatrix:pe,labelToScreenMatrix:Ce,clippingData:je,textPixelRatio:Me,mercatorCenter:qe,invMatrix:$e,holdingForFade:nt,collisionBoxArray:rt,partiallyEvaluatedTextSize:pt,partiallyEvaluatedIconSize:vt,collisionGroup:ot,latestFeatureIndex:Ut}=p.parameters,Tt=Y.get("text-optional"),$t=Y.get("icon-optional"),_t=Y.get("text-allow-overlap"),St=Y.get("icon-allow-overlap"),Rt=Y.get("text-rotation-alignment")==="map",Zt=Y.get("icon-rotation-alignment")==="map",qt=Y.get("text-pitch-alignment")==="map",xs=te.get("symbol-z-offset"),as=Y.get("symbol-elevation-reference")==="sea",Os=Y.get("symbol-placement"),[Hs,Qt]=Y.get("text-size-scale-range"),[Ht,us]=Y.get("icon-size-scale-range"),vs=o.aC(q,Hs,Qt),ks=o.aC(q,Ht,us),cr=Y.get("text-variable-anchor"),Js=Rt&&Os!=="point",er=Zt&&Os!=="point",Us=cr&&H.hasTextData(),Br=H.hasIconTextFit()&&Us&&H.hasIconData();this.transform.setProjection(H.projection);const Kr=Us||Js,Er=er||Br;let Fr=_t&&(St||!H.hasIconData()||$t),_n=St&&(_t||!H.hasTextData()||Tt);const Fn=!xs.isConstant();!H.collisionArrays&&rt&&H.deserializeCollisionBoxes(rt),L&&O&&H.updateCollisionDebugBuffers(this.transform.zoom,rt,vs,ks);const Pn=(pn,la,Dn)=>{const{crossTileID:Wa,numVerticalGlyphVertices:Ti}=pn;let yo=null;if(je&&je.dynamicFilterNeedsFeature||Fn){const qi=this.retainedQueryData[H.bucketInstanceId],Yi=Ut.loadFeature({featureIndex:pn.featureIndex,bucketIndex:qi.bucketIndex,sourceLayerIndex:qi.sourceLayerIndex,layoutVertexArrayOffset:0}),ji=Yi.properties?Yi.properties.worldview:null;if(H.localizable&&H.worldview&&typeof ji=="string")if(ji==="all")Yi.properties.$localized=!0;else{if(!ji.split(",").includes(H.worldview))return;Yi.properties.$localized=!0,Yi.properties.worldview=H.worldview}yo=je&&je.needGeometry?o.bD(Yi,!0):Yi}if(je&&!(0,je.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:H.worldview},yo,this.retainedQueryData[H.bucketInstanceId].tileID.canonical,new o.P(pn.tileAnchorX,pn.tileAnchorY),this.transform.calculateDistanceTileData(je.unwrappedTileID)))return this.placements[Wa]=new Lg(!1,!1,!1,!0),void j.add(Wa);const zi=xs.evaluate(yo,{});if((pn.zOffset||0)+(zi||0)>0&&this.frontCutoffStart>0){const qi=2*this.frontCutoffStart-1,Yi=[pn.tileAnchorX,pn.tileAnchorY,0,1],ji=o.aE(o.bE(),Yi,de);if(ji[1]/ji[3]{qi.tileID=this.retainedQueryData[H.bucketInstanceId].tileID;const Yi=this.transform.elevation;qi.elevation=as?zi:zi+o.bu.getAtTileOffset(qi.tileID,new o.P(qi.tileAnchorX,qi.tileAnchorY),Yi,rc),qi.elevation+=pn.zOffset},lm=Dn.textBox;if(lm){Yc(lm);const qi=ji=>{let gl=o.bk.horizontal;if(H.allowVerticalPlacement&&!ji&&this.prevPlacement){const lu=this.prevPlacement.placedOrientations[Wa];lu&&(this.placedOrientations[Wa]=lu,gl=lu,this.markUsedOrientation(H,gl,pn))}return gl},Yi=(ji,gl)=>{if(H.allowVerticalPlacement&&Ti>0&&Dn.verticalTextBox){for(const lu of H.writingModes)if(lu===o.bk.vertical?(qn=gl(),uo=qn):qn=ji(),qn&&qn.box&&qn.box.length)break}else qn=ji()};if(cr){let ji=cr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Wa]){const Vo=this.prevPlacement.variableOffsets[Wa];ji.indexOf(Vo.anchor)>0&&(ji=ji.filter(cm=>cm!==Vo.anchor),ji.unshift(Vo.anchor))}const gl=(Vo,cm,i0)=>{const x1=H.getSymbolInstanceTextSize(pt,pn,this.transform.zoom,la),g1=(Vo.x2-Vo.x1)*x1+2*Vo.padding,b_=(Vo.y2-Vo.y1)*x1+2*Vo.padding,Ug=pn.hasIconTextFit&&!St?cm:null;Ug&&Yc(Ug);let kx={box:[],offscreen:!1,occluded:!1};const __=_t?2*ji.length:ji.length;for(let Ph=0;Ph<__;++Ph){const o0=this.attemptAnchorPlacement(ji[Ph%ji.length],Vo,qe,$e,Kr,g1,b_,x1,Rt,qt,Me,de,ot,Ph>=ji.length,pn,la,H,i0,Ug,pt,vt);if(o0&&(kx=o0.placedGlyphBoxes,kx&&kx.box&&kx.box.length)){ri=!0,ni=o0.shift;break}}return kx};Yi(()=>gl(lm,Dn.iconBox,o.bk.horizontal),()=>{const Vo=Dn.verticalTextBox;return Vo&&Yc(Vo),H.allowVerticalPlacement&&!(qn&&qn.box&&qn.box.length)&&Ti>0&&Vo?gl(Vo,Dn.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),qn&&(ri=qn.box,ea=qn.offscreen,$i=qn.occluded);const lu=qi(!(!qn||!qn.box));if(!ri&&this.prevPlacement){const Vo=this.prevPlacement.variableOffsets[Wa];Vo&&(this.variableOffsets[Wa]=Vo,this.markUsedJustification(H,Vo.anchor,pn,lu))}}else{const ji=(gl,lu)=>{const Vo=H.getSymbolInstanceTextSize(pt,pn,this.transform.zoom,la),cm=this.collisionIndex.placeCollisionBox(H,Vo,gl,qe,$e,Kr,new o.P(0,0),_t,Me,de,ot.predicate);return cm&&cm.box&&cm.box.length&&(this.markUsedOrientation(H,lu,pn),this.placedOrientations[Wa]=lu),cm};Yi(()=>ji(lm,o.bk.horizontal),()=>{const gl=Dn.verticalTextBox;return H.allowVerticalPlacement&&Ti>0&&gl?(Yc(gl),ji(gl,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),qi(!!(qn&&qn.box&&qn.box.length))}}if(Ei=qn,ri=Ei&&Ei.box&&Ei.box.length>0,ea=Ei&&Ei.offscreen,$i=Ei&&Ei.occluded,pn.useRuntimeCollisionCircles){const qi=pn.centerJustifiedTextSymbolIndex>=0?pn.centerJustifiedTextSymbolIndex:pn.verticalPlacedTextSymbolIndex,Yi=H.text.placedSymbolArray.get(qi),ji=o.bl(H.textSizeData,pt,Yi),gl=Y.get("text-padding");jl=this.collisionIndex.placeCollisionCircles(H,_t,Yi,qi,H.lineVertexArray,H.glyphOffsetArray,ji,de,pe,Ce,L,qt,ot.predicate,pn.collisionCircleDiameter*ji/o.by,gl,this.retainedQueryData[H.bucketInstanceId].tileID),ri=_t||jl.circles.length>0&&!jl.collisionDetected,ea=ea&&jl.offscreen,$i=jl.occluded}if(Dn.iconFeatureIndex&&(Ud=Dn.iconFeatureIndex),Dn.iconBox){const qi=Yi=>{Yc(Yi);const ji=pn.hasIconTextFit&&ni?Xy(ni.x,ni.y,Rt,qt,this.transform.angle):new o.P(0,0),gl=H.getSymbolInstanceIconSize(vt,this.transform.zoom,pn.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(H,gl,Yi,qe,$e,Er,ji,St,Me,de,ot.predicate)};uo&&uo.box&&uo.box.length&&Dn.verticalIconBox?(_a=qi(Dn.verticalIconBox),Jn=_a.box.length>0):(_a=qi(Dn.iconBox),Jn=_a.box.length>0),ea=ea&&_a.offscreen,No=_a.occluded}const fi=Tt||pn.numHorizontalGlyphVertices===0&&Ti===0,$m=$t||pn.numIconVertices===0;if(fi||$m?$m?fi||(Jn=Jn&&ri):ri=Jn&&ri:Jn=ri=Jn&&ri,ri&&Ei&&Ei.box&&this.collisionIndex.insertCollisionBox(Ei.box,Y.get("text-ignore-placement"),H.bucketInstanceId,uo&&uo.box&&Ul?Ul:Ri,ot.ID),Jn&&_a&&this.collisionIndex.insertCollisionBox(_a.box,Y.get("icon-ignore-placement"),H.bucketInstanceId,Ud,ot.ID),jl&&(ri&&this.collisionIndex.insertCollisionCircles(jl.circles,Y.get("text-ignore-placement"),H.bucketInstanceId,Ri,ot.ID),L)){const qi=H.bucketInstanceId;let Yi=this.collisionCircleArrays[qi];Yi===void 0&&(Yi=this.collisionCircleArrays[qi]=new Zr);for(let ji=0;ji=0;--la){const Dn=pn[la];Pn(H.symbolInstances.get(Dn),Dn,H.collisionArrays[Dn])}H.hasAnyZOffset&&o.w(`${H.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(H.hasAnyZOffset){const pn=H.getSortedIndexesByZOffset();for(let la=0;la=0&&(p.text.placedSymbolArray.get(q).crossTileID=Ce>=0&&q!==Ce?0:de),H>=0&&(p.text.placedSymbolArray.get(H).crossTileID=Ce>=0&&H!==Ce?0:de),Y>=0&&(p.text.placedSymbolArray.get(Y).crossTileID=Ce>=0&&Y!==Ce?0:de),te>=0&&(p.text.placedSymbolArray.get(te).crossTileID=Ce>=0&&te!==Ce?0:de)}markUsedOrientation(p,j,L){const O=j===o.bk.horizontal||j===o.bk.horizontalOnly?j:0,q=j===o.bk.vertical?j:0,{leftJustifiedTextSymbolIndex:H,centerJustifiedTextSymbolIndex:Y,rightJustifiedTextSymbolIndex:te,verticalPlacedTextSymbolIndex:de}=L,pe=p.text.placedSymbolArray;H>=0&&(pe.get(H).placedOrientation=O),Y>=0&&(pe.get(Y).placedOrientation=O),te>=0&&(pe.get(te).placedOrientation=O),de>=0&&(pe.get(de).placedOrientation=q)}commit(p){this.commitTime=p,this.zoomAtLastRecencyCheck=this.transform.zoom;const j=this.prevPlacement;let L=!1;this.prevZoomAdjustment=j?j.zoomAdjustment(this.transform.zoom):0;const O=j?j.symbolFadeChange(p):1,q=j?j.opacities:{},H=j?j.variableOffsets:{},Y=j?j.placedOrientations:{};for(const te in this.placements){const de=this.placements[te],pe=q[te];pe?(this.opacities[te]=new Ig(pe,O,de.text,de.icon,null,de.clipped),L=L||de.text!==pe.text.placed||de.icon!==pe.icon.placed):(this.opacities[te]=new Ig(null,O,de.text,de.icon,de.skipFade,de.clipped),L=L||de.text||de.icon)}for(const te in q){const de=q[te];if(!this.opacities[te]){const pe=new Ig(de,O,!1,!1);pe.isHidden()||(this.opacities[te]=pe,L=L||de.text.placed||de.icon.placed)}}for(const te in H)this.variableOffsets[te]||!this.opacities[te]||this.opacities[te].isHidden()||(this.variableOffsets[te]=H[te]);for(const te in Y)this.placedOrientations[te]||!this.opacities[te]||this.opacities[te].isHidden()||(this.placedOrientations[te]=Y[te]);L?this.lastPlacementChangeTime=p:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=j?j.lastPlacementChangeTime:p)}updateLayerOpacities(p,j,L,O){O&&(this.lastReplacementSourceUpdateTime=O.updateTime);const q=new Set;for(const H of j){const Y=H.getBucket(p);Y&&H.latestFeatureIndex&&p.fqid===Y.layerIds[0]&&(this.updateBucketOpacities(Y,q,H,H.collisionBoxArray,L,O,H.tileID,p.scope),Y.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(Y,H.tileID),Y.elevationType==="road"&&Y.updateRoadElevation(H.tileID.canonical),Y.updateZOffset())}}updateBucketOpacities(p,j,L,O,q,H,Y,te){p.hasTextData()&&p.text.opacityVertexArray.clear(),p.hasIconData()&&p.icon.opacityVertexArray.clear(),p.hasIconCollisionBoxData()&&p.iconCollisionBox.collisionVertexArray.clear(),p.hasTextCollisionBoxData()&&p.textCollisionBox.collisionVertexArray.clear();const de=p.layers[0].layout,pe=p.layers[0].paint,Ce=!!p.layers[0].dynamicFilter(),je=new Ig(null,0,!1,!1,!0),Me=de.get("text-allow-overlap"),qe=de.get("icon-allow-overlap"),$e=de.get("text-variable-anchor"),nt=de.get("text-rotation-alignment")==="map",rt=de.get("text-pitch-alignment")==="map",pt=pe.get("symbol-z-offset"),vt=de.get("symbol-elevation-reference")==="sea",ot=!pt.isConstant(),Ut=new Ig(null,0,Me&&(qe||!p.hasIconData()||de.get("icon-optional")),qe&&(Me||!p.hasTextData()||de.get("text-optional")),!0);!p.collisionArrays&&O&&(p.hasIconCollisionBoxData()||p.hasTextCollisionBoxData())&&p.deserializeCollisionBoxes(O);const Tt=(_t,St,Rt)=>{for(let Zt=0;Zt0||Zt>0,cr=xs>0,Js=this.placedOrientations[qt],er=Js===o.bk.vertical,Us=Js===o.bk.horizontal||Js===o.bk.horizontalOnly;!ks&&!cr||vs.isHidden()||$t++;let Br=!1;if((ks||cr)&&H)for(const Kr of p.activeReplacements){if(o.bz(Kr,q,o.bA.Symbol,te)||Kr.min.x>as||as>Kr.max.x||Kr.min.y>Os||Os>Kr.max.y)continue;const Er=o.bB(as,Os,Y.canonical,Kr.footprintTileId.canonical);if(Br=o.bC(Er,Kr.footprint),Br)break}if(Br&&this.collisionIndex.markSymbolAsClipped(p.bucketInstanceId,St.featureIndex),ks){const Kr=Br?Pg:e_(vs.text);Tt(p.text,Rt,er?Pg:Kr),Tt(p.text,Zt,Us?Pg:Kr);const Er=vs.text.isHidden(),{leftJustifiedTextSymbolIndex:Fr,centerJustifiedTextSymbolIndex:_n,rightJustifiedTextSymbolIndex:Fn,verticalPlacedTextSymbolIndex:Pn}=St,oa=p.text.placedSymbolArray,pn=Er||er?1:0;Fr>=0&&(oa.get(Fr).hidden=pn),_n>=0&&(oa.get(_n).hidden=pn),Fn>=0&&(oa.get(Fn).hidden=pn),Pn>=0&&(oa.get(Pn).hidden=Er||Us?1:0);const la=this.variableOffsets[qt];la&&this.markUsedJustification(p,la.anchor,St,Js);const Dn=this.placedOrientations[qt];Dn&&(this.markUsedJustification(p,"left",St,Dn),this.markUsedOrientation(p,Dn,St))}if(cr){const Kr=Br?Pg:e_(vs.icon),{placedIconSymbolIndex:Er,verticalPlacedIconSymbolIndex:Fr}=St,_n=p.icon.placedSymbolArray,Fn=vs.icon.isHidden()?1:0;Er>=0&&(Tt(p.icon,xs,er?Pg:Kr),_n.get(Er).hidden=Fn),Fr>=0&&(Tt(p.icon,St.numVerticalIconVertices,Us?Pg:Kr),_n.get(Fr).hidden=Fn)}if(p.hasIconCollisionBoxData()||p.hasTextCollisionBoxData()){const Kr=p.collisionArrays[_t];if(Kr){let Er=new o.P(0,0),Fr=!0;if(Kr.textBox||Kr.verticalTextBox){if($e){const Fn=this.variableOffsets[qt];Fn?(Er=rh(Fn.anchor,Fn.width,Fn.height,Fn.textOffset,Fn.textScale),nt&&Er._rotate(rt?this.transform.angle:-this.transform.angle)):Fr=!1}Ce&&(Fr=!vs.clipped),Kr.textBox&&Jv(p.textCollisionBox.collisionVertexArray,vs.text.placed,!Fr||er,Ht,vt,Er.x,Er.y),Kr.verticalTextBox&&Jv(p.textCollisionBox.collisionVertexArray,vs.text.placed,!Fr||Us,Ht,vt,Er.x,Er.y)}const _n=Fr&&!!(!Us&&Kr.verticalIconBox);Kr.iconBox&&Jv(p.iconCollisionBox.collisionVertexArray,vs.icon.placed,_n,Ht,vt,St.hasIconTextFit?Er.x:0,St.hasIconTextFit?Er.y:0),Kr.verticalIconBox&&Jv(p.iconCollisionBox.collisionVertexArray,vs.icon.placed,!_n,Ht,vt,St.hasIconTextFit?Er.x:0,St.hasIconTextFit?Er.y:0)}}}if(p.fullyClipped=$t===0,p.sortFeatures(this.transform.angle),this.retainedQueryData[p.bucketInstanceId]&&(this.retainedQueryData[p.bucketInstanceId].featureSortOrder=p.featureSortOrder),p.hasTextData()&&p.text.opacityVertexBuffer&&p.text.opacityVertexBuffer.updateData(p.text.opacityVertexArray),p.hasIconData()&&p.icon.opacityVertexBuffer&&p.icon.opacityVertexBuffer.updateData(p.icon.opacityVertexArray),p.hasIconCollisionBoxData()&&p.iconCollisionBox.collisionVertexBuffer&&p.iconCollisionBox.collisionVertexBuffer.updateData(p.iconCollisionBox.collisionVertexArray),p.hasTextCollisionBoxData()&&p.textCollisionBox.collisionVertexBuffer&&p.textCollisionBox.collisionVertexBuffer.updateData(p.textCollisionBox.collisionVertexArray),p.bucketInstanceId in this.collisionCircleArrays){const _t=this.collisionCircleArrays[p.bucketInstanceId];p.placementInvProjMatrix=_t.invProjMatrix,p.placementViewportMatrix=_t.viewportMatrix,p.collisionCircleArray=_t.circles,delete this.collisionCircleArrays[p.bucketInstanceId]}}symbolFadeChange(p){return this.fadeDuration===0?1:(p-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(p){return Math.max(0,(this.transform.zoom-p)/1.5)}hasTransitions(p){return p-this.lastPlacementChangeTimep}isStale(){return this.stale}setStale(){this.stale=!0}}function Jv(E,p,j,L,O,q,H){E.emplaceBack(p?1:0,j?1:0,q||0,H||0,L,O?1:0),E.emplaceBack(p?1:0,j?1:0,q||0,H||0,L,O?1:0),E.emplaceBack(p?1:0,j?1:0,q||0,H||0,L,O?1:0),E.emplaceBack(p?1:0,j?1:0,q||0,H||0,L,O?1:0)}const g2=Math.pow(2,25),y2=Math.pow(2,24),Su=Math.pow(2,17),tc=Math.pow(2,16),tge=Math.pow(2,9),v2=Math.pow(2,8),DL=Math.pow(2,1);function e_(E){if(E.opacity===0&&!E.placed)return 0;if(E.opacity===1&&E.placed)return 4294967295;const p=E.placed?1:0,j=Math.floor(127*E.opacity);return j*g2+p*y2+j*Su+p*tc+j*tge+p*v2+j*DL+p}const Pg=0;class RL{constructor(p){this._sortAcrossTiles=p.layout.get("symbol-z-order")!=="viewport-y"&&p.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(p,j,L,O,q,H){const Y=this._bucketParts;for(;this._currentTileIndexte.sortKey-de.sortKey));this._currentPartIndex{const te=o.o.now()-H;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&te>2};for(;this._currentPlacementIndex>=0;){const te=j[p[this._currentPlacementIndex]],de=this.placement.collisionIndex.transform.zoom;if(te.type==="symbol"&&te.visibility!=="none"&&(!te.minzoom||te.minzoom<=de)&&(!te.maxzoom||te.maxzoom>de)){const pe=te,Ce=pe.layout.get("symbol-z-elevate"),je=pe.layout.get("symbol-sort-key").constantOr(1)!==void 0,Me=pe.layout.get("symbol-z-order"),qe=Me==="viewport-y"||Me==="auto"&&!(Me!=="viewport-y"&&je),$e=pe.layout.get("text-allow-overlap")||pe.layout.get("icon-allow-overlap")||pe.layout.get("text-ignore-placement")||pe.layout.get("icon-ignore-placement"),nt=qe&&$e,rt=this._inProgressLayer=this._inProgressLayer||new RL(pe),pt=o.F(te.source,te.scope);if(rt.continuePlacement(Ce||nt?O[pt]:L[pt],this.placement,this._showCollisionBoxes,te,Y,q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(p){return this.placement.commit(p),this.placement}}const iu=512/o.an/2;class Sf{constructor(p,j,L){this.tileID=p,this.bucketInstanceId=L,this.index=new o.bI(j.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const O=p.canonical.x*o.an,q=p.canonical.y*o.an;for(let H=0;Hnt-rt);for(const nt of $e){const rt=this.crossTileIDs[nt];if(this.keys[nt]===pe&&!L.has(rt)){L.add(rt),de.crossTileID=rt;break}}}}}class Lh{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class KB{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(p){const j=Math.round((p-this.lng)/360);if(j!==0)for(const L in this.indexes){const O=this.indexes[L],q={};for(const H in O){const Y=O[H];Y.tileID=Y.tileID.unwrapTo(Y.tileID.wrap+j),q[Y.tileID.key]=Y}this.indexes[L]=q}this.lng=p}addBucket(p,j,L){if(this.indexes[p.overscaledZ]&&this.indexes[p.overscaledZ][p.key]){if(this.indexes[p.overscaledZ][p.key].bucketInstanceId===j.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(p.overscaledZ,this.indexes[p.overscaledZ][p.key])}for(let q=0;qp.overscaledZ)for(const Y in H){const te=H[Y];te.tileID.isChildOf(p)&&te.findMatches(j.symbolInstances,p,O)}else{const Y=H[p.scaledTo(Number(q)).key];Y&&Y.findMatches(j.symbolInstances,p,O)}}for(let q=0;q{j[L]=!0});for(const L in this.layerIndexes)j[L]||delete this.layerIndexes[L]}}const xl=771;class Tn{constructor(p,j,L,O){this.blendFunction=p,this.blendColor=j.toNonPremultipliedRenderColor(null),this.mask=L,this.blendEquation=O}}Tn.Replace=[1,0,1,0],Tn.disabled=new Tn(Tn.Replace,o.aq.transparent,[!1,!1,!1,!1]),Tn.unblended=new Tn(Tn.Replace,o.aq.transparent,[!0,!0,!0,!0]),Tn.alphaBlended=new Tn([1,xl,1,xl],o.aq.transparent,[!0,!0,!0,!0]),Tn.alphaBlendedNonPremultiplied=new Tn([770,xl,770,xl],o.aq.transparent,[!0,!0,!0,!0]),Tn.multiply=new Tn([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),Tn.multiplyAccumulateAlpha=new Tn([774,0,1,xl],o.aq.transparent,[!0,!0,!0,!0]),Tn.additive=new Tn([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class $r{constructor(p,j,L){this.func=p,this.mask=j,this.range=L}}$r.ReadOnly=!1,$r.ReadWrite=!0,$r.disabled=new $r(519,$r.ReadOnly,[0,1]);const $l=7680;class Mn{constructor(p,j,L,O,q,H){this.test=p,this.ref=j,this.mask=L,this.fail=O,this.depthFail=q,this.pass=H}}Mn.disabled=new Mn({func:519,mask:0},0,0,$l,$l,$l);const Rm=1029,e1=2305;class vn{constructor(p,j,L){this.enable=p,this.mode=j,this.frontFace=L}}function _2(E,p){const j=o.bO(E,3);o.bR(E,p),o.bW(E,3,j)}function v5(E,p){const j=o.bL([]);return o.bM(j,j,-p),o.bN(j,j,-E),j}function b5(E,p){const j=[E[0],E[1],0],L=[p[0],p[1],0];if(o.ai(j)>=1e-15){const H=o.ay([],j);o.bJ(L,H,o.bi(L,H)),p[0]=L[0],p[1]=L[1]}const O=o.bh([],p,E);if(o.bK(O)<1e-15)return null;const q=Math.atan2(-O[1],O[0]);return v5(Math.atan2(Math.sqrt(E[0]*E[0]+E[1]*E[1]),-E[2]),q)}vn.disabled=new vn(!1,Rm,e1),vn.backCCW=new vn(!0,Rm,e1),vn.backCW=new vn(!0,Rm,2304),vn.frontCW=new vn(!0,1028,2304),vn.frontCCW=new vn(!0,1028,e1);class w2{constructor(p,j){this.position=p,this.orientation=j}get position(){return this._position}set position(p){if(p){const j=p instanceof o.ag?p:new o.ag(p[0],p[1],p[2]);this._renderWorldCopies&&(j.x=o.bs(j.x,0,1)),this._position=j}else this._position=null}lookAtPoint(p,j,L){if(this.orientation=null,!this.position)return;const O=this.position,q=L||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(p)):0),H=o.ag.fromLngLat(p,q),Y=[H.x-O.x,H.y-O.y,H.z-O.z];j||(j=[0,0,1]),j[2]=Math.abs(j[2]),this.orientation=b5(Y,j)}setPitchBearing(p,j){this.orientation=v5(o.ap(p),o.ap(-j))}}class j2{constructor(p,j){this._transform=o.b9([]),this.orientation=j,this.position=p}get mercatorPosition(){const p=this.position;return new o.ag(p[0],p[1],p[2])}get position(){const p=o.bO(this._transform,3);return[p[0],p[1],p[2]]}set position(p){var j;p&&o.bW(this._transform,3,[(j=p)[0],j[1],j[2],1])}get orientation(){return this._orientation}set orientation(p){this._orientation=p||o.bL([]),p&&_2(this._transform,this._orientation)}getPitchBearing(){const p=this.forward(),j=this.right();return{bearing:Math.atan2(-j[1],j[0]),pitch:Math.atan2(Math.sqrt(p[0]*p[0]+p[1]*p[1]),-p[2])}}setPitchBearing(p,j){this._orientation=v5(p,j),_2(this._transform,this._orientation)}forward(){const p=o.bO(this._transform,2);return[-p[0],-p[1],-p[2]]}up(){const p=o.bO(this._transform,1);return[-p[0],-p[1],-p[2]]}right(){const p=o.bO(this._transform,0);return[p[0],p[1],p[2]]}getCameraToWorld(p,j){const L=new Float64Array(16);return o.b7(L,this.getWorldToCamera(p,j)),L}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(p,j,L){const O=this.position;o.bJ(O,O,-p);const q=new Float64Array(16);return o.bP(q,[L,L,L]),o.bx(q,q,O),q[10]*=j,q}getWorldToCamera(p,j){const L=new Float64Array(16),O=new Float64Array(4),q=this.position;return o.bQ(O,this._orientation),o.bJ(q,q,-p),o.bR(L,O),o.bx(L,L,q),L[1]*=-1,L[5]*=-1,L[9]*=-1,L[13]*=-1,L[8]*=j,L[9]*=j,L[10]*=j,L[11]*=j,L}getCameraToClipPerspective(p,j,L,O){const q=new Float64Array(16);return o.bS(q,p,j,L,O),q}getCameraToClipOrthographic(p,j,L,O,q,H){const Y=new Float64Array(16);return o.bT(Y,p,j,L,O,q,H),Y}getDistanceToElevation(p,j=!1){const L=p===0?0:o.bU(p,j?o.bV(this.position[1]):this.position[1]),O=this.forward();return(L-this.position[2])/O[2]}clone(){return new j2([...this.position],[...this.orientation])}}const sge=(E,p)=>({u_matrix:E,u_ground_shadow_factor:p});class dp{constructor(p=0,j=0,L=0,O=0){if(isNaN(p)||p<0||isNaN(j)||j<0||isNaN(L)||L<0||isNaN(O)||O<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=p,this.bottom=j,this.left=L,this.right=O}interpolate(p,j,L){return j.top!=null&&p.top!=null&&(this.top=o.am(p.top,j.top,L)),j.bottom!=null&&p.bottom!=null&&(this.bottom=o.am(p.bottom,j.bottom,L)),j.left!=null&&p.left!=null&&(this.left=o.am(p.left,j.left,L)),j.right!=null&&p.right!=null&&(this.right=o.am(p.right,j.right,L)),this}getCenter(p,j){const L=o.aC((this.left+p-this.right)/2,0,p),O=o.aC((this.top+j-this.bottom)/2,0,j);return new o.P(L,O)}equals(p){return this.top===p.top&&this.bottom===p.bottom&&this.left===p.left&&this.right===p.right}clone(){return new dp(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const t1=15;class N2{constructor(p,j,L,O,q,H,Y){this.tileSize=512,this._renderWorldCopies=q===void 0||q,this._minZoom=p||0,this._maxZoom=j||22,this._minPitch=L??0,this._maxPitch=O??60,this.setProjection(H),this.setMaxBounds(Y),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 dp,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new j2,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 p=new N2(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return p._elevation=this._elevation,p._centerAltitude=this._centerAltitude,p._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,p.tileSize=this.tileSize,p.mercatorFromTransition=this.mercatorFromTransition,p.width=this.width,p.height=this.height,p.cameraElevationReference=this.cameraElevationReference,p._center=this._center,p._setZoom(this.zoom),p._seaLevelZoom=this._seaLevelZoom,p.angle=this.angle,p._fov=this._fov,p._pitch=this._pitch,p._nearZ=this._nearZ,p._farZ=this._farZ,p._nearClipOffset=this._nearClipOffset,p._averageElevation=this._averageElevation,p._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,p._unmodified=this._unmodified,p._edgeInsets=this._edgeInsets.clone(),p._camera=this._camera.clone(),p._calcMatrices(),p.freezeTileCoverage=this.freezeTileCoverage,p.frustumCorners=this.frustumCorners,p._allowWorldUnderZoom=this._allowWorldUnderZoom,p}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||p===Number.NEGATIVE_INFINITY&&(!j||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const L=this._elevation;j||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&L.exaggeration()&&this._centerAltitudeValidForExaggeration!==L.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*L.exaggeration(),this._centerAltitudeValidForExaggeration=L.exaggeration()):(this._centerAltitude=p||0,this._centerAltitudeValidForExaggeration=L.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const p=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(p)}sampleAverageElevation(){if(!this._elevation)return 0;const p=this._elevation,j=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],L=this.horizonLineFromTop();let O=0,q=0;for(let H=0;H{const nt=o.ck(je,Ce,Me,qe,$e);te.has(nt)||(q.push(new o.aR(Ce,je,Me,qe,$e)),te.add(nt))};for(let Ce=0;Ceje.canonical.z)continue;const Me=je.canonical,qe=je.overscaledZ,$e=je.wrap,nt=1<0,vt=Me.y+10,Ut=je.wrap-(pt?0:1),Tt=je.wrap+(rt?0:1),$t=pt?Me.x-1:nt-1,_t=rt?Me.x+1:0;if(H)L[0]<0?(de(qe,Tt,Me.z,_t,Me.y),L[1]<0&&vt&&(de(qe,$e,Me.z,Me.x,Me.y+1),de(qe,Tt,Me.z,_t,Me.y+1)),L[1]>0&&ot&&(de(qe,$e,Me.z,Me.x,Me.y-1),de(qe,Tt,Me.z,_t,Me.y-1))):L[0]>0?(de(qe,Ut,Me.z,$t,Me.y),L[1]<0&&vt&&(de(qe,$e,Me.z,Me.x,Me.y+1),de(qe,Ut,Me.z,$t,Me.y+1)),L[1]>0&&ot&&(de(qe,$e,Me.z,Me.x,Me.y-1),de(qe,Ut,Me.z,$t,Me.y-1))):L[1]<0&&vt?de(qe,$e,Me.z,Me.x,Me.y+1):ot&&de(qe,$e,Me.z,Me.x,Me.y-1);else{const St=je.visibleQuadrants;1&St&&(de(qe,Ut,Me.z,$t,Me.y),ot&&(de(qe,$e,Me.z,Me.x,Me.y-1),de(qe,Ut,Me.z,$t,Me.y-1))),2&St&&(de(qe,Tt,Me.z,_t,Me.y),ot&&(de(qe,$e,Me.z,Me.x,Me.y-1),de(qe,Tt,Me.z,_t,Me.y-1))),4&St&&(de(qe,Ut,Me.z,$t,Me.y),vt&&(de(qe,$e,Me.z,Me.x,Me.y+1),de(qe,Ut,Me.z,$t,Me.y+1))),8&St&&(de(qe,Tt,Me.z,_t,Me.y),vt&&(de(qe,$e,Me.z,Me.x,Me.y+1),de(qe,Tt,Me.z,_t,Me.y+1)))}}const pe=[];for(const Ce of q)q.some(je=>Ce.isChildOf(je))||pe.push(Ce);if(q=pe.filter(Ce=>!p.some(je=>!!(Ce.overscaledZ{const rt=nt.canonical.x+.5-Me[0],pt=nt.canonical.y+.5-Me[1];return rt*rt+pt*pt<$e})}return q}extendTileCoverToNearPlane(p,j,L){const O=[],q=new Set;for(const pt of p)q.add(pt.key);const H=(pt,vt,ot,Ut,Tt)=>{const $t=o.ck(vt,pt,ot,Ut,Tt);q.has($t)||(O.push(new o.aR(pt,vt,ot,Ut,Tt)),q.add($t))},Y=p.reduce((pt,vt)=>Math.max(pt,vt.overscaledZ),L),te=1<{const ot=Math.floor(pt[0]),Ut=Math.floor(pt[1]),Tt=(pt[0]-ot)*o.an,$t=(pt[1]-Ut)*o.an,_t=Math.floor(vt[0]),St=Math.floor(vt[1]),Rt=(vt[0]-_t)*o.an,Zt=(vt[1]-St)*o.an;for(let qt=-1;qt<=1;qt++){const xs=ot+qt;if(!(xs<0||xs>=te)){pe.x=Tt-qt*o.an,Ce.x=Rt-(xs-_t)*o.an;for(let as=-1;as<=1;as++){const Os=Ut+as;pe.y=$t-as*o.an,Ce.y=Zt-(Os-St)*o.an,o.cI(pe,Ce,de)&&H(Y,0,L,xs,Os)}}}},Me=j.points,qe=Me[o.c9],$e=Me[o.ca],nt=this._projectToGround(qe,Me[o.cb]),rt=this._projectToGround($e,Me[o.cc]);return je(qe,nt),je($e,rt),O}_projectToGround(p,j){return o.cd(o.ce(),p,j,p[2]/(p[2]-j[2]))}_projectToZ(p,j,L){const O=p[2]-j[2];return Math.abs(O)<1e-6?o.cf(p):o.cd(o.ce(),p,j,(p[2]-L)/O)}extendTileCoverForTunnels(p,j,L,O){if(L<18)return[];const q=j.points,H=q[o.cg],Y=q[o.ch],te=q[o.ci],de=q[o.cj];if(te[2]>=0&&de[2]>=0||H[2]<=0||Y[2]<=0)return[];const pe=te[2]<0?this._projectToZ(H,te,0):te,Ce=de[2]<0?this._projectToZ(Y,de,0):de,je=-O,Me=te[2]3&&($e.length=3),$e}_findExtensionTilesInQuad(p,j,L,O){const q=[],H=new Set;for(const _t of p)H.add(_t.key);const Y=p.reduce((_t,St)=>Math.max(_t,St.overscaledZ),j),te=1<{const Rt=_t.canonical.x+.5-Tt,Zt=_t.canonical.y+.5-$t,qt=St.canonical.x+.5-Tt,xs=St.canonical.y+.5-$t;return Rt*Rt+Zt*Zt-(qt*qt+xs*xs)||_t.canonical.x-St.canonical.x||_t.canonical.y-St.canonical.y}),q}coveringTiles(p){let j=this.coveringZoomLevel(p);const L=j,O=this.elevation&&this.elevation.exaggeration(),q=O&&!p.isTerrainDEM,H=this.projection.name==="mercator";if(p.minzoom!==void 0&&jp.maxzoom&&(j=p.maxzoom);const Y=this.locationCoordinate(this.center),te=this.center.lat,de=1<{const vs=new o.ag(Ht.x+25e-6,Ht.y,Ht.z),ks=new o.ag(Ht.x,Ht.y+25e-6,Ht.z),cr=Ht.toLngLat(),Js=vs.toLngLat(),er=ks.toLngLat(),Us=this.locationCoordinate(cr),Br=this.locationCoordinate(Js),Kr=this.locationCoordinate(er),Er=Math.hypot(Br.x-Us.x,Br.y-Us.y),Fr=Math.hypot(Kr.x-Us.x,Kr.y-Us.y);return Math.sqrt(Er*Fr)*$t/25e-6},St=Ht=>{const us=Ut,vs=Tt;return{aabb:o.cp(this,de,0,0,0,Ht,vs,us,this.projection),zoom:0,x:0,y:0,minZ:vs,maxZ:us,wrap:Ht,fullyVisible:!1}},Rt=[];let Zt=[];const qt=j,xs=p.reparseOverscaled?L:j,as=(nt-this._centerAltitude)*$e,Os=Ht=>{if(!this._elevation||!Ht.tileID||!H)return;const us=this._elevation.getMinMaxForTile(Ht.tileID),vs=Ht.aabb;us?(vs.min[2]=us.min,vs.max[2]=us.max,vs.center[2]=(vs.min[2]+vs.max[2])/2):(Ht.shouldSplit=Qt(Ht),Ht.shouldSplit||(vs.min[2]=vs.max[2]=vs.center[2]=this._centerAltitude))},Hs=(Ht,us)=>{if(.707*us{if(Ht.zoom=.9)return!0}else if(q&&(ks=Ht.aabb.distanceZ(rt)*$e),this.projection.isReprojectedInTileSpace&&L<=5){const Fr=Math.pow(2,Ht.zoom),_n=_t(new o.ag((Ht.x+.5)/Fr,(Ht.y+.5)/Fr));cr=_n>.85?1:_n}if(!H&&!Ce){const Fr=Math.sqrt(us*us+vs*vs+ks*ks);let _n=(1<0;){const Ht=Rt.pop(),us=Ht.x,vs=Ht.y;let ks=Ht.fullyVisible;const cr=()=>this.projection.name==="globe"&&(Ht.y===0||Ht.y===(1<Js)continue;let er=0;if(!ks){let Er=pt?Ht.aabb.intersectsPrecise(Me):Ht.aabb.intersectsPreciseFlat(Me);if(Er===0&&cr()){const Fr=new o.cn(Ht.zoom,us,vs);Er=o.co(this,de,Fr,!0).intersectsPrecise(Me)}if(Er===0)continue;if(p.calculateQuadrantVisibility)if(Me.containsPoint(Ht.aabb.center))er=15;else for(let Fr=0;Fr<4;Fr++)Ht.aabb.quadrant(Fr).intersects(Me)!==0&&(er|=1<>1),Br={aabb:H?Ht.aabb.quadrant(Js):o.cp(this,de,Ht.zoom+1,er,Us,Ht.wrap,Ht.minZ,Ht.maxZ,this.projection),zoom:Ht.zoom+1,x:er,y:Us,wrap:Ht.wrap,fullyVisible:ks,tileID:void 0,shouldSplit:void 0,minZ:Ht.minZ,maxZ:Ht.maxZ};q&&!Ce&&(Br.tileID=new o.aR(Ht.zoom+1===qt?xs:Ht.zoom+1,Ht.wrap,Ht.zoom+1,er,Us),Os(Br)),Rt.push(Br)}}if(this.fogCullDistSq){const Ht=this.fogCullDistSq,us=this.horizonLineFromTop();Zt=Zt.filter(vs=>{const ks=[0,0,0,1],cr=[o.an,o.an,0,1],Js=this.calculateFogTileMatrix(vs.tileID.toUnwrapped());o.aE(ks,ks,Js),o.aE(cr,cr,Js);const er=o.cq([],ks,cr),Us=o.cr([],ks,cr),Br=o.cK(er,Us);if(Br===0)return!0;let Kr=!1;const Er=this._elevation;if(Er&&Br>Ht&&us!==0){const Fr=this.calculateProjMatrix(vs.tileID.toUnwrapped());let _n;p.isTerrainDEM||(_n=Er.getMinMaxForTile(vs.tileID)),_n||(_n={min:Tt,max:Ut});const Fn=o.cs(this.rotation),Pn=[Fn[0]*o.an,Fn[1]*o.an,_n.max];o.ah(Pn,Pn,Fr),Kr=(1-Pn[1])*this.height*.5Ht.distanceSq-us.distanceSq).map(Ht=>Ht.tileID)}resize(p,j){this.width=p,this.height=j,this.pixelsToGLUnits=[2/p,-2/j],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(p){return Math.pow(2,p)}scaleZoom(p){return Math.log2(p)}project(p){const j=o.aC(p.lat,-o.ct,o.ct),L=this.projection.project(p.lng,j);return new o.P(L.x*this.worldSize,L.y*this.worldSize)}unproject(p){return this.projection.unproject(p.x/this.worldSize,p.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(p,j){let L,O;const q=this.centerPoint;if(this.projection.name==="globe"){const Y=this.worldSize;L=(j.x-q.x)/Y,O=(j.y-q.y)/Y}else{const Y=this.pointCoordinate(j),te=this.pointCoordinate(q);L=Y.x-te.x,O=Y.y-te.y}const H=this.locationCoordinate(p);this.setLocation(new o.ag(H.x-L,H.y-O))}setLocation(p){this.center=this.coordinateLocation(p),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(p,j){return this.projection.locationPoint(this,p,j)}locationPoint3D(p,j){return this.projection.locationPoint(this,p,j,!0)}pointLocation(p){return this.coordinateLocation(this.pointCoordinate(p))}pointLocation3D(p,j){return this.coordinateLocation(this.pointCoordinate3D(p,j))}locationCoordinate(p,j){const L=j?o.bU(j,p.lat):void 0,O=this.projection.project(p.lng,p.lat);return new o.ag(O.x,O.y,L)}coordinateLocation(p){return this.projection.unproject(p.x,p.y)}pointRayIntersection(p,j){const L=j??this._centerAltitude,O=[p.x,p.y,0,1],q=[p.x,p.y,1,1];o.aE(O,O,this.pixelMatrixInverse),o.aE(q,q,this.pixelMatrixInverse);const H=q[3];o.cu(O,O,1/O[3]),o.cu(q,q,1/H);const Y=O[2],te=q[2];return{p0:O,p1:q,t:Y===te?0:(L-Y)/(te-Y)}}screenPointToMercatorRay(p){const j=[p.x,p.y,0,1],L=[p.x,p.y,1,1];return o.aE(j,j,this.pixelMatrixInverse),o.aE(L,L,this.pixelMatrixInverse),o.cu(j,j,1/j[3]),o.cu(L,L,1/L[3]),j[2]=o.bU(j[2],this._center.lat)*this.worldSize,L[2]=o.bU(L[2],this._center.lat)*this.worldSize,o.cu(j,j,1/this.worldSize),o.cu(L,L,1/this.worldSize),new o.az([j[0],j[1],j[2]],o.ay([],o.ax([],L,j)))}rayIntersectionCoordinate(p){const{p0:j,p1:L,t:O}=p,q=o.bU(j[2],this._center.lat),H=o.bU(L[2],this._center.lat);return new o.ag(o.am(j[0],L[0],O)/this.worldSize,o.am(j[1],L[1],O)/this.worldSize,o.am(q,H,O))}pointCoordinate(p,j=this._centerAltitude){return this.projection.pointCoordinate(this,p.x,p.y,j)}pointCoordinate3D(p,j){if(!this.elevation)return this.pointCoordinate(p,j);let L=this.projection.pointCoordinate3D(this,p.x,p.y);if(L)return new o.ag(L[0],L[1],L[2]);let O=0,q=this.horizonLineFromTop();if(p.y>q)return this.pointCoordinate(p,j);const H=.02*q,Y=p.clone();for(let te=0;te<10&&q-O>H;te++){Y.y=o.am(O,q,.66);const de=this.projection.pointCoordinate3D(this,Y.x,Y.y);de?(q=Y.y,L=de):O=Y.y}return L?new o.ag(L[0],L[1],L[2]):this.pointCoordinate(p)}isPointAboveHorizon(p){return this.projection.isPointAboveHorizon(this,p)}isPointOnSurface(p){if(p.y<0||p.y>this.height||p.x<0||p.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(p);const j=this.pointCoordinate(p);return j.y>=0&&j.y<=1}_coordinatePoint(p,j){const L=j&&this.elevation?this.elevation.getAtPointOrZero(p,this._centerAltitude):this._centerAltitude,O=[p.x*this.worldSize,p.y*this.worldSize,L+p.toAltitude(),1];return o.aE(O,O,this.pixelMatrix),O[3]>0?new o.P(O[0]/O[3],O[1]/O[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:p,left:j}=this._edgeInsets,L=this.height-this._edgeInsets.bottom,O=this.width-this._edgeInsets.right,q=this.pointLocation3D(new o.P(j,p)),H=this.pointLocation3D(new o.P(O,p)),Y=this.pointLocation3D(new o.P(O,L)),te=this.pointLocation3D(new o.P(j,L));let de=Math.min(q.lng,H.lng,Y.lng,te.lng),pe=Math.max(q.lng,H.lng,Y.lng,te.lng),Ce=Math.min(q.lat,H.lat,Y.lat,te.lat),je=Math.max(q.lat,H.lat,Y.lat,te.lat);const Me=Math.pow(2,-this.zoom)/16*270,qe=this.projection.name==="globe"?1:4,$e=(nt,rt,pt,vt,ot)=>{const Ut=(nt+pt)/2,Tt=(rt+vt)/2,$t=new o.P(Ut,Tt),{lng:_t,lat:St}=this.pointLocation3D($t),Rt=Math.max(0,de-_t,Ce-St,_t-pe,St-je);de=Math.min(de,_t),pe=Math.max(pe,_t),Ce=Math.min(Ce,St),je=Math.max(je,St),(otMe)&&($e(nt,rt,Ut,Tt,ot+1),$e(Ut,Tt,pt,vt,ot+1))};if($e(j,p,O,p,1),$e(O,p,O,L,1),$e(O,L,j,L,1),$e(j,L,j,p,1),this.projection.name==="globe"){const[nt,rt]=o.cw(this);nt?(je=90,pe=180,de=-180):rt&&(Ce=-90,pe=180,de=-180)}return new o.aK(new o.aU(de,Ce),new o.aU(pe,je))}_getBoundsRectangular(p,j){const{top:L,left:O}=this._edgeInsets,q=this.height-this._edgeInsets.bottom,H=this.width-this._edgeInsets.right,Y=new o.P(O,L),te=new o.P(H,L),de=new o.P(H,q),pe=new o.P(O,q);let Ce=this.pointCoordinate(Y,p),je=this.pointCoordinate(te,p);const Me=this.pointCoordinate(de,j),qe=this.pointCoordinate(pe,j),$e=(nt,rt)=>(rt.y-nt.y)/(rt.x-nt.x);return Ce.y>1&&je.y>=0?Ce=new o.ag((1-qe.y)/$e(qe,Ce)+qe.x,1):Ce.y<0&&je.y<=1&&(Ce=new o.ag(-qe.y/$e(qe,Ce)+qe.x,0)),je.y>1&&Ce.y>=0?je=new o.ag((1-Me.y)/$e(Me,je)+Me.x,1):je.y<0&&Ce.y<=1&&(je=new o.ag(-Me.y/$e(Me,je)+Me.x,0)),new o.aK().extend(this.coordinateLocation(Ce)).extend(this.coordinateLocation(je)).extend(this.coordinateLocation(qe)).extend(this.coordinateLocation(Me))}_getBoundsRectangularTerrain(){const p=this.elevation;if(!p.visibleDemTiles.length||p.isUsingMockSource())return this._getBoundsRectangular(0,0);const j=p.visibleDemTiles.reduce((L,O)=>{if(O.dem){const q=O.dem.tree;L.min=Math.min(L.min,q.minimums[0]),L.max=Math.max(L.max,q.maximums[0])}return L},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(j.min*p.exaggeration(),j.max*p.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(p=!0){const j=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,L=this.height/2-j*(1-this._horizonShift);return p?Math.max(0,L):L}getMaxBounds(){return this.maxBounds}setMaxBounds(p){this.maxBounds=p,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,p&&(this.minLat=p.getSouth(),this.maxLat=p.getNorth(),this.minLng=p.getWest(),this.maxLng=p.getEast(),this.maxLngCe&&(Y=Ce-de),Ce-peMe&&(H=Me-te),Me-je{for(let Qt=0;Qt<16;Qt++)xs[Qt]=o.am(as[Qt],Os[Qt],Hs)})(Y,Y,te,o.cL(this.pitch>=t1?1:this.pitch/t1))}else Y=te;const de=o.cz([],te,H);let pe=o.cz([],Y,H);if(this.projection.isReprojectedInTileSpace){const St=this.locationCoordinate(this.center),Rt=o.b9([]);o.bx(Rt,Rt,[St.x*this.worldSize,St.y*this.worldSize,0]),o.aD(Rt,Rt,o.cA(this)),o.bx(Rt,Rt,[-St.x*this.worldSize,-St.y*this.worldSize,0]),o.aD(pe,pe,Rt),o.aD(de,de,Rt),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],pe,[this.worldSize,this.worldSize,this.worldSize/q,1]),this.projMatrix=pe,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),j){const St=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);St[8]=2*-p.x/this.width,St[9]=2*p.y/this.height,this.expandedFarZProjMatrix=o.cz([],St,H)}else this.expandedFarZProjMatrix=this.projMatrix;const Ce=o.b7([],Y);this.frustumCorners=o.cD.fromInvProjectionMatrix(Ce,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!j);const je=new Float32Array(16);o.b9(je),o.cC(je,je,[1,-1,1]),o.cE(je,je,this._pitch),o.ba(je,je,this.angle);const Me=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(Me);const qe=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;Me[8]=2*-p.x/this.width,Me[9]=2*(p.y+qe)/this.height,this.skyboxMatrix=o.aD(je,Me,je);const $e=this.point,nt=$e.x,rt=$e.y,pt=this.width%2/2,vt=this.height%2/2,ot=Math.cos(this.angle),Ut=Math.sin(this.angle),Tt=nt-Math.round(nt)+ot*pt+Ut*vt,$t=rt-Math.round(rt)+ot*vt+Ut*pt,_t=new Float64Array(pe);if(o.bx(_t,_t,[Tt>.5?Tt-1:Tt,$t>.5?$t-1:$t,0]),this.alignedProjMatrix=_t,pe=o.bb(),o.cC(pe,pe,[this.width/2,-this.height/2,1]),o.bx(pe,pe,[1,-1,0]),this.labelPlaneMatrix=pe,pe=o.bb(),o.cC(pe,pe,[1,-1,1]),o.bx(pe,pe,[-1,-1,0]),o.cC(pe,pe,[2/this.width,2/this.height,1]),this.glCoordMatrix=pe,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,de),this._calcFogMatrices(),this._distanceTileDataCache={},pe=o.b7(new Float64Array(16),this.pixelMatrix),!pe)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=pe,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const St=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(St,St,H),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=pe;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const p=this.cameraWorldSizeForFog,j=this.cameraPixelsPerMeter,L=this._camera.position,O=1/this.height/this._pixelsPerMercatorPixel,q=[p,p,j];o.bJ(q,q,O),o.bJ(L,L,-1),o.cG(L,L,q);const H=o.bb();o.bx(H,H,L),o.cC(H,H,q),this.mercatorFogMatrix=H,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(p,j,O)}_computeCameraPosition(p){const j=(p=p||this.pixelsPerMeter)/this.pixelsPerMeter,L=this._camera.forward(),O=this.point,q=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*j-p/this.worldSize*this._centerAltitude;return[O.x/this.worldSize-L[0]*q,O.y/this.worldSize-L[1]*q,p/this.worldSize*this._centerAltitude-L[2]*q]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(p){const j=this._maxCameraBoundsDistance()*Math.cos(this._pitch),L=this._camera.position[2],O=p[2];let q=1;this.projection.wrap&&(this.center=this.center.wrap()),O>0&&(q=Math.min((j-L)/O,1)),this._camera.position=o.bg([],this._camera.position,p,q),this._updateStateFromCamera()}_updateStateFromCamera(){const p=this._camera.position,j=this._camera.forward(),{pitch:L,bearing:O}=this._camera.getPitchBearing(),q=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,H=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),Y=Math.max((p[2]-q)/Math.cos(L),H),te=this._zoomFromMercatorZ(Y);o.bg(p,p,j,Y),this._pitch=o.aC(L,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(O,-Math.PI,Math.PI),this._setZoom(o.aC(te,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(p[0],p[1],p[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(p){return Math.pow(2,p)*this.tileSize}_mercatorZfromZoom(p){return this.cameraToCenterDistance/this._worldSizeFromZoom(p)}_minimumHeightOverTerrain(){const p=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(p)}_zoomFromMercatorZ(p){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,p)*this.tileSize))}zoomFromMercatorZAdjusted(p){let j=0,L=o.cv,O=0,q=1/0;for(;L-j>1e-6&&L>j;){const H=j+.5*(L-j),Y=this.tileSize*Math.pow(2,H),te=this.getCameraToCenterDistance(this.projection,H,Y),de=this.scaleZoom(te/(Math.max(0,p)*this.tileSize)),pe=Math.abs(H-de);pede||je.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(p,j){const L=o.ai(o.ax([],this._camera.position,p)),O=this._zoomFromMercatorZ(L)+j;return L-this._mercatorZfromZoom(O)}getCameraPoint(){if(this.projection.name==="globe"){const p=function([j,L,O],q){const H=[j,L,O,1];o.aE(H,H,q);const Y=H[3]=Math.max(H[3],1e-6);return H[0]/=Y,H[1]/=Y,H[2]/=Y,H}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(p[0],p[1])}{const p=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,p))}}getCameraToCenterDistance(p,j=this.zoom,L=this.worldSize){const O=o.cy(p,j,this.width,this.height,1024),q=p.pixelSpaceConversion(this.center.lat,L,O);let H=.5/Math.tan(.5*this._fov)*this.height*q;return this.isOrthographic&&(H=o.am(1,H,o.cL(this.pitch>=t1?1:this.pitch/t1))),H}getWorldToCameraMatrix(){const p=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(p,p,this.globeMatrix),p}getFrustum(p){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,p,this.projection.zAxisUnit==="meters")}}const Mc=(E,p)=>{if(p>0&&E.terrain&&o.w("Cutoff is currently disabled on terrain"),p<=0||E.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const j=E.transform,L=j.pitch,O=j.isLODDisabled(!1)?60:30;if(L0,uniformValues:{u_cutoff_params:[j._nearZ,j._farZ,(pe-j._nearZ)/q,(pe-je-j._nearZ)/q]}}},Qy=2048;class _5{constructor(p,j){this.aabb=p,this.lastCascade=j}}class YB{add(p,j){const L=this.receivers[p.key];L!==void 0?(L.aabb.min[0]=Math.min(L.aabb.min[0],j.min[0]),L.aabb.min[1]=Math.min(L.aabb.min[1],j.min[1]),L.aabb.min[2]=Math.min(L.aabb.min[2],j.min[2]),L.aabb.max[0]=Math.max(L.aabb.max[0],j.max[0]),L.aabb.max[1]=Math.max(L.aabb.max[1],j.max[1]),L.aabb.max[2]=Math.max(L.aabb.max[2],j.max[2])):this.receivers[p.key]=new _5(j,null)}clear(){this.receivers={}}get(p){return this.receivers[p.key]}computeRequiredCascades(p,j,L){const O=o.cU.fromPoints(p.points);let q=0;for(const H in this.receivers){const Y=this.receivers[H];if(!Y||!O.intersectsAabb(Y.aabb))continue;Y.aabb.min=O.closestPoint(Y.aabb.min),Y.aabb.max=O.closestPoint(Y.aabb.max);const te=Y.aabb.getCorners();for(let de=0;de1||je[1]<-1||je[1]>1){pe=!1;break}}if(Y.lastCascade=de,q=Math.max(q,de),pe)break}}return q+1}}class k2{constructor(p){this.painter=p,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new YB,this._depthMode=new $r(p.context.gl.LEQUAL,$r.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 p of this._cascades)p.texture.destroy(),p.framebuffer.destroy();this._cascades=[]}updateShadowParameters(p,j){const L=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!j||!j.properties)return;const O=j.properties.get("shadow-intensity"),q=j.properties.get("shadow-draw-before-layer");if(!j.shadowsEnabled()||O<=0)return;let H=-1,Y=0;for(const rt of L.style.order){const pt=L.style._mergedLayers[rt];pt.hasShadowPass()&&!pt.isHidden(p.zoom)&&(H=Y),!q||q!==rt&&q!==pt.slot||(this._drawShadowAfterLayer=Y>0?Y-1:0),Y+=1}if(this._enabled=H>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=H);const te=L.context,de=Qy,pe=Qy;if(this._cascades.length===0||Qy!==this._cascades[0].texture.size[0]){this._cascades=[];for(let rt=0;rt<2;++rt){const pt=te.gl,vt=te.createFramebuffer(de,pe,0,"texture"),ot=new o.T(te,{width:de,height:pe,data:null},pt.DEPTH_COMPONENT16);vt.depthAttachment.set(ot.texture),this._cascades.push({framebuffer:vt,texture:ot,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=ZB(j);let Ce=0;if(p.elevation){const rt=p.elevation,pt=[1e4,-1e4];rt.visibleDemTiles.filter(vt=>vt.dem).forEach(vt=>{const ot=vt.dem.tree;pt[0]=Math.min(pt[0],ot.minimums[0]),pt[1]=Math.max(pt[1],ot.maximums[0])}),pt[0]!==1e4&&(Ce=(pt[1]-pt[0])*rt.exaggeration())}const je=1.5*p.cameraToCenterDistance,Me=3*je,qe=new Float64Array(16);for(let rt=0;rt=0)return{};const q=function(te,de,pe){const Ce=pe/(1<0&&(o.cT(q[1],q[1],[O[0]*H,0,0]),o.cT(q[2],q[2],[O[0]*H,0,0])),O[1]<0?(o.cT(q[0],q[0],[0,O[1]*H,0]),o.cT(q[1],q[1],[0,O[1]*H,0])):O[1]>0&&(o.cT(q[2],q[2],[0,O[1]*H,0]),o.cT(q[3],q[3],[0,O[1]*H,0]));const Y={};return Y.vertices=q,Y.planes=[w5(q[1],q[0],q[4]),w5(q[2],q[1],q[5]),w5(q[3],q[2],q[6]),w5(q[0],q[3],q[7])],Y}addShadowReceiver(p,j,L){this._receivers.add(p,o.cU.fromTileIdAndHeight(p,j,L))}getMaxCascadeForTile(p){const j=this._receivers.get(p);return j&&j.lastCascade?j.lastCascade:0}}function w5(E,p,j){const L=o.ax([],j,p),O=o.ax([],E,p),q=o.bh([],L,O),H=o.ai(q);return H===0?[0,0,1,0]:(o.bJ(q,q,1/H),[q[0],q[1],q[2],-o.bi(q,p)])}function ZB(E){const p=E.properties.get("direction"),j=o.cP(p.x,p.y,p.z);j[2]=o.aC(j[2],0,75);const L=o.cR([j[0],j[1],j[2]]);return o.cQ(L.x,L.y,L.z)}function up(E,p,j){const L=p.properties.get("color-use-theme")==="none",O=p.properties.get("color"),q=p.properties.get("intensity"),H=p.properties.get("direction"),Y=[H.x,H.y,H.z],te=j.properties.get("color-use-theme")==="none",de=j.properties.get("color"),pe=j.properties.get("intensity"),Ce=Math.max(o.bi([0,0,1],Y),0),je=[0,0,0];o.bJ(je,de.toPremultipliedRenderColor(te?null:E.getLut(p.scope)).toArray01Linear().slice(0,3),pe);const Me=[0,0,0];return o.bJ(Me,O.toPremultipliedRenderColor(L?null:E.getLut(j.scope)).toArray01Linear().slice(0,3),Ce*q),o.cW([je[0]>0?je[0]/(je[0]+Me[0]):0,je[1]>0?je[1]/(je[1]+Me[1]):0,je[2]>0?je[2]/(je[2]+Me[2]):0])}function S2(E,p,j,L,O,q){const H=E.zoom,Y=E.scale,te=E.worldSize,de=1/te,pe=E.aspect,Ce=Math.sqrt(1+pe*pe)*Math.tan(.5*E.fovX),je=Ce*Ce,Me=L-j,qe=L+j;let $e,nt;je>Me/qe?($e=L,nt=L*Ce):($e=.5*qe*(1+je),nt=.5*Math.sqrt(Me*Me+2*(L*L+j*j)*je+qe*qe*je*je));const rt=E.projection.pixelsPerMeter(E.center.lat,te),pt=E._camera.getCameraToWorldMercator(),vt=[0,0,-$e*de];o.ah(vt,vt,pt);let ot=nt*de;const Ut=function(ks){return ks[0]/=Y,ks[1]/=Y,ks[2]=o.bU(ks[2],E._center.lat),ks},Tt=E._edgeInsets;if(!(Tt.left===0&&Tt.top===0&&Tt.right===0&&Tt.bottom===0||Tt.left===Tt.right&&Tt.top===Tt.bottom)){const ks=E._camera.getWorldToCamera(E.worldSize,E.projection.zAxisUnit==="meters"?rt:1),cr=E._camera.getCameraToClipPerspective(E._fov,E.width/E.height,j,L);cr[8]=2*-E.centerOffset.x/E.width,cr[9]=2*E.centerOffset.y/E.height;const Js=new Float64Array(16);o.cz(Js,cr,ks);const er=new Float64Array(16);o.b7(er,Js);const Us=o.cl.fromInvProjectionMatrix(er,te,H,!0);for(const Br of Us.points){const Kr=Ut(Br);ot=Math.max(ot,o.bK(o.cV([],vt,Kr)))}}ot*=O/(O-1);const $t=Math.acos(p[2]),_t=Math.atan2(-p[0],-p[1]),St=new j2;St.position=vt,St.setPitchBearing($t,_t);const Rt=St.getWorldToCamera(te,rt),Zt=ot*te,qt=Math.min(E._mercatorZfromZoom(17)*te*-2,-2*Zt),xs=St.getCameraToClipOrthographic(-Zt,Zt,-Zt,Zt,qt,(Zt+q*rt)/p[2]),as=new Float64Array(16);o.aD(as,xs,Rt);const Os=o.cQ(Math.floor(1e6*vt[0])/1e6*te,Math.floor(1e6*vt[1])/1e6*te,0),Hs=.5*O,Qt=[0,0,0];o.ah(Qt,Os,as),o.bJ(Qt,Qt,Hs);const Ht=[Math.floor(Qt[0]),Math.floor(Qt[1]),Math.floor(Qt[2])],us=[0,0,0];o.ax(us,Qt,Ht),o.bJ(us,us,-1/Hs);const vs=new Float64Array(16);return o.b9(vs),o.bx(vs,vs,us),o.aD(as,vs,as),[as,Zt]}class rge extends o.E{constructor(p){super(),this.requestManager=p,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(p,j){return o.cX(this.requestManager.transformRequest(j,o.R.Model).url).then(L=>{const O=o.cY(L),q=new o.cZ(p,j,void 0,void 0,O);return q.computeBoundsAndApplyParent(),q}).catch(L=>{if(L&&L.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${p} from ${j}: ${L.message}`)))})}load(p,j,L={forceReload:!1}){this.models[j]||(this.models[j]={});const O=Object.keys(p),q=[],H=[];for(const Y of O){const te=p[Y];this.hasURLBeenRequested(te)&&!L.forceReload||(this.modelByURL[te]={modelId:Y,scope:j},q.push(this.loadModel(Y,te)),H.push(Y)),this.models[j][Y]||(this.models[j][Y]={model:null,numReferences:1})}this.numModelsLoading[j]=(this.numModelsLoading[j]||0)+H.length,Promise.allSettled(q).then(Y=>{for(let te=0;te{this.fire(new o.B(new Error(`Could not load models: ${Y.message}`)))})}isLoaded(){for(const p in this.numModelsLoading)if(this.numModelsLoading[p]>0)return!1;return!0}hasModel(p,j,L={exactIdMatch:!1}){return!!(L.exactIdMatch?this.getModel(p,j):this.getModelByURL(this.modelUris[j][p]))}getModel(p,j){return this.models[j]||(this.models[j]={}),this.models[j][p]?this.models[j][p].model:void 0}getModelByURL(p){if(!p)return null;const j=this.modelByURL[p];return j?this.models[j.scope][j.modelId].model:null}hasModelBeenAdded(p,j){return this.models[j]&&this.models[j][p]!==void 0}getModelURIs(p){return this.modelUris[p]||{}}addModel(p,j,L){this.models[L]||(this.models[L]={}),this.modelUris[L]||(this.modelUris[L]={});const O=this.requestManager.normalizeModelURL(j);if((this.hasModel(p,L,{exactIdMatch:!0})||this.hasModelBeenAdded(p,L))&&this.modelUris[L][p]===O)this.models[L][p].numReferences++;else if(this.hasURLBeenRequested(O)){const{scope:q,modelId:H}=this.modelByURL[O];this.models[q][H].numReferences++}else this.modelUris[L][p]=O,this.load({[p]:this.modelUris[L][p]},L)}addModelURLs(p,j){this.models[j]||(this.models[j]={}),this.modelUris[j]||(this.modelUris[j]={});const L=this.modelUris[j];for(const O in p)L[O]=this.requestManager.normalizeModelURL(p[O])}reloadModels(p){this.load(this.modelUris[p],p,{forceReload:!0})}addModelsFromBucket(p,j){this.models[j]||(this.models[j]={}),this.modelUris[j]||(this.modelUris[j]={});const L={};for(const O of p)this.hasModel(O,j,{exactIdMatch:!0})||this.hasURLBeenRequested(O)?this.models[j][O].numReferences++:this.modelUris[j][O]&&!this.hasURLBeenRequested(O)?L[O]=this.modelUris[j][O]:!this.hasURLBeenRequested(O)&&o.c_(O,!1)&&(this.modelUris[j][O]=this.requestManager.normalizeModelURL(O),L[O]=this.modelUris[j][O]);this.load(L,j)}hasURLBeenRequested(p){return this.modelByURL[p]!==void 0}removeModel(p,j,L=!1,O=!1){if(this.models[j]&&this.models[j][p]&&(this.models[j][p].numReferences--,this.models[j][p].numReferences===0||O)){const q=this.modelUris[j][p];L||delete this.modelUris[j][p],delete this.modelByURL[q];const H=this.models[j][p].model;if(!H)return;delete this.models[j][p],H.destroy()}}destroy(){for(const p of Object.keys(this.models))for(const j of Object.keys(this.models[p])){const L=this.models[p][j].model;delete this.models[p][j],L&&L.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(p){return this.models[p]||(this.models[p]={}),Object.keys(this.models[p])}upload(p,j){this.models[j]||(this.models[j]={});for(const L in this.models[j])this.models[j][L].model&&this.models[j][L].model.upload(p.context)}}const OL=o.a8.colorTheme,s_=new o.ab({data:new o.ac(OL.data)});function XB(E){if(!E.metadata||!E.metadata.content_area)return;const p=o.o.devicePixelRatio,{left:j,top:L,width:O,height:q}=E.metadata.content_area,H=j*p,Y=L*p;return[H,Y,H+O*p,Y+q*p]}function C2(E){if(E)return E.map(([p,j])=>[p*o.o.devicePixelRatio,j*o.o.devicePixelRatio])}class FL{constructor(p,j,L){this.id=p,this.scope=j,this.sourceCache=L,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(p){this.missingRequests.has(p.name)||this.pendingRequests.has(p.name)||this.pendingRequests.add(p.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const p=new Map;if(!this.sourceCache.loaded())return p;const j=this.sourceCache.getVisibleCoordinates();if(j.length===0)return p;const L=this.sourceCache.getSource();if(!(L instanceof Im))return p;const O=j.map(H=>this.sourceCache.getTile(H)),q=L.getImages(O,Array.from(this.pendingRequests));for(const[H,Y]of q)p.set(o.I.from({name:H,iconsetId:this.id}),Y),this.pendingRequests.delete(H);for(const H of this.pendingRequests)this.missingRequests.add(H);return this.pendingRequests.clear(),p}}class Jy{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(p,j,L,O,q){if(Lte*this._hysteresisRatio&&(H=this._previousClosestBuildingId):de&&!H&&(H=this._previousClosestBuildingId),this._previousClosestBuildingId=H,H}_calculateDistance(p,j){if(!j.center)return Number.MAX_VALUE;const L=p.lat-j.center[1],O=p.lng-j.center[0];return L*L+O*O}_isBuildingVisible(p,j,L){if(!L)return!1;for(const O of p.floorIds){const q=p.floors[O];if(!q.geometry)continue;const H=q.geometry;if(H.type==="Polygon"){const Y=this._convertRingToPoints(H.coordinates[0]);if(o.bw(Y,L))return!0}else if(H.type==="MultiPolygon"){const Y=this._convertMultiPolygonToPoints(H.coordinates);if(o.d0(L,Y))return!0}}return!1}_convertRingToPoints(p){return p.map(j=>new o.P(j[0],j[1]))}_convertMultiPolygonToPoints(p){return p.map(j=>j.length===0?[]:j[0].map(L=>new o.P(L[0],L[1])))}}class nge extends o.E{constructor(p){super(),this._style=p,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Jy,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(p){p===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=p,this._recalculateActiveFloors())}setActiveFloorsVisibility(p){this._updateActiveFloors(p),this._updateIndoorSelector()}setIndoorData(p){let j=!1;for(const[L,O]of Object.entries(p.buildings))if(this._buildings[L])for(const q of O.floorIds)this._buildings[L].floorIds.add(q),this._buildings[L].floors[q]?this._mergeFloors(this._buildings[L].floors[q],O.floors[q]):(this._buildings[L].floors[q]=O.floors[q],j=!0);else this._buildings[L]=O,j=!0;j&&this._recalculateActiveFloors()}getIndoorTileOptions(p,j){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(p,j),indoorState:this._indoorState}:null}getControlState(){const p=this._buildings,j=this._closestBuildingId,L=j&&p?p[j]:void 0;if(!L)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let O=null;for(const H of L.floorIds)if(this._activeFloors&&this._activeFloors.has(H)){O=H;break}const q=Array.from(L.floorIds).map(H=>({id:H,name:L.floors[H].name,zIndex:L.floors[H].zIndex})).sort((H,Y)=>Y.zIndex-H.zIndex).filter((H,Y,te)=>Y===0||H.zIndex!==te[Y-1].zIndex);return{selectedFloorId:O,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:q}}_updateUI(){this._initialLoadDone=!0;const p=this._style.map.transform,j=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,p.center,p.zoom,p.getBounds(),this._makeViewportPolygon());if(j!==this._closestBuildingId){const L=this._closestBuildingId;this._closestBuildingId=j,this._onBuildingTransition(L,j),this._updateIndoorSelector()}}_onBuildingTransition(p,j){if(!this._indoorState)return;!j&&p?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!j&&!p&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(p){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:p,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const p=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(j,L){if(j===L)return!0;if(!j||!L||j.size!==L.size)return!1;for(const O of j)if(!L.has(O))return!1;return!0})(p,this._activeFloors)||(this._activeFloors=p,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(p,j){j.geometry&&(p.geometry?(p.geometry.type==="Polygon"&&(p.geometry={type:"MultiPolygon",coordinates:[p.geometry.coordinates]}),j.geometry.type==="Polygon"?p.geometry.coordinates.push(j.geometry.coordinates):j.geometry.type==="MultiPolygon"&&p.geometry.coordinates.push(...j.geometry.coordinates)):p.geometry=j.geometry)}_makeViewportPolygon(){const p=this._style.map.transform,j=p.width,L=p.height;return[p.pointLocation(new o.P(0,0)),p.pointLocation(new o.P(j,0)),p.pointLocation(new o.P(j,L)),p.pointLocation(new o.P(0,L))].map(O=>new o.P(O.lng,O.lat))}}const s1=(E,p)=>xr(E,p&&p.filter(j=>j.identifier!=="source.canvas")),age=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"]),QB=o.aJ(qa,["setCenter","setZoom","setBearing","setPitch"]),BL=new Set(["background","sky","slot","custom"]),j5={version:8,layers:[],sources:{}},zL={duration:300,delay:0};class Cf extends o.E{constructor(p,j={}){if(super(),this.map=p,this.scope=j.scope||"",this.globalId=null,this.fragments=[],this.importDepth=j.importDepth||0,this.importsCache=j.importsCache||new Map,this.resolvedImports=j.resolvedImports||new Set,this.transition=Object.assign({},zL),this._buildingIndex=new Zv(this),this.crossTileSymbolIndex=new t_,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=j.styleChanges||new _e,this._hasDataDrivenEmissive=!1,this.indoorManager=new nge(this),this.dispatcher=j.dispatcher?j.dispatcher:new xt(jt(),this),this.map.painter&&this.map.painter.context){const O=this.map.painter.context.maxUniformBufferBindings,q=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:O,maxUniformBlockSizeDwords:q,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}j.imageManager?this.imageManager=j.imageManager:(this.imageManager=new ns(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=j.glyphManager?j.glyphManager:new o.d2(p._requestManager,j.localFontFamily?o.d3.all:j.localIdeographFontFamily?o.d3.ideographs:o.d3.none,j.localFontFamily||j.localIdeographFontFamily,j.useServerFontComposition),j.modelManager?this.modelManager=j.modelManager:(this.modelManager=new rge(p._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=j.configOptions?j.configOptions:new Map,this._configDependentLayers=j.configDependentLayers?j.configDependentLayers:new Set,this._indoorDependentLayers=j.indoorDependentLayers?j.indoorDependentLayers:new Set,this._config=j.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:j.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=j.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const L=this;this._rtlTextPluginCallback=Cf.registerForPluginStateChange(O=>{L.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:O.pluginStatus,pluginURL:O.pluginURL},(q,H)=>{if(o.d6(q),H&&H.every(Y=>Y))for(const Y in L._sourceCaches){const te=L._sourceCaches[Y],de=te.getSource().type;de!=="vector"&&de!=="geojson"||te.reload()}})}),this.on("data",O=>{if(O.dataType!=="source"||O.sourceDataType!=="metadata")return;const q=this.getOwnSource(O.sourceId);if(q&&q.vectorLayerIds)for(const H in this._layers){const Y=this._layers[H];Y.source===q.id&&this._validateLayer(Y)}})}load(p){return p?(typeof p=="string"?this.loadURL(p):this.loadJSON(p),this):this}_getGlobalId(p){if(!p)return null;if(typeof p=="string"){if(o.e(p))return p;const j=o.d7(p);if(!j.startsWith("http"))try{return new URL(j,location.href).toString()}catch{return j}return j}return`json://${o.d8(JSON.stringify(p))}`}_diffStyle(p,j,L){this.globalId=this._getGlobalId(p);const O=(q,H)=>{try{H(null,this.setState(q,L))}catch(Y){H(Y,!1)}};if(typeof p=="string"){const q=this.map._requestManager.normalizeStyleURL(p),H=this.map._requestManager.transformRequest(q,o.R.Style);o.m(H,(Y,te)=>{Y?this.fire(new o.B(Y)):te&&O(te,j)})}else typeof p=="object"&&O(p,j)}loadURL(p,j={}){this.fire(new o.C("dataloading",{dataType:"style"}));const L=typeof j.validate=="boolean"?j.validate:!o.e(p);this.globalId=this._getGlobalId(p),p=this.map._requestManager.normalizeStyleURL(p,j.accessToken),this.resolvedImports.add(p);const O=this.importsCache.get(p);if(O)return this._load(O,L);const q=this.map._requestManager.transformRequest(p,o.R.Style);this._request=o.m(q,(H,Y)=>{if(this._request=null,H)this.fire(new o.B(H));else if(Y)return this.importsCache.set(p,Y),this._load(Y,L)})}loadJSON(p,j={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(p),this._request=o.o.frame(()=>{this._request=null,this._load(p,j.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(j5,!1)}_loadImports(p,j,L){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const O=[];for(const q of p){const H=this._createFragmentStyle(q),Y=new Promise(pe=>{H.once("style.import.load",pe),H.once("error",pe)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(O.push(Y),this.resolvedImports.has(q.url)){H.loadEmpty();continue}const te=q.data||this.importsCache.get(q.url);te?(q.data?(H.fire(new o.C("dataloading",{dataType:"style"})),H.globalId=H._getGlobalId(te),queueMicrotask(()=>H._load(te,j))):H.loadJSON(te,{validate:j}),this._isInternalStyle(te)&&(H.globalId=null)):q.url?H.loadURL(q.url,{validate:j}):H.loadEmpty();const de={style:H,id:q.id,config:q.config};if(L){const pe=this.fragments.findIndex(({id:Ce})=>Ce===L);this.fragments=this.fragments.slice(0,pe).concat(de).concat(this.fragments.slice(pe))}else this.fragments.push(de)}return Promise.allSettled(O)}getImportGlobalIds(p=this,j=new Set){for(const L of p.fragments)L.style.globalId&&j.add(L.style.globalId),this.getImportGlobalIds(L.style,j);return[...j.values()]}_createFragmentStyle(p){const j=this.scope?o.F(p.id,this.scope):p.id;let L;const O=this._initialConfig&&this._initialConfig[j];(p.config||O)&&(L=Object.assign({},p.config,O));const q=new Cf(this.map,{scope:j,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:L,configOptions:this.options,colorThemeOverride:p["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return q.setEventedParent(this.map,{style:q}),q}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(p){return this.isRootStyle()&&(p.fragment||!!p.schema&&p.fragment!==!1)}_load(p,j){if(this._isInternalStyle(p)){const q=Object.assign({},j5,{imports:[{id:"basemap",data:p,url:""}]},p.center?{center:p.center}:{},p.bearing?{bearing:p.bearing}:{},p.pitch?{pitch:p.pitch}:{},p.zoom?{zoom:p.zoom}:{},p.light?{light:p.light}:{});return this._importedAsBasemap=!0,void this._load(q,j)}if(this.updateConfig(this._config,p.schema),j&&s1(this,Gt(p)))return;this._loaded=!0;for(const q in p.sources)this.addSource(q,p.sources[q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(p);const L=()=>{if(p.iconsets)for(const te in p.iconsets)this.addIconset(te,p.iconsets[te]);p.sprite?this._loadIconset(p.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&p.glyphs&&this.glyphManager.setURL(p.glyphs);const q=Tg(this.stylesheet.layers);if(this._order=q.map(te=>te.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 te=this.stylesheet.lights[0];this.light=new Rr(te.properties,te.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Rr(this.stylesheet.light)),this._layers={};for(const te of q){const de=o.de(te,this.scope,this._styleColorTheme.lut,this.options);de.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(de.fqid),de.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(de.fqid),this._hasAppearances=this._hasAppearances||de.getAppearances().length!==0,de.setEventedParent(this,{layer:{id:de.id}}),this._layers[de.id]=de;const pe=this.getOwnLayerSourceCache(de),Ce=!!this.directionalLight&&this.directionalLight.shadowsEnabled();pe&&de.canCastShadows()&&Ce&&(pe.castsShadows=!0)}if(this.glyphManager.url){const te=new Set;for(const de in this._layers){const pe=this._layers[de];if(pe.type==="symbol"&&pe.layout){const Ce=pe.layout.get("text-font");Ce&&Ce.value&&Ce.value.kind==="constant"&&te.add(Ce.value.value.join(","))}}for(const de of te)this.glyphManager.prefetchRange(de,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const H=this.stylesheet.terrain;H&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(H,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 Y=this.isRootStyle();p.imports?this._loadImports(p.imports,j).then(()=>{this._reloadImports(),this.fire(new o.C(Y?"style.load":"style.import.load"))}).catch(te=>{this.fire(new o.B(new Error("Failed to load imports",te))),this.fire(new o.C(Y?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(Y?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const O=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(O){const q=this._evaluateColorThemeData(O);this._loadColorTheme(q).then(()=>{L()}).catch(H=>{o.w(`Couldn't load color theme from the stylesheet: ${H}`),L()})}else this._styleColorTheme.lut=null,L()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(p=>p.style.hasAppearances())}mergeAll(){let p,j,L,O,q,H,Y,te,de,pe;const Ce={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(je=>{if(je.stylesheet){if(je.light!=null&&(p=je.light),je.stylesheet.lights)for(const Me of je.stylesheet.lights)Me.type==="ambient"&&je.ambientLight!=null&&(j=je.ambientLight),Me.type==="directional"&&je.directionalLight!=null&&(L=je.directionalLight);O=this._prioritizeTerrain(O,je.terrain,je.stylesheet.terrain),je.stylesheet.fog&&je.fog!=null&&(q=je.fog),je.stylesheet.snow&&je.snow!=null&&(H=je.snow),je.stylesheet.rain&&je.rain!=null&&(Y=je.rain),je.stylesheet.camera!=null&&(pe=je.stylesheet.camera),je.stylesheet.projection!=null&&(te=je.stylesheet.projection),je.stylesheet.transition!=null&&(de=je.stylesheet.transition),Ce[je.scope]=je._styleColorTheme}}),this.light=p,this.ambientLight=j,this.directionalLight=L,this.fog=q,this.snow=H,this.rain=Y,this._styleColorThemeForScope=Ce,O===null?delete this.terrain:this.terrain=O,this.camera=pe||{"camera-projection":"perspective"},this.projection=te||{name:"mercator"},this.transition=Object.assign({},zL,de),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(p){const j=L=>{for(const O of L.fragments)j(O.style);p(L)};j(this)}_prioritizeTerrain(p,j,L){const O=p&&p.drapeRenderMode===0;return L===null?j&&j.drapeRenderMode===0?j:O?p:null:j!=null&&(!p||O||j&&j.drapeRenderMode===1)?j:p}mergeTerrain(){let p;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(j=>{p=this._prioritizeTerrain(p,j.terrain,j.stylesheet.terrain)}),p===null?delete this.terrain:this.terrain=p}mergeProjection(){let p;this.forEachFragmentStyle(j=>{j.stylesheet.projection!=null&&(p=j.stylesheet.projection)}),this.projection=p||{name:"mercator"}}mergeSources(){const p={},j={},L={},O={};this.forEachFragmentStyle(q=>{for(const H in q._sourceCaches){const Y=o.F(H,q.scope);p[Y]=q._sourceCaches[H]}for(const H in q._otherSourceCaches){const Y=o.F(H,q.scope);j[Y]=q._otherSourceCaches[H]}for(const H in q._symbolSourceCaches){const Y=o.F(H,q.scope);L[Y]=q._symbolSourceCaches[H]}for(const H in q._fillExtrusionSourceCaches){const Y=o.F(H,q.scope);O[Y]=q._fillExtrusionSourceCaches[H]}}),this._mergedSourceCaches=p,this._mergedOtherSourceCaches=j,this._mergedSymbolSourceCaches=L,this._mergedFillExtrusionSourceCaches=O}mergeIndoor(){this.forEachFragmentStyle(p=>{if(p.stylesheet&&p.stylesheet.indoor)for(const j of Object.values(p.stylesheet.indoor)){const L=j,O=o.F(L.sourceId,p.scope);this._mergedIndoor[O]=new Set(L.sourceLayers||[])}})}mergeLayers(){const p={},j=[],L={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(H=>{for(const Y of H._order){const te=H._layers[Y];if(te.type==="slot"){const de=o.da(Y);if(p[de])continue;p[de]=[]}te.slot&&p[te.slot]?p[te.slot].push(te):j.push(te)}}),this._mergedOrder=[];let O=-1;const q=(H=[])=>{for(const Y of H)if(Y.type==="slot"){const te=o.da(Y.id);p[te]&&q(p[te]),this._mergedSlots.push(te)}else{const te=o.F(Y.id,Y.scope);this._mergedOrder.push(te),L[te]=Y,Y.is3D(!!this.terrain)&&(this._has3DLayers=!0,O=this._mergedOrder.length-1),Y.type==="circle"&&(this._hasCircleLayers=!0),Y.type==="symbol"&&(this._hasSymbolLayers=!0),Y.type==="clip"&&(this._clipLayerPresent=!0)}};if(q(j),this._has3DLayers){const H={};for(let Y=0;YH[Y]-H[te])}this._mergedLayers=L,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(p){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,p),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(p){return p.data?function(j,L,O){const q=Object.assign({},L);for(const Y of Object.keys(OL))q[Y]===void 0&&(q[Y]=OL[Y].default);const H=new o.aa(s_,j,new Map(O));return H.setTransitionOrValue(q,O),H.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,p,this.options).get("data"):null}_loadColorTheme(p){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const j=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((L,O)=>{const q="data:image/png;base64,";if(!p||p.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void L();let H=p;H.startsWith(q)||(H=q+H);const Y=o.I.from("mapbox-reserved-lut"),te=new Image;te.src=H,te.onerror=()=>{this._styleColorTheme.lutLoading=!1,O(new Error("Failed to load image data"))},te.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==j)return void L();this._styleColorTheme.lutLoading=!1;const{width:de,height:pe,data:Ce}=o.o.getImageData(te);if(pe>32)return void O(new Error("The height of the image must be less than or equal to 32 pixels."));if(de!==pe*pe)return void O(new Error("The width of the image must be equal to the height squared."));this.getImage(Y)&&this.removeImage(Y),this.addImage(Y,{data:new o.q({width:de,height:pe},Ce),pixelRatio:1,sdf:!1,usvg:!1,version:0});const je=this.imageManager.getImage(Y,this.scope);je?(this._styleColorTheme.lut={image:je.data,data:p},L()):O(new Error("Missing LUT image."))}})}getLut(p){const j=this._styleColorThemeForScope[p];return j?j.lut:null}setProjection(p){p?this.stylesheet.projection=p: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(p){this._spriteRequest=function(j,L,O){let q,H,Y;const te=o.o.devicePixelRatio>1?"@2x":"";let de=o.m(L.transformRequest(L.normalizeSpriteURL(j,te,".json"),o.R.SpriteJSON),(je,Me)=>{de=null,Y||(Y=je,q=Me,Ce())}),pe=o.n(L.transformRequest(L.normalizeSpriteURL(j,te,".png"),o.R.SpriteImage),(je,Me)=>{pe=null,Y||(Y=je,H=Me,Ce())});function Ce(){if(Y)O(Y);else if(q&&H){const je=o.o.getImageData(H),Me={};for(const qe in q){const{width:$e,height:nt,x:rt,y:pt,sdf:vt,pixelRatio:ot,stretchX:Ut,stretchY:Tt,content:$t}=q[qe],_t=new o.q({width:$e,height:nt});o.q.copy(je,_t,{x:rt,y:pt},{x:0,y:0},{width:$e,height:nt},null),Me[qe]={data:_t,pixelRatio:ot!==void 0?ot:1,sdf:vt!==void 0&&vt,stretchX:Ut,stretchY:Tt,content:$t,usvg:!1,version:0}}O(null,Me)}}return{cancel(){de&&(de.cancel(),de=null),pe&&(pe.cancel(),pe=null)}}}(p,this.map._requestManager,(j,L)=>{if(this._spriteRequest=null,j)this.fire(new o.B(j));else if(L){const O=new Map;for(const q in L)O.set(o.I.from(q),L[q]);this.addImages(O)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(p,j){if(j.type==="sprite")return void this._loadSprite(j.url);const L=this.getOwnSourceCache(j.source);if(!L)return void this.fire(new o.B(new Error(`Source "${j.source}" as specified by iconset "${p}" does not exist and cannot be used as an iconset source`)));const O=L.getSource();if(O.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${j.source}" as specified by iconset "${p}" is not a "raster-array" source and cannot be used as an iconset source`)));O.partial=!1;const q=new FL(p,this.scope,L);this.imageManager.addImageProvider(q,this.scope)}removeIconset(p){this.imageManager.removeImageProvider(p,this.scope)}_loadIconset(p){if(!o.e(p)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(p);const j=this.map._spriteFormat==="auto";var L,O;this._spriteRequest=(O=(q,H)=>{if(this._spriteRequest=null,q)j?this._loadSprite(p):this.fire(new o.B(q));else if(H){const Y=new Map;for(const te in H)Y.set(o.I.from(te),H[te]);this.addImages(Y)}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((L=this.map._requestManager).transformRequest(L.normalizeIconsetURL(p),o.R.Iconset),(q,H)=>{if(q)return void O(q);const Y={},te=o.c$(new o.a$(H));for(const de of te.icons){const pe={version:1,pixelRatio:o.o.devicePixelRatio,content:XB(de),stretchX:de.metadata?C2(de.metadata.stretch_x_areas):void 0,stretchY:de.metadata?C2(de.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:de};Y[de.name]=pe}O(null,Y)}))}_validateLayer(p){const j=this.getOwnSource(p.source);if(!j)return;const L=p.sourceLayer;L&&(j.type==="geojson"||j.vectorLayerIds&&j.vectorLayerIds.indexOf(L)===-1)&&this.fire(new o.B(new Error(`Source layer "${L}" does not exist on source "${j.id}" as specified by style layer "${p.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const p in this._sourceCaches)if(!this._sourceCaches[p].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:p}of this.fragments)if(!p.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((p,j)=>{const L=this.fragments[j];return L&&L.style&&(p.data=L.style.serialize()),p})}_serializeSources(){const p={};for(const j in this._sourceCaches){const L=this._sourceCaches[j].getSource();p[L.id]||(p[L.id]=L.serialize())}return p}_serializeLayers(p){const j=[];for(const L of p){const O=this._layers[L];O&&O.type!=="custom"&&j.push(O.serialize())}return j}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 p in this._sourceCaches)if(this._sourceCaches[p].hasTransition())return!0;for(const p in this._layers)if(this._layers[p].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const p in this._mergedLayers){const j=this._mergedLayers[p];if(j._transitionablePaint&&j._transitionablePaint._values){const L=j._transitionablePaint._values["line-emissive-strength"];if(L&&L.value&&L.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(p){return p?this.order:this._mergedOrder}isLayerDraped(p){return!!this.terrain&&p.isDraped(this.getLayerSourceCache(p))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(p){const j=this.getOwnLayer(p);if(j)return j;this.fire(new o.B(new Error(`The layer '${p}' does not exist in the map's style.`)))}_checkSource(p){const j=this.getOwnSource(p);if(j)return j;this.fire(new o.B(new Error(`The source '${p}' does not exist in the map's style.`)))}precompilePrograms(p,j){const L=this.map.painter;if(L)for(let O=p.minzoom||0;O<(p.maxzoom||25.5);O++){const q=p.getProgramIds();if(q)for(const H of q){const Y=p.getDefaultProgramParams(H,j.zoom,this._styleColorTheme.lut);Y&&(L.style=this,this.fog&&(L._fogVisible=!0,Y.overrideFog=!0,L.getOrCreateProgram(H,Y)),L._fogVisible=!1,Y.overrideFog=!1,L.getOrCreateProgram(H,Y),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(Y.overrideRtt=!0,L.getOrCreateProgram(H,Y)))}}}update(p){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(p),this.directionalLight&&this.directionalLight.recalculate(p);const j=this.calculateLightsBrightness();p.brightness=j||0,j!==this._brightness&&(this._brightness=j,this.dispatcher.broadcast("setBrightness",j)),p.worldview!==this._worldview&&(this._worldview=p.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const L=this._changes.isDirty();let O=!1;if(this._changes.isDirty()){const te=this._changes.getLayerUpdatesByScope();for(const de in te){const{updatedIds:pe,removedIds:Ce}=te[de];(pe||Ce)&&(this._updateWorkerLayers(de,pe,Ce),O=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(p),this.light&&this.light.updateTransitions(p),this.ambientLight&&this.ambientLight.updateTransitions(p),this.directionalLight&&this.directionalLight.updateTransitions(p),this.fog&&this.fog.updateTransitions(p),this.snow&&this.snow.updateTransitions(p),this.rain&&this.rain.updateTransitions(p),this._changes.reset()}const q={};for(const te in this._mergedSourceCaches){const de=this._mergedSourceCaches[te];q[te]=de.used,de.used=!1,de.tileCoverLift=0}const H={};for(const te of this._mergedOrder){const de=this._mergedLayers[te];if((de.visibility!=="none"||de.hasTransition())&&de.recalculate(p,this._availableImages),!de.isHidden(p.zoom)){const pe=this.getLayerSourceCache(de);pe&&(pe.used=!0,pe.tileCoverLift=Math.max(pe.tileCoverLift,de.tileCoverLift()))}if(de.type==="fill-extrusion"){const pe=o.F(de.source,de.scope);if(pe in this._mergedFillExtrusionSourceCaches){const Ce=de.layout&&de.layout.get("source-max-zoom");if(Ce!=null){const je=H[pe];H[pe]=je==null?Ce:Math.min(je,Ce)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(de,p)}):this.precompilePrograms(de,p))}this._shouldPrecompile&&(this._precompileDone=!0);for(const te in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[te].setMaxzoomOverride(H[te]!=null?H[te]:null);this.terrain&&O&&this.mergeLayers();const Y=this.imageManager.getPendingImageProviders();for(const te of Y)te.sourceCache.used=!0;for(const te in q){const de=this._mergedSourceCaches[te];q[te]!==de.used&&de.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:de.getSource().id}))}this.light&&this.light.recalculate(p),this.terrain&&this.terrain.recalculate(p),this.fog&&this.fog.recalculate(p),this.snow&&this.snow.recalculate(p),this.rain&&this.rain.recalculate(p),this.z=p.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),L&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const p=this.imageManager.getPendingImageProviders();for(const j of p){const L=j.resolvePendingRequests(),O=this.getFragmentStyle(j.scope);O&&O.addImages(L)}}_updateTilesForChangedImages(){const p={};for(const j in this._mergedSourceCaches){const L=this._mergedSourceCaches[j].getSource().scope;p[L]=p[L]||this._changes.getUpdatedImages(L),p[L].length!==0&&this._mergedSourceCaches[j].reloadTilesForDependencies(["icons","patterns"],p[L])}for(const j in p)this._changes.resetUpdatedImages(j)}_updateWorkerLayers(p,j,L){const O=this.getFragmentStyle(p);O&&this.dispatcher.broadcast("updateLayers",{layers:j?O._serializeLayers(j):[],scope:p,removedIds:L||[],options:O.options})}setState(p,j){if(this._checkLoaded(),s1(this,Gt(p)))return!1;(p=o.d9(p)).layers=Tg(p.layers);const L=function(H,Y){if(!H)return[{command:qa.setStyle,args:[Y]}];let te=[];try{if(!o.b6(H.version,Y.version))return[{command:qa.setStyle,args:[Y]}];if(o.b6(H.center,Y.center)||te.push({command:qa.setCenter,args:[Y.center]}),o.b6(H.zoom,Y.zoom)||te.push({command:qa.setZoom,args:[Y.zoom]}),o.b6(H.bearing,Y.bearing)||te.push({command:qa.setBearing,args:[Y.bearing]}),o.b6(H.pitch,Y.pitch)||te.push({command:qa.setPitch,args:[Y.pitch]}),o.b6(H.sprite,Y.sprite)||te.push({command:qa.setSprite,args:[Y.sprite]}),o.b6(H.glyphs,Y.glyphs)||te.push({command:qa.setGlyphs,args:[Y.glyphs]}),o.b6(H.imports,Y.imports)||function(Me=[],qe=[],$e){qe=qe||[];const nt=(Me=Me||[]).map(Eg),rt=qe.map(Eg),pt=Me.reduce(Ag,{}),vt=qe.reduce(Ag,{}),ot=nt.slice();let Ut,Tt,$t,_t;for(Ut=0,Tt=0;Ut{Me.source&&de[Me.source]?te.push({command:qa.removeLayer,args:[Me.id]}):Ce.push(Me)});let je=H.terrain;je&&de[je.source]&&(te.push({command:qa.setTerrain,args:[void 0]}),je=void 0),te=te.concat(pe),o.b6(je,Y.terrain)||te.push({command:qa.setTerrain,args:[Y.terrain]}),function(Me,qe,$e){qe=qe||[];const nt=(Me=Me||[]).map(Eg),rt=qe.map(Eg),pt=Me.reduce(Ag,{}),vt=qe.reduce(Ag,{}),ot=nt.slice(),Ut=Object.create(null);let Tt,$t,_t,St,Rt,Zt,qt;for(Tt=0,$t=0;Tt!(H.command in QB));if(L.length===0)return!1;const O=L.filter(H=>!(H.command in age));if(O.length>0)throw new Error(`Unimplemented: ${O.map(H=>H.command).join(", ")}.`);const q=[];return L.forEach(H=>{q.push(this[H.command](...H.args))}),j&&Promise.all(q).then(j).catch(j),this.stylesheet=p,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(p){if(p.size===0)return this;for(const[j,L]of p.entries()){if(this.getImage(j))return this.fire(new o.B(new Error(`An image with the name "${j.name}" already exists.`)));this.imageManager.addImage(j,this.scope,L),this._changes.updateImage(j,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(p,j){return this.getImage(p)?this.fire(new o.B(new Error(`An image with the name "${p.name}" already exists.`))):(this.imageManager.addImage(p,this.scope,j),this._changes.updateImage(p,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(p,j,L=!1){this.imageManager.updateImage(p,this.scope,j),L&&(this._changes.updateImage(p,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(p){return this.imageManager.getImage(p,this.scope)}removeImage(p){return this.getImage(p)?(this.imageManager.removeImage(p,this.scope),this._changes.updateImage(p,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(p){return this.modelManager.addModelURLs(p,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(p,j,L={}){return this._checkLoaded(),this._validate(qs,`models.${p}`,j,null,L)||(this.modelManager.addModel(p,j,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(p){return this.modelManager.hasModel(p,this.getActualScope())}removeModel(p){return this.hasModel(p)?(this.modelManager.removeModel(p,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(p,j,L={}){if(this._checkLoaded(),this.getOwnSource(p)!==void 0)throw new Error(`There is already a source with ID "${p}".`);if(!j.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(j).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(j.type)>=0&&this._validate(gr,`sources.${p}`,j,null,L))return;this.map&&this.map._collectResourceTiming&&(j.collectResourceTiming=!0);const O=Zb(p,j,this.dispatcher,this);O.scope=this.scope,O.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(O.id),source:O.serialize(),sourceId:O.id}));const q=H=>{const Y=(H===o.b4.Symbol?"symbol:":H===o.b4.FillExtrusion?"fill-extrusion:":"other:")+O.id,te=o.F(Y,this.scope),de=this._sourceCaches[Y]=new ku(te,O,H);H===o.b4.Symbol?this._symbolSourceCaches[O.id]=de:H===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[O.id]=de:this._otherSourceCaches[O.id]=de,de.onAdd(this.map)};q(o.b4.Other),j.type!=="vector"&&j.type!=="geojson"||(q(o.b4.Symbol),j.type==="vector"&&q(o.b4.FillExtrusion)),O.onAdd&&O.onAdd(this.map),L.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(p){this._checkLoaded();const j=this.getOwnSource(p);if(!j)throw new Error("There is no source with this ID");for(const O in this._layers)if(this._layers[O].source===p)return this.fire(new o.B(new Error(`Source "${p}" cannot be removed while layer "${O}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===p)return this.fire(new o.B(new Error(`Source "${p}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const O=Object.entries(this.stylesheet.iconsets).find(([q,H])=>H.type==="source"&&H.source===p);if(O)return this.fire(new o.B(new Error(`Source "${p}" cannot be removed while iconset "${O[0]}" is using it.`)))}const L=this.getOwnSourceCaches(p);for(const O of L){const q=o.da(O.id);delete this._sourceCaches[q],this._changes.discardSourceCacheUpdate(O.id),O.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:O.getSource().id})),O.setEventedParent(null),O.clearTiles()}return delete this._otherSourceCaches[p],delete this._symbolSourceCaches[p],delete this._fillExtrusionSourceCaches[p],this.mergeSources(),j.setEventedParent(null),j.onRemove&&j.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(p,j){this._checkLoaded(),this.getOwnSource(p).setData(j),this._changes.setDirty()}getOwnSource(p){const j=this.getOwnSourceCache(p);return j&&j.getSource()}getOwnSources(){const p=[];for(const j in this._otherSourceCaches){const L=this.getOwnSourceCache(j);L&&p.push(L.getSource())}return p}areTilesLoaded(){const p=this._mergedSourceCaches;for(const j in p){const L=p[j]._tiles;for(const O in L){const q=L[O];if(q.state!=="loaded"&&q.state!=="errored")return!1}}return!0}setLights(p){if(this._checkLoaded(),!p)return delete this.ambientLight,void delete this.directionalLight;const j=this._getTransitionParameters();for(const q of p){if(this._validate(Se,"lights",q))return;switch(q.type){case"ambient":if(this.ambientLight){const H=this.ambientLight;H.set(q),H.updateTransitions(j)}else this.ambientLight=new ir(q,ra(),this.scope,this.options);break;case"directional":if(this.directionalLight){const H=this.directionalLight;H.set(q),H.updateTransitions(j)}else this.directionalLight=new ir(q,qo(),this.scope,this.options)}}const L=Object.assign(j,{worldview:this.map.getWorldview()}),O=new o.ae(this.z||0,L);this.ambientLight&&this.ambientLight.recalculate(O),this.directionalLight&&this.directionalLight.recalculate(O),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const p=this.directionalLight,j=this.ambientLight;if(!p||!j)return;const L=je=>.2126*(je[0]<=.03928?je[0]/12.92:Math.pow((je[0]+.055)/1.055,2.4))+.7152*(je[1]<=.03928?je[1]/12.92:Math.pow((je[1]+.055)/1.055,2.4))+.0722*(je[2]<=.03928?je[2]/12.92:Math.pow((je[2]+.055)/1.055,2.4)),O=p.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),q=p.properties.get("intensity"),H=p.properties.get("direction"),Y=1-o.cP(H.x,H.y,H.z)[2]/90,te=L(O)*q*Y,de=j.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),pe=j.properties.get("intensity"),Ce=L(de)*pe;return Number(((te+Ce)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const p=[];return this.directionalLight&&p.push(this.directionalLight.get()),this.ambientLight&&p.push(this.ambientLight.get()),p}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(p){if(p==null||p===""&&this.isRootStyle())return this;if(o.db(p)){const j=o.dc(p),L=this.fragments.find(({id:q})=>q===j);if(!L)return;const O=o.da(p);return L.style.getFragmentStyle(O)}{const j=this.fragments.find(({id:L})=>L===p);return j?j.style:void 0}}setFeaturesetSelectors(p){if(!p)return;const j=(L,O="")=>`${L}::${O}`;this._featuresetSelectors={};for(const L in p){const O={},q=this._featuresetSelectors[L]=[];for(const H of p[L].selectors){if(H.featureNamespace){const te=this.getOwnLayer(H.layer);if(!te){o.w(`Layer is undefined for selector: ${H.layer}`);continue}const de=j(te.source,te.sourceLayer);if(de in O&&O[de]!==H.featureNamespace){o.w(`"featureNamespace ${H.featureNamespace} of featureset ${L}'s selector is not associated to the same source, skip this selector`);continue}O[de]=H.featureNamespace}let Y;if(H.properties)for(const te in H.properties){const de=o.X(H.properties[te]);de.result==="success"&&(Y=Y||{},Y[te]=de.value)}q.push({layerId:H.layer,namespace:H.featureNamespace,properties:Y,uniqueFeatureID:H._uniqueFeatureID})}}}getFeaturesetDescriptors(p){const j=this.getFragmentStyle(p);if(!j||!j.stylesheet.featuresets)return[];const L=[];for(const O in j.stylesheet.featuresets)L.push({featuresetId:O,importId:j.scope?j.scope:void 0});return L}getFeaturesetLayers(p,j){const L=this.getFragmentStyle(j),O=L.stylesheet.featuresets;if(!O||!O[p])return this.fire(new o.B(new Error(`The featureset '${p}' does not exist in the map's style and cannot be queried.`))),[];const q=[];for(const H of O[p].selectors){const Y=L.getOwnLayer(H.layer);Y&&q.push(Y)}return q}getConfigProperty(p,j){const L=this.getFragmentStyle(p);if(!L)return null;const O=o.F(j,L.scope),q=L.options.get(O),H=q?q.value||q.default:null;return H?H.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(p,j){const L=o.F(p,j);return this._mergedIndoor[L]}setIndoorData(p,j){this.indoorManager.setIndoorData(j)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(p,j,L){const O=this.getFragmentStyle(p);if(!O)return;const q=O.stylesheet.schema;if(!q||!q[j])return;const H=o.X(L);if(H.result!=="success")return void s1(this,H.value);const Y=H.value.expression,te=o.F(j,O.scope),de=O.options.get(te);if(!de)return;let pe;const{minValue:Ce,maxValue:je,stepValue:Me,type:qe,values:$e}=q[j],nt=o.X(q[j].default);nt.result==="success"&&(pe=nt.value.expression),pe?(this.options.set(te,Object.assign({},de,{value:Y,default:pe,minValue:Ce,maxValue:je,stepValue:Me,type:qe,values:$e})),this.updateConfigDependencies(j)):this.fire(new o.B(new Error(`No schema defined for the config option "${j}" in the "${p}" fragment.`)))}getConfig(p){const j=this.getFragmentStyle(p);if(!j)return null;const L=j.stylesheet.schema;if(!L)return null;const O={};for(const q in L){const H=o.F(q,j.scope),Y=j.options.get(H),te=Y?Y.value||Y.default:null;O[q]=te?te.serialize():null}return O}setConfig(p,j){const L=this.getFragmentStyle(p);L&&(L.updateConfig(j,L.stylesheet.schema),this.updateConfigDependencies())}getSchema(p){const j=this.getFragmentStyle(p);return j?j.stylesheet.schema:null}setSchema(p,j){const L=this.getFragmentStyle(p);L&&(L.stylesheet.schema=j,L.updateConfig(L._config,j),this.updateConfigDependencies())}updateConfig(p,j){if(this._config=p,p||j)if(j)for(const L in j){let O,q;const H=o.X(j[L].default);if(H.result==="success"&&(O=H.value.expression),p&&p[L]!==void 0){const je=o.X(p[L]);je.result==="success"&&(q=je.value.expression)}const{minValue:Y,maxValue:te,stepValue:de,type:pe,values:Ce}=j[L];if(O){const je=o.F(L,this.scope);this.options.set(je,{default:O,value:q,minValue:Y,maxValue:te,stepValue:de,type:pe,values:Ce})}else this.fire(new o.B(new Error(`No schema defined for config option "${L}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(p,j=()=>!0){for(const L of p){const O=this.getLayer(L);O&&j(O)&&(O.possiblyEvaluateVisibility(),this._updateLayer(O),this._changes.setDirty())}}updateConfigDependencies(p){this._updateLayers(this._configDependentLayers,j=>!p||j.expressionDependencies.configDependencies.has(p)),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(j=>{const L=j._styleColorTheme.colorThemeOverride?j._styleColorTheme.colorThemeOverride:j._styleColorTheme.colorTheme;if(L){const O=j._evaluateColorThemeData(L);(!j._styleColorTheme.lut&&O!==""||j._styleColorTheme.lut&&O!==j._styleColorTheme.lut.data)&&j.setColorTheme(L)}}),this._changes.setDirty()}addLayer(p,j,L={}){this._checkLoaded();const O=p.id;if(this._layers[O])return void this.fire(new o.B(new Error(`Layer with id "${O}" already exists on this map`)));let q;if(p.type==="custom"){if(s1(this,o.dd(p)))return;q=o.de(p,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof p.source=="object"&&(this.addSource(O,p.source),p=o.d9(p),p=Object.assign(p,{source:O})),this._validate(Ft,`layers.${O}`,p,{arrayIndex:-1},L))return;q=o.de(p,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(q),q.setEventedParent(this,{layer:{id:O}})}const H=o.F(q.source,q.scope);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(H),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(H);let Y=this._order.length;if(j){const Ce=this._order.indexOf(j);if(Ce===-1)return void this.fire(new o.B(new Error(`Layer with id "${j}" does not exist on this map.`)));q.slot&&q.slot!==this._layers[j].slot?o.w(`Layer with id "${j}" has a different slot. Layers can only be rearranged within the same slot.`):Y=Ce}this._order.splice(Y,0,O),this._handleLayerOrderChange(),this._layers[O]=q;const te=this.getOwnLayerSourceCache(q),de=!!this.directionalLight&&this.directionalLight.shadowsEnabled();te&&q.canCastShadows()&&de&&(te.castsShadows=!0);const pe=this._changes.getRemovedLayer(q);if(pe&&q.source&&te&&q.type!=="custom"){this._changes.discardLayerRemoval(q);const Ce=o.F(q.source,q.scope);pe.type!==q.type?this._changes.updateSourceCache(Ce,"clear"):(this._changes.updateSourceCache(Ce,"reload"),te.pause())}this._updateLayer(q),q.onAdd&&q.onAdd(this.map),q.scope=this.scope,this.mergeLayers()}moveLayer(p,j){this._checkLoaded();const L=this._checkLayer(p);if(!L||p===j)return;const O=this._order.indexOf(p);this._order.splice(O,1);let q=this._order.length;if(j){const H=this._order.indexOf(j);if(H===-1)return void this.fire(new o.B(new Error(`Layer with id "${j}" does not exist on this map.`)));L.slot&&L.slot!==this._layers[j].slot?o.w(`Layer with id "${j}" has a different slot. Layers can only be rearranged within the same slot.`):q=H}this._order.splice(q,0,p),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(p){this._checkLoaded();const j=this._checkLayer(p);if(!j)return;j.setEventedParent(null);const L=this._order.indexOf(p);this._order.splice(L,1),delete this._layers[p],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(j.fqid),this._indoorDependentLayers.delete(j.fqid),this._changes.removeLayer(j);const O=this.getOwnLayerSourceCache(j);if(O&&O.castsShadows){let q=!1;for(const H in this._layers)if(this._layers[H].source===j.source&&this._layers[H].canCastShadows()){q=!0;break}O.castsShadows=q}j.onRemove&&j.onRemove(this.map),this.mergeLayers()}getOwnLayer(p){return this._layers[p]}hasLayer(p){return p in this._mergedLayers}hasLayerType(p){for(const j in this._layers)if(this._layers[j].type===p)return!0;return!1}setLayerZoomRange(p,j,L){this._checkLoaded();const O=this._checkLayer(p);O&&(O.minzoom===j&&O.maxzoom===L||(j!=null&&(O.minzoom=j),L!=null&&(O.maxzoom=L),this._updateLayer(O)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(p,j){this._checkLoaded();const L=this._checkLayer(p);L&&L.slot!==j&&(L.slot=j,this._updateLayer(L))}setFilter(p,j,L={}){this._checkLoaded();const O=this._checkLayer(p);if(O&&!o.b6(O.filter,j))return j==null?(O.filter=void 0,void this._updateLayer(O)):void(this._validate(Wt,`layers.${O.id}.filter`,j,{layerType:O.type},L)||(O.filter=o.d9(j),this._updateLayer(O)))}getFilter(p){const j=this._checkLayer(p);if(j)return o.d9(j.filter)}setLayoutProperty(p,j,L,O={}){this._checkLoaded();const q=this._checkLayer(p);if(q&&!o.b6(q.getLayoutProperty(j),L)){if(L!=null&&(!O||O.validate!==!1)&&s1(q,Jt.call(Gt,{key:`layers.${p}.layout.${j}`,layerType:q.type,objectKey:j,value:L,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;q.setLayoutProperty(j,L),q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),this._updateLayer(q)}}setLayerProperty(p,j,L,O={}){this._checkLoaded();const q=this._checkLayer(p);q&&(j==="appearances"?(q.setAppearances(L),this._updateLayer(q)):q.isPaintProperty(j)?this.setPaintProperty(p,j,L,O):this.setLayoutProperty(p,j,L,O))}getLayoutProperty(p,j){const L=this._checkLayer(p);if(L)return L.getLayoutProperty(j)}setPaintProperty(p,j,L,O={}){this._checkLoaded();const q=this._checkLayer(p);if(!q||o.b6(q.getPaintProperty(j),L)||L!=null&&(!O||O.validate!==!1)&&s1(q,Vt.call(Gt,{key:`layers.${p}.paint.${j}`,layerType:q.type,objectKey:j,value:L,styleSpec:o.a8})))return;const H=q.setPaintProperty(j,L);q.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(q.fqid),q.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(q.fqid),H&&this._updateLayer(q),this._changes.updatePaintProperties(q)}getPaintProperty(p,j){const L=this._checkLayer(p);if(L)return L.getPaintProperty(j)}setFeatureState(p,j){if(this._checkLoaded(),"target"in p){if("featuresetId"in p.target){const{featuresetId:te,importId:de}=p.target,pe=this.getFragmentStyle(de),Ce=pe.getFeaturesetLayers(te);for(const{source:je,sourceLayer:Me}of Ce)pe.setFeatureState({id:p.id,source:je,sourceLayer:Me},j)}else if("layerId"in p.target){const{layerId:te}=p.target,de=this.getLayer(te);this.setFeatureState({id:p.id,source:de.source,sourceLayer:de.sourceLayer},j)}return}const L=p.source,O=p.sourceLayer,q=this._checkSource(L);if(!q)return;const H=q.type;if(H==="geojson"&&O)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(H==="vector"&&!O)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));p.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const Y=this.getOwnSourceCaches(L);for(const te of Y)te.setFeatureState(O,p.id,j)}removeFeatureState(p,j){if(this._checkLoaded(),"target"in p){if("featuresetId"in p.target){const{featuresetId:te,importId:de}=p.target,pe=this.getFragmentStyle(de),Ce=pe.getFeaturesetLayers(te);for(const{source:je,sourceLayer:Me}of Ce)pe.removeFeatureState({id:p.id,source:je,sourceLayer:Me},j)}else if("layerId"in p.target){const{layerId:te}=p.target,de=this.getLayer(te);this.removeFeatureState({id:p.id,source:de.source,sourceLayer:de.sourceLayer},j)}return}const L=p.source,O=this._checkSource(L);if(!O)return;const q=O.type,H=q==="vector"?p.sourceLayer:void 0;if(q==="vector"&&!H)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(j&&typeof p.id!="string"&&typeof p.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const Y=this.getOwnSourceCaches(L);for(const te of Y)te.removeFeatureState(H,p.id,j)}getFeatureState(p){if(this._checkLoaded(),"target"in p){let q;if("featuresetId"in p.target){const{featuresetId:H,importId:Y}=p.target,te=this.getFragmentStyle(Y),de=te.getFeaturesetLayers(H);for(const{source:pe,sourceLayer:Ce}of de){const je=te.getFeatureState({id:p.id,source:pe,sourceLayer:Ce});if(je&&!q)q=je;else if(!o.b6(q,je))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 p.target){const{layerId:H}=p.target,Y=this.getLayer(H);q=this.getFeatureState({id:p.id,source:Y.source,sourceLayer:Y.sourceLayer})}return q}const j=p.source,L=p.sourceLayer,O=this._checkSource(j);if(O){if(O.type!=="vector"||L)return p.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(j)[0].getFeatureState(L,p.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(p){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,p),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(p){p!==this._worldview&&(this._worldview=p,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const p=this.getTerrain(),j=p&&this.terrain&&this.terrain.scope===this.scope?p: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:j,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)},L=>L!==void 0)}_updateFilteredLayers(p){for(const j of Object.values(this._mergedLayers))p(j)&&this._updateLayer(j)}_updateLayer(p){this._changes.updateLayer(p);const j=this.getLayerSourceCache(p),L=o.F(p.source,p.scope),O=this._changes.getUpdatedSourceCaches();p.source&&!O[L]&&j&&j.getSource().type!=="raster"&&(this._changes.updateSourceCache(L,"reload"),j.pause()),p.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(p){const j=Y=>this._mergedLayers[Y].is3D(!!this.terrain),L=this.order,O={},q=[];for(let Y=L.length-1;Y>=0;Y--){const te=L[Y];if(j(te)){O[te]=Y;for(const de of p){const pe=de[te];if(pe)for(const Ce of pe)q.push(Ce)}}}q.sort((Y,te)=>te.intersectionZ-Y.intersectionZ);const H=[];for(let Y=L.length-1;Y>=0;Y--){const te=L[Y];if(j(te))for(let de=q.length-1;de>=0;de--){const pe=q[de].feature;if(pe.layer&&O[pe.layer.id]{if(BL.has(pe.type))return;const Ce=this.getOwnLayerSourceCache(pe),je=q[Ce.id]=q[Ce.id]||{sourceCache:Ce,layers:{},has3DLayers:!1};pe.is3D(!!this.terrain)&&(je.has3DLayers=!0),je.layers[pe.fqid]=je.layers[pe.fqid]||{styleLayer:pe,targets:[]},je.layers[pe.fqid].targets.push({filter:O})};if(j&&j.layers){if(!Array.isArray(j.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const pe of j.layers){const Ce=this._layers[pe];if(!Ce)return this.fire(new o.B(new Error(`The layer '${pe}' does not exist in the map's style and cannot be queried for features.`))),[];H(Ce)}}else for(const pe in this._layers)H(this._layers[pe]);const Y=this._queryRenderedFeatures(p,q,L),te=this._flattenAndSortRenderedFeatures(Y),de=[];for(const pe of te)o.dh(pe.layer.id)===this.scope&&de.push(pe);return de}queryRenderedFeatureset(p,j,L){let O;j&&!Array.isArray(j)&&j.filter&&(this._validate(Wt,"queryRenderedFeatures.filter",j.filter,null,j),O=o.dg(j.filter));const q="mock",H=[];if(j&&j.target)H.push(Object.assign({},j,{targetId:q,filter:O}));else{const pe=this.getFeaturesetDescriptors();for(const Ce of pe)H.push({targetId:q,filter:O,target:Ce});for(const{style:Ce}of this.fragments){const je=Ce.getFeaturesetDescriptors();for(const Me of je)H.push({targetId:q,filter:O,target:Me})}}const Y=this.queryRenderedTargets(p,H,L),te=[],de=new Set;for(const pe of Y)for(const Ce of pe.variants[q])Nu(Ce,pe,de)||te.push(new o.di(pe,Ce));return te}queryRenderedTargets(p,j,L){const O={},q=(Y,te,de,pe)=>{const Ce=O[te.id]=O[te.id]||{sourceCache:te,layers:{},has3DLayers:!1};if(Ce.layers[Y.fqid]=Ce.layers[Y.fqid]||{styleLayer:Y,targets:[]},Y.is3D(!!this.terrain)&&(Ce.has3DLayers=!0),!pe)return de.uniqueFeatureID=!1,void Ce.layers[Y.fqid].targets.push(de);Ce.layers[Y.fqid].targets.push(Object.assign({},de,{namespace:pe.namespace,properties:pe.properties,uniqueFeatureID:pe.uniqueFeatureID}))};for(const Y of j)if("featuresetId"in Y.target){const{featuresetId:te,importId:de}=Y.target,pe=this.getFragmentStyle(de);if(!pe||!pe._featuresetSelectors)continue;const Ce=pe._featuresetSelectors[te];if(!Ce){this.fire(new o.B(new Error(`The featureset '${te}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const je of Ce){const Me=pe.getOwnLayer(je.layerId);Me&&!BL.has(Me.type)&&q(Me,pe.getOwnLayerSourceCache(Me),Y,je)}}else if("layerId"in Y.target){const{layerId:te}=Y.target,de=this.getLayer(te);if(!de||BL.has(de.type))continue;q(de,this.getLayerSourceCache(de),Y)}const H=this._queryRenderedFeatures(p,O,L);return this._flattenAndSortRenderedFeatures(H)}_queryRenderedFeatures(p,j,L){const O=[],q=!!this.map._showQueryGeometry,H=Xo.createFromScreenPoints(p,L);for(const Y in j){const te=Cg(H,j[Y],this._availableImages,L,q,this.getActualScope());Object.keys(te).length&&O.push(te)}if(this.placement)for(const Y in j){if(j[Y].sourceCache._renderSourceType!==o.b4.Symbol)continue;const te=lp(H.screenGeometry,j[Y],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(te).length&&O.push(te)}return O}querySourceFeatures(p,j){const L=j&&j.filter;L&&this._validate(Wt,"querySourceFeatures.filter",L,null,j);let O=[];const q=this.getOwnSourceCaches(p);for(const H of q)O=O.concat(f2(H,j));return O}addSourceType(p,j,L){return Cf.getSourceType(p)?L(new Error(`A source type called "${p}" already exists.`)):(Cf.setSourceType(p,j),j.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:p,url:j.workerSourceURL},L):L(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(p,j,L={}){this._checkLoaded();const O=this.light.getLight();let q=!1;for(const Y in p)if(!o.b6(p[Y],O[Y])){q=!0;break}if(!q)return;const H=this._getTransitionParameters();this.light.setLight(p,j,L),this.light.updateTransitions(H)}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(p,j=1){if(this._checkLoaded(),!p)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),j===0&&delete this.terrain,p===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let L=p;const O=!("source"in p)||p.source==null;if(j===1){if(this.disableElevatedTerrain)return;if("source"in L&&typeof L.source=="object"){const Y="terrain-dem-src";this.addSource(Y,L.source),L=o.d9(L),L=Object.assign(L,{source:Y})}const q=Object.assign({},L),H={};if(this.terrain&&O){q.source=this.terrain.get().source;const Y=this.terrain?this.getFragmentStyle(this.terrain.scope):null;Y&&(H.style=Y.serialize())}if(this._validate(ze,"terrain",q,H))return}if(!this.terrain||this.terrain.scope!==this.scope&&!O||this.terrain&&j!==this.terrain.drapeRenderMode){if(!L)return;this._createTerrain(L,j),this.fire(new o.C("data",{dataType:"style"}))}else{const q=this.terrain,H=q.get();for(const Y of Object.keys(o.a8.terrain))!L.hasOwnProperty(Y)&&o.a8.terrain[Y].default&&(L[Y]=o.a8.terrain[Y].default);for(const Y in p)if(!o.b6(p[Y],H[Y])){q.set(p,this.options),this.stylesheet.terrain=p;const te=this._getTransitionParameters({duration:0});q.updateTransitions(te),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(p){const j=this.fog=new Ji(p,this.map.transform,this.scope,this.options);this.stylesheet.fog=j.get();const L=this._getTransitionParameters({duration:0});j.updateTransitions(L)}_createSnow(p){const j=this.snow=new no(p,this.map.transform,this.scope,this.options);this.stylesheet.snow=j.get();const L=this._getTransitionParameters({duration:0});j.updateTransitions(L)}_createRain(p){const j=this.rain=new ba(p,this.map.transform,this.scope,this.options);this.stylesheet.rain=j.get();const L=this._getTransitionParameters({duration:0});j.updateTransitions(L)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const p of this.map._markers)p._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(p){if(this._checkLoaded(),!p)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const j=this.fog;if(!o.b6(j.get(),p)){j.set(p,this.options),this.stylesheet.fog=j.get();const L=this._getTransitionParameters({duration:0});j.updateTransitions(L)}}else this._createFog(p);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(p){if(this._checkLoaded(),!p)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const j=this.snow;if(!o.b6(j.get(),p)){j.set(p,this.options),this.stylesheet.snow=j.get();const L=this._getTransitionParameters({duration:0});j.updateTransitions(L)}}else this._createSnow(p);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(p){if(this._checkLoaded(),!p)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const j=this.rain;if(!o.b6(j.get(),p)){j.set(p,this.options),this.stylesheet.rain=j.get();const L=this._getTransitionParameters({duration:0});j.updateTransitions(L)}}else this._createRain(p);this._markersNeedUpdate=!0}_reloadColorTheme(){const p=()=>{for(const O in this._layers)this._layers[O].lut=this._styleColorTheme.lut;for(const O in this._sourceCaches)this._sourceCaches[O].clearTiles()},j=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!j)return this._styleColorTheme.lut=null,void p();const L=this._evaluateColorThemeData(j);this._loadColorTheme(L).then(()=>{this.fire(new o.C("colorthemeset")),p()}).catch(O=>{o.w(`Couldn't set color theme: ${O}`)})}setColorTheme(p){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=p,this._reloadColorTheme()}setImportColorTheme(p,j){const L=this.getFragmentStyle(p);L&&(L._styleColorTheme.colorThemeOverride=j,L._reloadColorTheme())}_getTransitionParameters(p){return{now:o.o.now(),transition:Object.assign(this.transition,p)}}updateDrapeFirstLayers(){if(!this.terrain)return;const p=[],j=[];for(const L of this._mergedOrder)this.isLayerDraped(this._mergedLayers[L])?p.push(L):j.push(L);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...p),this._drapedFirstOrder.push(...j)}_createTerrain(p,j){const L=this.terrain=new rn(p,j,this.scope,this.options,this.map.getWorldview());j===1&&(this.stylesheet.terrain=p),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const O=this._getTransitionParameters({duration:0});L.updateTransitions(O)}_force3DLayerUpdate(){for(const p in this._layers){const j=this._layers[p];j.type==="fill-extrusion"&&this._updateLayer(j)}}_forceSymbolLayerUpdate(){for(const p in this._layers){const j=this._layers[p];j.type==="symbol"&&this._updateLayer(j)}}_validate(p,j,L,O,q={}){if(q&&q.validate===!1)return!1;const H=Object.assign({},this.serialize());return s1(this,p.call(Gt,Object.assign({key:j,style:H,value:L,styleSpec:o.a8},O)))}_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 p in this._mergedLayers)this._mergedLayers[p].setEventedParent(null);for(const p in this._mergedSourceCaches)this._mergedSourceCaches[p].clearTiles(),this._mergedSourceCaches[p].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(p){const j=this.getSourceCaches(p);for(const L of j)L.clearTiles()}clearSources(){for(const p in this._mergedSourceCaches)this._mergedSourceCaches[p].clearTiles()}clearLayers(){for(const p in this._mergedLayers){const j=this._mergedLayers[p];j._clear&&j._clear()}}reloadSource(p){const j=this.getSourceCaches(p);for(const L of j)L.resume(),L.reload()}reloadSources(){for(const p of this.getSources())p.reload&&p.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(p=>{p.modelManager.reloadModels(p.scope)})}updateSources(p){let j;this.directionalLight&&(j=ZB(this.directionalLight));const L=new Set,O=new Set,q=new Set;for(const H in this._mergedLayers){const Y=this._mergedLayers[H];Y.type==="building"?L.add(Y.source):Y.type==="raster"&&Y.paint&&Y.paint.get("raster-elevation-reference")==="ground"&&q.add(Y.source),Y.hasElevation()&&!O.has(Y.source)&&O.add(Y.source)}for(const H in this._mergedSourceCaches){const Y=this._mergedSourceCaches[H],te=O.has(Y._source.id);Y._isRasterElevatedOverTerrain=q.has(Y._source.id),L.has(Y._source.id)&&(Y._source.reparseOverscaled=!1),Y.update(p,void 0,void 0,j,te)}}_generateCollisionBoxes(){for(const p in this._sourceCaches){const j=this._sourceCaches[p];j.resume(),j.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new b2),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(p,j,L,O,q){this.pauseablePlacement||(this.pauseablePlacement=new b2);let H=!1,Y=!1;const te={},de={};for(const $e of this._mergedOrder){const nt=this._mergedLayers[$e];if(nt.type!=="symbol")continue;const rt=o.F(nt.source,nt.scope);let pt=te[rt];if(!pt){const ot=this.getLayerSourceCache(nt);if(!ot)continue;const Ut=ot.getRenderableIds(!0).map(Tt=>ot.getTileByID(Tt));de[rt]=Ut.slice(),pt=te[rt]=Ut.sort((Tt,$t)=>$t.tileID.overscaledZ-Tt.tileID.overscaledZ||(Tt.tileID.isLessThan($t.tileID)?-1:1))}const vt=this.crossTileSymbolIndex.addLayer(nt,pt,p.center.lng,p.projection);H=H||vt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const pe=!!(this.placement&&!p.equals(this.placement.transform)),Ce=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!q||this.placement.lastReplacementSourceUpdateTime!==q.updateTime)),je=pe||Ce||H,Me=(je||this.pauseablePlacement.isStale())&&L===0,qe=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),p.zoom)&&L!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Me||qe)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(p,this._mergedOrder,j,L,O,this.placement,this.fog&&p.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const $e=this.map.painter.maxFrontCutoffRawStart;if($e>0){const nt=180*p.pitch/Math.PI;if(nt>=15){const rt=Math.min(1,Math.max(0,(nt-15)/5)),pt=rt*rt*(3-2*rt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-pt)+$e*pt}}}if(this.pauseablePlacement.isDone()?je&&L!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,te,de,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),Y=!0),H&&this.pauseablePlacement.setStale()),Y||H){this._buildingIndex.onNewFrame(p.zoom);for(let $e=0;$eq===p.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${p.id}' already exists in the map's style.`)));if(!j)return L.push(p),this._loadImports([p],!0);const O=L.findIndex(({id:q})=>q===j);return O===-1&&this.fire(new o.B(new Error(`Import with id "${j}" does not exist on this map.`))),this.stylesheet.imports=L.slice(0,O).concat(p).concat(L.slice(O)),this._loadImports([p],!0,j)}updateImport(p,j){this._checkLoaded();const L=this.stylesheet.imports||[],O=this.getImportIndex(p);return O===-1?this:typeof j=="string"?(this.setImportUrl(p,j),this):(j.url&&j.url!==L[O].url&&this.setImportUrl(p,j.url),o.b6(j.config,L[O].config)||this.setImportConfig(p,j.config,j.data.schema),o.b6(j.data,L[O].data)||this.setImportData(p,j.data),this)}moveImport(p,j){this._checkLoaded();let L=this.stylesheet.imports||[];const O=this.getImportIndex(p);if(O===-1)return this;const q=this.getImportIndex(j);if(q===-1)return this;const H=L[O],Y=this.fragments[O];return L=L.filter(({id:te})=>te!==p),this.fragments=this.fragments.filter(({id:te})=>te!==p),this.stylesheet.imports=L.slice(0,q).concat(H).concat(L.slice(q)),this.fragments=this.fragments.slice(0,q).concat(Y).concat(this.fragments.slice(q)),this.mergeLayers(),this}setImportUrl(p,j){this._checkLoaded();const L=this.stylesheet.imports||[],O=this.getImportIndex(p);if(O===-1)return this;L[O].url=j;const q=this.fragments[O];return q.style=this._createFragmentStyle(L[O]),q.style.on("style.import.load",()=>this.mergeAll()),q.style.loadURL(j),this}setImportData(p,j){this._checkLoaded();const L=this.getImportIndex(p),O=this.stylesheet.imports||[];return L===-1?this:j?(this.fragments[L].style.setState(j),this._reloadImports(),this):(delete O[L].data,this.setImportUrl(p,O[L].url))}setImportConfig(p,j,L){this._checkLoaded();const O=this.getImportIndex(p),q=this.stylesheet.imports||[];if(O===-1)return this;j?q[O].config=j:delete q[O].config;const H=this.fragments[O];L&&H.style.stylesheet&&(H.style.stylesheet.schema=L);const Y=H.style.stylesheet&&H.style.stylesheet.schema;return H.config=j,H.style.updateConfig(j,Y),this.updateConfigDependencies(),this}removeImport(p){this._checkLoaded();const j=this.stylesheet.imports||[],L=this.getImportIndex(p);L!==-1&&(j.splice(L,1),this.fragments[L].style._remove(),this.fragments.splice(L,1),this._reloadImports())}getImportIndex(p){const j=(this.stylesheet.imports||[]).findIndex(L=>L.id===p);return j===-1&&this.fire(new o.B(new Error(`Import '${p}' does not exist in the map's style and cannot be updated.`))),j}getLayer(p){return this._mergedLayers[p]}getSources(){const p=[];for(const j in this._mergedOtherSourceCaches){const L=this._mergedOtherSourceCaches[j];L&&p.push(L.getSource())}return p}getSource(p,j){const L=this.getSourceCache(p,j);return L&&L.getSource()}getLayerSource(p){const j=this.getLayerSourceCache(p);return j&&j.getSource()}getSourceCache(p,j){const L=o.F(p,j);return this._mergedOtherSourceCaches[L]}getLayerSourceCache(p){const j=o.F(p.source,p.scope);return p.type==="symbol"?this._mergedSymbolSourceCaches[j]:p.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[j]||this._mergedOtherSourceCaches[j]}getSourceCaches(p){if(p==null)return Object.values(this._mergedSourceCaches);const j=[];return this._mergedOtherSourceCaches[p]&&j.push(this._mergedOtherSourceCaches[p]),this._mergedSymbolSourceCaches[p]&&j.push(this._mergedSymbolSourceCaches[p]),this._mergedFillExtrusionSourceCaches[p]&&j.push(this._mergedFillExtrusionSourceCaches[p]),j}updateSourceCaches(){const p=this._changes.getUpdatedSourceCaches();for(const j in p){const L=p[j];L==="reload"?this.reloadSource(j):L==="clear"&&this.clearSource(j)}}updateLayers(p){const j=this._changes.getUpdatedPaintProperties();for(const L of j){const O=this.getLayer(L);O&&O.updateTransitions(p)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(p){this.stylesheet.glyphs=p,this.glyphManager.setURL(p)}getImages(p,j,L){this.imageManager.getImages(j.images,j.scope,L),this._updateTilesForChangedImages();const O=H=>{if(H){const Y=j.images.map(te=>o.I.toString(te));H.setDependencies(j.tileID.key,j.type,Y)}},q=o.F(j.source,j.scope);O(this._mergedOtherSourceCaches[q]),O(this._mergedSymbolSourceCaches[q]),j.images.some(H=>H.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(p,j,L){this.imageManager.rasterizeImages(j,L)}checkAtlasCache(p,j,L){const O=this.imageManager.imageAtlasCache.findCachedAtlas(j.descriptor);L(null,O&&O.contentDescriptor?{iconPositions:O.iconPositions,patternPositions:O.patternPositions,sourceHash:O.contentDescriptor.hash}:null)}getGlyphs(p,j,L){this.glyphManager.getGlyphs(j.stacks,L)}getOwnSourceCache(p){return this._otherSourceCaches[p]}getOwnLayerSourceCache(p){return p.type==="symbol"?this._symbolSourceCaches[p.source]:p.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[p.source]||this._otherSourceCaches[p.source]}getOwnSourceCaches(p){const j=[];return this._otherSourceCaches[p]&&j.push(this._otherSourceCaches[p]),this._symbolSourceCaches[p]&&j.push(this._symbolSourceCaches[p]),this._fillExtrusionSourceCaches[p]&&j.push(this._fillExtrusionSourceCaches[p]),j}_isSourceCacheLoaded(p){const j=this.getOwnSourceCaches(p);return j.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${p}'`))),!1):j.every(L=>L.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(p,j){if(!this._clipLayerPresent&&p.type!=="fill-extrusion"&&p.type!=="building")return!1;const L=p.type==="fill-extrusion"&&(p.sourceLayer==="building"||p.sourceLayer==="procedural_buildings"),O=p.type==="building";if(p.is3D(!!this.terrain)){if(L||O||j&&j.type==="batched-model"||p.type==="model")return!0}else if(p.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(p=>{p.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}Cf.getSourceType=function(E){return Kv[E]},Cf.setSourceType=function(E,p){Kv[E]=p},Cf.registerForPluginStateChange=o.dk;var $L=` #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`,UL=` #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;}`,e0=` #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`,T2="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;}",qL=` #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`,VL=`#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`,r_=`#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`,n_=`#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`,HL=`#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;}`,N5=`#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`,Om=`#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 E2=/#include\s+"([^"]+)"/g,fr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,JB=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,ez=new Set(["ifdef","ifndef","elif","if","defined"]),r1=new Set;Dg($L,r1),Dg(e0,r1),Dg(UL,r1);const hp={"_prelude_fog.vertex.glsl":VL,"_prelude_terrain.vertex.glsl":qL,"_prelude_shadow.vertex.glsl":N5,"_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":r_,"_prelude_shadow.fragment.glsl":Om,"_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":n_,"_prelude_raster_particle.glsl":HL},a_={};Fa("",qL),Fa(r_,VL),Fa(Om,N5),Fa(n_,""),Fa(HL,"");const t0=Fa(UL,e0),A2=$L,i_=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",A2,t0.fragmentSource].join(` `),ige=["precision highp float;",A2,t0.vertexSource].join(` `);var tz={background:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`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:Fa("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:Fa(`#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:Fa("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:Fa(`#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:Fa(`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:Fa("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:Fa("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:Fa("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:Fa("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:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`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:Fa(`#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:Fa("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:Fa(`#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:Fa(`#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:Fa(`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:Fa(`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:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`#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:Fa(`#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:Fa("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:Fa("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:Fa(`#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:Fa(`#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:Fa(`#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:Fa("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:Fa(`#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 }`,T2),skyboxGradient:Fa(`#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 }`,T2),skyboxCapture:Fa(` 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:Fa(`#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:Fa(`#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:Fa(`#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:Fa("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:Fa(`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:Fa("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:Fa("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:Fa("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:Fa("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 Dg(E,p){const j=E.split(` `);for(let L of j){if(L=L.trimStart(),L[0]!=="#"||!L.includes("if")||L.startsWith("#endif"))continue;const O=L.match(JB);if(O)for(const q of O)ez.has(q)||p.add(q)}}function sz(E){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(E)}function Fa(E,p){const j=new Set,L=[],O=[];E=E.replace(E2,(H,Y)=>(O.push(Y),"")),p=p.replace(E2,(H,Y)=>(L.push(Y),""));let q=new Set(r1);Dg(E,q),Dg(p,q);for(const H of[...L,...O])a_[H]||(a_[H]=new Set,Dg(hp[H],a_[H])),q=new Set([...q,...a_[H]]);return{fragmentSource:E=E.replace(fr,(H,Y,te,de,pe)=>(j.add(pe),Y==="define"?` #ifndef HAS_UNIFORM_u_${pe} ${sz(de)?"flat ":""}in ${te} ${de} ${pe}; #else uniform ${te} ${de} u_${pe}; #endif `:Y==="initialize"?` #ifdef HAS_UNIFORM_u_${pe} ${te} ${de} ${pe} = u_${pe}; #endif `:Y==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${pe} in ${te} ${de} ${pe}; #endif `:Y==="initialize-attribute"?"":void 0)),vertexSource:p=p.replace(fr,(H,Y,te,de,pe)=>{const Ce=`MATERIAL_ATTRIBUTE_OFFSET_${pe}`,je=de==="float"?"vec2":de,Me=`GET_ATTRIBUTE_${je}(a_${pe}, materialInfo, ${Ce})`,qe=pe.match(/color/)?"color":je;return Y==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${pe} in ${te} ${de} a_${pe}; #endif `:j.has(pe)?Y==="define"?` #ifndef HAS_UNIFORM_u_${pe} uniform lowp float u_${pe}_t; #if !defined(${Ce}) in ${te} ${je} a_${pe}; #endif ${sz(de)?"flat ":""}out ${te} ${de} ${pe}; #else uniform ${te} ${de} u_${pe}; #endif `:Y==="initialize"?qe==="vec4"||qe==="uvec4"?` #ifndef HAS_UNIFORM_u_${pe} ${pe} = a_${pe}; #else ${te} ${de} ${pe} = u_${pe}; #endif `:` #if !defined(HAS_UNIFORM_u_${pe}) #ifdef ${Ce} ${pe} = unpack_mix_${qe}(${Me}, u_${pe}_t); #else ${pe} = unpack_mix_${qe}(a_${pe}, u_${pe}_t); #endif #else ${te} ${de} ${pe} = u_${pe}; #endif `:Y==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${pe} in ${te} ${de} a_${pe}; out ${te} ${de} ${pe}; #endif `:Y==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${pe} ${pe} = a_${pe}; #endif `:void 0:Y==="define"?` #ifndef HAS_UNIFORM_u_${pe} uniform lowp float u_${pe}_t; #if !defined(${Ce}) in ${te} ${je} a_${pe}; #endif #else uniform ${te} ${de} u_${pe}; #endif `:Y==="define-instanced"?qe==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${pe}0; in vec4 a_${pe}1; in vec4 a_${pe}2; in vec4 a_${pe}3; #else uniform ${te} ${de} u_${pe}; #endif `:` #ifdef INSTANCED_ARRAYS in ${te} ${je} a_${pe}; #else uniform ${te} ${de} u_${pe}; #endif `:Y==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${pe} ${te} ${de} ${pe} = a_${pe}; #endif `:qe==="vec4"||qe==="uvec4"?` #ifndef HAS_UNIFORM_u_${pe} #ifdef ${Ce} ${te} ${de} ${pe} = ${Me}; #else ${te} ${de} ${pe} = a_${pe}; #endif #else ${te} ${de} ${pe} = u_${pe}; #endif `:` #ifndef HAS_UNIFORM_u_${pe} #ifdef ${Ce} ${te} ${de} ${pe} = unpack_mix_${qe}(${Me}, u_${pe}_t); #else ${te} ${de} ${pe} = unpack_mix_${qe}(a_${pe}, u_${pe}_t); #endif #else ${te} ${de} ${pe} = u_${pe}; #endif `}),usedDefines:q,vertexIncludes:L,fragmentIncludes:O}}class rz{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(p,j,L,O,q,H,Y,te){this.context=p;let de=this.boundPaintVertexBuffers.length!==O.length;for(let Ce=0;!de&&Ce{const Ut=vt.paint.get("hillshade-shadow-color"),Tt=vt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",$t=vt.paint.get("hillshade-highlight-color"),_t=vt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",St=vt.paint.get("hillshade-accent-color"),Rt=vt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Zt=vt.paint.get("hillshade-emissive-strength");let qt=o.ap(vt.paint.get("hillshade-illumination-direction"));if(vt.paint.get("hillshade-illumination-anchor")==="viewport")qt-=rt.transform.angle;else if(rt.style&&rt.style.enable3dLights()&&rt.style.directionalLight){const as=rt.style.directionalLight.properties.get("direction"),Os=o.cP(as.x,as.y,as.z);qt=o.ap(Os[1])}const xs=!rt.options.moving;return{u_matrix:ot||rt.transform.calculateProjMatrix(pt.tileID.toUnwrapped(),xs),u_image:0,u_latrange:GL(0,pt.tileID),u_light:[vt.paint.get("hillshade-exaggeration"),qt],u_shadow:Ut.toPremultipliedRenderColor(Tt?null:vt.lut),u_highlight:$t.toPremultipliedRenderColor(_t?null:vt.lut),u_emissive_strength:Zt,u_accent:St.toPremultipliedRenderColor(Rt?null:vt.lut)}})(E,j,L,E.terrain?p.projMatrix:null);E.uploadCommonUniforms(Y,je,p.toUnwrapped());const{tileBoundsBuffer:qe,tileBoundsIndexBuffer:$e,tileBoundsSegments:nt}=E.getTileBoundsBuffers(j);je.draw(E,te.TRIANGLES,O,q,H,vn.disabled,Me,L.id,qe,$e,nt)}function nz(E,p,j){if(!p.needsDEMTextureUpload)return;const L=E.context,O=L.gl;L.pixelStoreUnpackPremultiplyAlpha.set(!1),p.demTexture=p.demTexture||E.getTileTexture(j.stride);const q=j.getPixels();p.demTexture?p.demTexture.update(q,{premultiply:!1}):p.demTexture=new o.T(L,q,O.R32F,{premultiply:!1}),p.needsDEMTextureUpload=!1}function lge(E,p,j){const L=E.context,O=L.gl;if(!p.dem)return;const q=p.dem;if(L.activeTexture.set(O.TEXTURE1),nz(E,p,q),!p.demTexture)return;p.demTexture.bind(O.NEAREST,O.CLAMP_TO_EDGE);const H=q.dim;L.activeTexture.set(O.TEXTURE0);let Y=p.hillshadeFBO;if(!Y){const je=new o.T(L,{width:H,height:H,data:null},O.RGBA8);je.bind(O.LINEAR,O.CLAMP_TO_EDGE),Y=p.hillshadeFBO=L.createFramebuffer(H,H,1,"renderbuffer"),Y.colorAttachment0.set(je.texture)}L.bindFramebuffer.set(Y.framebuffer),L.viewport.set([0,0,H,H]);const{tileBoundsBuffer:te,tileBoundsIndexBuffer:de,tileBoundsSegments:pe}=E.getMercatorTileBoundsBuffers(),Ce=[];E.linearFloatFilteringSupported()&&Ce.push("TERRAIN_DEM_FLOAT_FORMAT"),E.terrain&&E.terrain.renderingToTexture&&E.emissiveMode==="mrt-fallback"&&Ce.push("USE_MRT1"),E.getOrCreateProgram("hillshadePrepare",{defines:Ce}).draw(E,O.TRIANGLES,$r.disabled,Mn.disabled,Tn.unblended,vn.disabled,((je,Me)=>{const qe=Me.stride,$e=o.bb();return o.bT($e,0,o.an,-o.an,0,0,1),o.bx($e,$e,[0,-o.an,0]),{u_matrix:$e,u_image:1,u_dimension:[qe,qe],u_zoom:je.overscaledZ}})(p.tileID,q),j.id,te,de,pe),p.needsHillshadePrepare=!1}class Mo{constructor(p){this.gl=p.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(p){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class az extends Mo{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(p){const j=this.current;(p.r!==j.r||p.g!==j.g||p.b!==j.b||p.a!==j.a||this.dirty)&&(this.gl.clearColor(p.r,p.g,p.b,p.a),this.current=p,this.dirty=!1)}}class cge extends Mo{getDefault(){return 1}set(p){(p!==this.current||this.dirty)&&(this.gl.clearDepth(p),this.current=p,this.dirty=!1)}}class k5 extends Mo{getDefault(){return 0}set(p){(p!==this.current||this.dirty)&&(this.gl.clearStencil(p),this.current=p,this.dirty=!1)}}class dge extends Mo{getDefault(){return[!0,!0,!0,!0]}set(p){const j=this.current;(p[0]!==j[0]||p[1]!==j[1]||p[2]!==j[2]||p[3]!==j[3]||this.dirty)&&(this.gl.colorMask(p[0],p[1],p[2],p[3]),this.current=p,this.dirty=!1)}}class iz extends Mo{getDefault(){return!0}set(p){(p!==this.current||this.dirty)&&(this.gl.depthMask(p),this.current=p,this.dirty=!1)}}class WL extends Mo{getDefault(){return 255}set(p){(p!==this.current||this.dirty)&&(this.gl.stencilMask(p),this.current=p,this.dirty=!1)}}class S5 extends Mo{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(p){const j=this.current;(p.func!==j.func||p.ref!==j.ref||p.mask!==j.mask||this.dirty)&&(this.gl.stencilFunc(p.func,p.ref,p.mask),this.current=p,this.dirty=!1)}}class KL extends Mo{getDefault(){const p=this.gl;return[p.KEEP,p.KEEP,p.KEEP]}set(p){const j=this.current;(p[0]!==j[0]||p[1]!==j[1]||p[2]!==j[2]||this.dirty)&&(this.gl.stencilOp(p[0],p[1],p[2]),this.current=p,this.dirty=!1)}}class n1 extends Mo{getDefault(){return!1}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;p?j.enable(j.STENCIL_TEST):j.disable(j.STENCIL_TEST),this.current=p,this.dirty=!1}}class a1 extends Mo{getDefault(){return[0,1]}set(p){const j=this.current;(p[0]!==j[0]||p[1]!==j[1]||this.dirty)&&(this.gl.depthRange(p[0],p[1]),this.current=p,this.dirty=!1)}}class o_ extends Mo{getDefault(){return!1}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;p?j.enable(j.DEPTH_TEST):j.disable(j.DEPTH_TEST),this.current=p,this.dirty=!1}}class vx extends Mo{getDefault(){return this.gl.LESS}set(p){(p!==this.current||this.dirty)&&(this.gl.depthFunc(p),this.current=p,this.dirty=!1)}}class oz extends Mo{getDefault(){return!1}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;p?j.enable(j.BLEND):j.disable(j.BLEND),this.current=p,this.dirty=!1}}class YL extends Mo{getDefault(){const p=this.gl;return[p.ONE,p.ZERO,p.ONE,p.ZERO]}set(p){const j=this.current;(p[0]!==j[0]||p[1]!==j[1]||p[2]!==j[2]||p[3]!==j[3]||this.dirty)&&(this.gl.blendFuncSeparate(p[0],p[1],p[2],p[3]),this.current=p,this.dirty=!1)}}class lz extends Mo{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(p){const j=this.current;(p.r!==j.r||p.g!==j.g||p.b!==j.b||p.a!==j.a||this.dirty)&&(this.gl.blendColor(p.r,p.g,p.b,p.a),this.current=p,this.dirty=!1)}}class l_ extends Mo{getDefault(){return this.gl.FUNC_ADD}set(p){(p!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(p,p),this.current=p,this.dirty=!1)}}class C5 extends Mo{getDefault(){return!1}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;p?j.enable(j.CULL_FACE):j.disable(j.CULL_FACE),this.current=p,this.dirty=!1}}class T5 extends Mo{getDefault(){return this.gl.BACK}set(p){(p!==this.current||this.dirty)&&(this.gl.cullFace(p),this.current=p,this.dirty=!1)}}class ZL extends Mo{getDefault(){return this.gl.CCW}set(p){(p!==this.current||this.dirty)&&(this.gl.frontFace(p),this.current=p,this.dirty=!1)}}let E5=class extends Mo{getDefault(){return null}set(E){(E!==this.current||this.dirty)&&(this.gl.useProgram(E),this.current=E,this.dirty=!1)}};class M2 extends Mo{getDefault(){return this.gl.TEXTURE0}set(p){(p!==this.current||this.dirty)&&(this.gl.activeTexture(p),this.current=p,this.dirty=!1)}}class cz extends Mo{getDefault(){const p=this.gl;return[0,0,p.drawingBufferWidth,p.drawingBufferHeight]}set(p){const j=this.current;(p[0]!==j[0]||p[1]!==j[1]||p[2]!==j[2]||p[3]!==j[3]||this.dirty)&&(this.gl.viewport(p[0],p[1],p[2],p[3]),this.current=p,this.dirty=!1)}}class dz extends Mo{getDefault(){return null}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.bindFramebuffer(j.FRAMEBUFFER,p),this.current=p,this.dirty=!1}}class uz extends Mo{getDefault(){return null}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.bindRenderbuffer(j.RENDERBUFFER,p),this.current=p,this.dirty=!1}}class c_ extends Mo{getDefault(){return null}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.bindTexture(j.TEXTURE_2D,p),this.current=p,this.dirty=!1}}class hz extends Mo{getDefault(){return null}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.bindBuffer(j.ARRAY_BUFFER,p),this.current=p,this.dirty=!1}}class uge extends Mo{getDefault(){return null}set(p){const j=this.gl;j.bindBuffer(j.ELEMENT_ARRAY_BUFFER,p),this.current=p,this.dirty=!1}}class hge extends Mo{getDefault(){return null}set(p){this.gl&&(p!==this.current||this.dirty)&&(this.gl.bindVertexArray(p),this.current=p,this.dirty=!1)}}class mge extends Mo{getDefault(){return 4}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.pixelStorei(j.UNPACK_ALIGNMENT,p),this.current=p,this.dirty=!1}}class XL extends Mo{getDefault(){return!1}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.pixelStorei(j.UNPACK_PREMULTIPLY_ALPHA_WEBGL,p),this.current=p,this.dirty=!1}}class QL extends Mo{getDefault(){return!1}set(p){if(p===this.current&&!this.dirty)return;const j=this.gl;j.pixelStorei(j.UNPACK_FLIP_Y_WEBGL,p),this.current=p,this.dirty=!1}}class I2 extends Mo{constructor(p,j){super(p),this.context=p,this.parent=j}getDefault(){return null}}class d_ extends I2{constructor(p,j,L=0){super(p,j),this.attachmentPoint=p.gl.COLOR_ATTACHMENT0+L}setDirty(){this.dirty=!0}set(p){if(p===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const j=this.gl;j.framebufferTexture2D(j.FRAMEBUFFER,this.attachmentPoint,j.TEXTURE_2D,p,0),this.current=p,this.dirty=!1}}class JL extends I2{attachment(){return this.gl.DEPTH_ATTACHMENT}set(p){if(p===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const j=this.gl;j.framebufferRenderbuffer(j.FRAMEBUFFER,this.attachment(),j.RENDERBUFFER,p),this.current=p,this.dirty=!1}}class mz extends I2{attachment(){return this.gl.DEPTH_ATTACHMENT}set(p){if(p===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const j=this.gl;j.framebufferTexture2D(j.FRAMEBUFFER,this.attachment(),j.TEXTURE_2D,p,0),this.current=p,this.dirty=!1}}class fge extends JL{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const L2=(E,p,j,L)=>({u_matrix:E,u_image0:0,u_image1:1,u_skirt_height:p,u_ground_shadow_factor:j,u_emissive_texture_available:L}),u_=(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt)=>({u_proj_matrix:Float32Array.from(E),u_globe_matrix:p,u_normalize_matrix:Float32Array.from(L),u_merc_matrix:j,u_zoom_transition:O,u_merc_center:q,u_image0:0,u_image1:1,u_frustum_tl:H,u_frustum_tr:Y,u_frustum_br:te,u_frustum_bl:de,u_globe_pos:pe,u_globe_radius:Ce,u_viewport:je,u_grid_matrix:nt?Float32Array.from(nt):new Float32Array(9),u_skirt_height:Me,u_far_z_cutoff:qe,u_emissive_texture_available:$e});function eP(E,p){return E!=null&&p!=null&&!(!E.hasData()||!p.hasData())&&E.demTexture!=null&&p.demTexture!=null&&E.tileID.key!==p.tileID.key}const ou=new class{constructor(){this.operations={}}newMorphing(E,p,j,L,O){if(E in this.operations){const q=this.operations[E];q.to.tileID.key!==j.tileID.key&&(q.queued=j)}else this.operations[E]={startTime:L,phase:0,duration:O,from:p,to:j,queued:null}}getMorphValuesForProxy(E){if(!(E in this.operations))return null;const p=this.operations[E];return{from:p.from,to:p.to,phase:p.phase}}update(E){for(const p in this.operations){const j=this.operations[p];for(j.phase=(E-j.startTime)/j.duration;j.phase>=1||!this._validOp(j);)if(!this._nextOp(j,E)){delete this.operations[p];break}}}_nextOp(E,p){return!!E.queued&&(E.from=E.to,E.to=E.queued,E.queued=null,E.phase=0,E.startTime=p,!0)}_validOp(E){return E.from.hasData()&&E.to.hasData()}},A5={0:null,1:"TERRAIN_VERTEX_MORPHING"};function P2(E,p,j){if(p===0)return 0;const L=p<1&&j===514?.25/p:1;return 6*Math.pow(1.5,22-E)*Math.max(p,1)*L}function M5(E,p){const j=1<({u_matrix:E});function O2(E,p,j,L,O){if(O>0){const q=o.o.now(),H=(q-E.timeAdded)/O,Y=p?(q-p.timeAdded)/O:-1,te=j.getSource(),de=L.coveringZoomLevel({tileSize:te.tileSize,roundZoom:te.roundZoom}),pe=!p||Math.abs(p.tileID.overscaledZ-de)>Math.abs(E.tileID.overscaledZ-de),Ce=pe&&E.refreshedUponExpiration?1:o.aC(pe?H:1-Y,0,1);return p?{opacity:1,mix:1-Ce,isFading:H<1}:{opacity:Ce,mix:0,isFading:H<1}}return{opacity:1,mix:0,isFading:!1}}class I5 extends ku{constructor(p){const j={type:"raster-dem",maxzoom:Math.ceil(p.transform.maxZoom)},L=Zb("mock-dem",j,p.style.dispatcher,p.style);super("mock-dem",L,null),L.setEventedParent(this),this._sourceLoaded=!0}_loadTile(p,j){p.state="loaded",j(null)}}class tP extends ku{constructor(p){const j=Zb("proxy",{type:"geojson",maxzoom:Math.ceil(p.transform.maxZoom)},p.style.dispatcher,p.style);super("proxy",j,null),j.setEventedParent(this),this.map=this.getSource().map=p,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(p,j,L){if(p.freezeTileCoverage)return;this.transform=p;const O=p.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((q,H)=>{if(q[H.key]="",!this._tiles[H.key]){const Y=new o.b0(H,this._source.tileSize*H.overscaleFactor(),p.tileZoom,void 0,void 0,this._source.worldview);Y.state="loaded",this._tiles[H.key]=Y}return q},{});for(const q in this._tiles)q in O||(this.freeFBO(q),this._tiles[q].unloadVectorData(),delete this._tiles[q])}freeFBO(p){const j=this.proxyCachedFBO[p];if(j!==void 0){const L=Object.values(j);this.renderCachePool.push(...L),delete this.proxyCachedFBO[p]}}deallocRenderCache(){this.renderCache.forEach(p=>p.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class L5 extends o.aR{constructor(p,j,L){super(p.overscaledZ,p.wrap,p.canonical.z,p.canonical.x,p.canonical.y),this.proxyTileKey=j,this.projMatrix=L}}class F2 extends o.bu{constructor(p,j){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=p,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[L,O,q]=function(){const te=new o.dB,de=new o.dC,pe=131;te.reserve(17161),de.reserve(33800);const Ce=o.an/128,je=o.an+Ce/2,Me=je+Ce;for(let $e=-Ce;$eje||$e<0||$e>je?24575:0,pt=o.aC(Math.round(nt),0,o.an),vt=o.aC(Math.round($e),0,o.an);te.emplaceBack(pt+rt,vt)}const qe=($e,nt)=>{const rt=nt*pe+$e;de.emplaceBack(rt+1,rt,rt+pe),de.emplaceBack(rt+pe,rt+pe+1,rt+1)};for(let $e=1;$e<129;$e++)for(let nt=1;nt<129;nt++)qe(nt,$e);return[0,129].forEach($e=>{for(let nt=0;nt<130;nt++)qe(nt,$e),qe($e,nt)}),[te,de,32768]}(),H=p.context;this.gridBuffer=H.createVertexBuffer(L,o.dx.members),this.gridIndexBuffer=H.createIndexBuffer(O),this.gridSegments=o.dy.simpleSegment(0,0,L.length,O.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,L.length,q),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new tP(j.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 Y=H.gl;this._overlapStencilMode=new Mn({func:Y.GEQUAL,mask:255},0,255,Y.KEEP,Y.KEEP,Y.REPLACE),this._previousZoom=p.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=j,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new I5(j.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(p){p.on("data",this._onStyleDataEvent.bind(this)),this._style=p,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(p,j,L){if(p&&p.terrain){this._style!==p&&(this.style=p,this._evaluationZoom=void 0);const O=p.terrain.properties,q=p.terrain.drapeRenderMode===0,H=p.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const Y=p.terrain&&p.terrain.scope,te=O.get("source"),de=q?this._mockSourceCache:p.getSourceCache(te,Y);if(!de)return void o.w(`Couldn't find terrain source "${te}".`);if(this.sourceCache=de,this._attenuationRange=p.terrain.getAttenuationRange(),this._exaggeration=H?this.calculateExaggeration(j):O.get("exaggeration"),!j.projection.requiresDraping&&H&&this._exaggeration===0)return void this._disable();this.enabled=!0;const pe=()=>{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 Ce=this.getScaledDemTileSize();this.sourceCache.update(j,Ce,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,pe(),this._initializing=!0),pe(),j.updateElevation(!0,L),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(j),this._emptyDEMTextureDirty=!0,this._previousZoom=j.zoom}else this._disable()}calculateExaggeration(p){if(this._attenuationRange&&p.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(p.zoom);const j=this._previousCameraAltitude,L=p.getFreeCameraOptions().position.z/p.pixelsPerMeter*p.worldSize;this._previousCameraAltitude=L;const O=j!=null?L-j:Number.MAX_VALUE;if(Math.abs(O)<2)return this._exaggeration;const q=p.zoom,H=this._style.terrain;if(!this._previousUpdateTimestamp)return H.getExaggeration(q);let Y=q-this._previousZoom;const te=this._previousUpdateTimestamp;let de=q;this._evaluationZoom!=null&&(de=this._evaluationZoom,Math.abs(q-de)>.5&&(Y=.5*(q-de+Y)),Y*O<0&&(de+=Y)),this._evaluationZoom=de;const pe=H.getExaggeration(de),Ce=pe===H.getExaggeration(Math.max(0,de-.1));if(Ce&&Math.abs(pe-this._exaggeration)<.01)return pe;let je=Math.min(.1,.00375*(this._updateTimestamp-te));return(Ce||pe<.1||Math.abs(Y)<1e-4)&&(je=Math.min(.2,4*je)),o.am(this._exaggeration,pe,je)}resetTileLookupCache(p){this._findCoveringTileCache[p]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(p){p.dataType==="source"&&p.coord?this._clearRenderCacheForTile(p.sourceCacheId,p.coord):p.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 p in this._style._mergedSourceCaches)this._style._mergedSourceCaches[p].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(p=>p.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 p=2*this.proxySourceCache.getSource().tileSize;return[p,p]}set useVertexMorphing(p){this._useVertexMorphing=p}updateTileBinding(p){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const j=this.proxySourceCache,L=this.painter.transform;this._initializing&&(this._initializing=L._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(L.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const O=this.proxyCoords=j.getIds().map(te=>{const de=j.getTileByID(te).tileID;return de.projMatrix=L.calculateProjMatrix(de.toUnwrapped()),de});(function(te,de){const pe=de.transform.pointCoordinate(de.transform.getCameraPoint()),Ce=new o.P(pe.x,pe.y);te.sort((je,Me)=>{if(Me.overscaledZ-je.overscaledZ)return Me.overscaledZ-je.overscaledZ;const qe=new o.P(je.canonical.x+(1<{this.proxyToSource[te.key]={}}),this.terrainTileForTile={};const H=this._style._mergedSourceCaches;for(const te in H){const de=H[te];if(!de.used||(de!==this.sourceCache&&this.resetTileLookupCache(de.id),this._setupProxiedCoordsForOrtho(de,p[te],q),de.usedForTerrain))continue;const pe=p[te];(de.getSource().reparseOverscaled||de._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(pe)}this.proxiedCoords[j.id]=O.map(te=>new L5(te,te.key,this.orthoMatrix)),this._assignTerrainTiles(O),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(q),this.renderingToTexture=!1;const Y={};this._visibleDemTiles=[];for(const te of this.proxyCoords){const de=this.terrainTileForTile[te.key];if(!de)continue;const pe=de.tileID.key;pe in Y||(this._visibleDemTiles.push(de),Y[pe]=pe)}}_assignTerrainTiles(p){this._initializing||p.forEach(j=>{if(this.terrainTileForTile[j.key])return;const L=this._findTileCoveringTileID(j,this.sourceCache);L&&(this.terrainTileForTile[j.key]=L)})}_prepareDEMTextures(){const p=this.painter.context,j=p.gl;for(const L in this.terrainTileForTile){const O=this.terrainTileForTile[L],q=O.dem;!q||O.demTexture&&!O.needsDEMTextureUpload||(p.activeTexture.set(j.TEXTURE1),nz(this.painter,O,q))}}_prepareDemTileUniforms(p,j,L,O){if(!j||j.demTexture==null)return!1;const q=p.tileID.canonical,H=Math.pow(2,j.tileID.canonical.z-q.z),Y=O||"";return L[`u_dem_tl${Y}`]=[q.x*H%1,q.y*H%1],L[`u_dem_scale${Y}`]=H,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let p=0;const j=this._visibleDemTiles.reduce((L,O)=>{if(!O.dem)return L;const q=O.dem.tree.minimums[0];return q>0&&p++,L+q},0);return p?j/p:0}_updateEmptyDEMTexture(){const p=this.painter.context,j=p.gl;p.activeTexture.set(j.TEXTURE2);const L=this._getLoadedAreaMinimum(),O=new o.dz({width:1,height:1},new Float32Array([L]));this._emptyDEMTextureDirty=!1;let q=this._emptyDEMTexture;return q?q.update(O,{premultiply:!1}):q=this._emptyDEMTexture=new o.T(p,O,j.R32F,{premultiply:!1}),q}setupElevationDraw(p,j,L){const O=this.painter.context,q=O.gl,H={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};H.u_exaggeration=this.exaggeration();let Y=null,te=null,de=1;if(L&&L.morphing&&this._useVertexMorphing){const Me=L.morphing.srcDemTile,qe=L.morphing.dstDemTile;de=L.morphing.phase,Me&&qe&&(this._prepareDemTileUniforms(p,Me,H,"_prev")&&(te=Me),this._prepareDemTileUniforms(p,qe,H)&&(Y=qe))}const pe=Me=>Me&&Me.demTexture&&this.painter.linearFloatFilteringSupported()?q.LINEAR:q.NEAREST;let Ce=null;var je;if(this.enabled?te&&Y?(Ce=Y.demTexture,O.activeTexture.set(q.TEXTURE4),te.demTexture.bind(pe(te),q.CLAMP_TO_EDGE),H.u_dem_lerp=de):(Y=this.terrainTileForTile[p.tileID.key],Ce=this._prepareDemTileUniforms(p,Y,H)?Y.demTexture:this.emptyDEMTexture):Ce=this.emptyDEMTexture,O.activeTexture.set(q.TEXTURE2),Ce&&(H.u_dem_size=(je=Ce).size[0]===1?1:je.size[0]-2,Ce.bind(pe(Y),q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(L&&L.useDepthForOcclusion,j,H),L&&L.useMeterToDem&&Y){const Me=(1<{if(rt===as)return;const Os=[A5[as],"PROJECTION_GLOBE_VIEW"];vt&&Os.push("CUSTOM_ANTIALIASING");const Hs=de.isTileAffectedByFog(xs);nt=de.getOrCreateProgram("globeRaster",{defines:Os,overrideFog:Hs}),rt=as},Ut=de.colorModeForRenderPass(),Tt=new $r($e.LEQUAL,$r.ReadWrite,de.depthRangeFor3D);ou.update(Me);const $t=o.dq(pt),_t=[o.aH(pt.center.lng),o.aL(pt.center.lat)],St=de.globeSharedBuffers,Rt=[pt.width*o.o.devicePixelRatio,pt.height*o.o.devicePixelRatio],Zt=Float32Array.from(pt.globeMatrix),qt={useDenormalizedUpVectorScale:!0};{const xs=de.transform,as=P2(xs.zoom,pe.exaggeration(),pe.sourceCache._source.tileSize);rt=-1;const Os=$e.TRIANGLES;for(const Hs of je){const Qt=Ce.getTile(Hs),Ht=Mn.disabled,us=pe.prevTerrainTileForTile[Hs.key],vs=pe.terrainTileForTile[Hs.key];eP(us,vs)&&ou.newMorphing(Hs.key,us,vs,Me,250),D2(de,Qt.emissiveTexture),qe.activeTexture.set($e.TEXTURE0),Qt.texture&&Qt.texture.bind($e.LINEAR,$e.CLAMP_TO_EDGE);const ks=ou.getMorphValuesForProxy(Hs.key),cr=ks?1:0;ks&&Object.assign(qt,{morphing:{srcDemTile:ks.from,dstDemTile:ks.to,phase:o.dn(ks.phase)}});const Js=o.dr(Hs.canonical),er=o.ds(Js.getCenter().lat),Us=o.dt(Hs.canonical,Js,er,xs.worldSize/xs._pixelsPerMercatorPixel),Br=o.du(o.dv(Hs.canonical)),Kr=de.emissiveMode==="mrt-fallback"?1:0,Er=u_(xs.expandedFarZProjMatrix,Zt,$t,Br,o.al(xs.zoom),_t,xs.frustumCorners.TL,xs.frustumCorners.TR,xs.frustumCorners.BR,xs.frustumCorners.BL,xs.globeCenterInViewSpace,xs.globeRadius,Rt,as,xs._farZ,Kr,Us);if(ot(Hs,cr),nt&&(pe.setupElevationDraw(Qt,nt,qt),de.uploadCommonUniforms(qe,nt,Hs.toUnwrapped()),St)){const[Fr,_n,Fn]=St.getGridBuffers(er,as!==0);nt.draw(de,Os,Tt,Ht,Ut,vn.backCCW,Er,"globe_raster",Fr,_n,Fn)}}}if(St&&(de.renderDefaultNorthPole||de.renderDefaultSouthPole)){const xs=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];vt&&xs.push("CUSTOM_ANTIALIASING"),nt=de.getOrCreateProgram("globeRaster",{defines:xs});for(const as of je){const{x:Os,y:Hs,z:Qt}=as.canonical,Ht=Hs===0,us=Hs===(1<Fr.draw(de,$e.TRIANGLES,Tt,Mn.disabled,Ut,vn.disabled,u_(pt.expandedFarZProjMatrix,Us,Us,Br,0,_t,pt.frustumCorners.TL,pt.frustumCorners.TR,pt.frustumCorners.BR,pt.frustumCorners.BL,pt.globeCenterInViewSpace,pt.globeRadius,Rt,0,pt._farZ,Kr),"globe_pole_raster",_n,cr,Js);pe.setupElevationDraw(er,nt,qt),de.uploadCommonUniforms(qe,nt,as.toUnwrapped()),Ht&&de.renderDefaultNorthPole&&Er(nt,vs),us&&de.renderDefaultSouthPole&&(Us=o.cC(o.bb(),Us,[1,-1,1]),Er(nt,ks))}}}})(O,q,H,Y,te);else{const de=O.context,pe=de.gl;let Ce,je;const Me=O.shadowRenderer,qe=Mc(O,O.longestCutoffRange),$e=Ut=>{if(je===Ut)return;const Tt=[];Tt.push(A5[Ut]),qe.shouldRenderCutoff&&Tt.push("RENDER_CUTOFF"),Me&&(Tt.push("RENDER_SHADOWS"),Me.useNormalOffset&&Tt.push("NORMAL_OFFSET")),Ce=O.getOrCreateProgram("terrainRaster",{defines:Tt}),je=Ut},nt=O.colorModeForRenderPass(),rt=new $r(pe.LEQUAL,$r.ReadWrite,O.depthRangeFor3D);ou.update(te);const pt=O.transform,vt=P2(pt.zoom,q.exaggeration(),q.sourceCache._source.tileSize);let ot=[0,0,0];if(Me){const Ut=O.style.directionalLight,Tt=O.style.ambientLight;Ut&&Tt&&(ot=up(O.style,Ut,Tt))}{je=-1;const Ut=pe.TRIANGLES,[Tt,$t]=[q.gridIndexBuffer,q.gridSegments];for(const _t of Y){const St=H.getTile(_t),Rt=Mn.disabled,Zt=q.prevTerrainTileForTile[_t.key],qt=q.terrainTileForTile[_t.key];eP(Zt,qt)&&ou.newMorphing(_t.key,Zt,qt,te,250),D2(O,St.emissiveTexture),de.activeTexture.set(pe.TEXTURE0),St.texture&&St.texture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE);const xs=ou.getMorphValuesForProxy(_t.key),as=xs?1:0;let Os;xs&&(Os={morphing:{srcDemTile:xs.from,dstDemTile:xs.to,phase:o.dn(xs.phase)}});const Hs=O.emissiveMode==="mrt-fallback"?1:0,Qt=L2(_t.projMatrix,M5(_t.canonical,pt.renderWorldCopies)?vt/10:vt,ot,Hs);if($e(as),!Ce)continue;q.setupElevationDraw(St,Ce,Os);const Ht=_t.toUnwrapped();Me&&Me.setupShadows(Ht,Ce),O.uploadCommonUniforms(de,Ce,Ht,null,qe),Ce.draw(O,Ut,rt,Rt,nt,vn.backCCW,Qt,"terrain_raster",q.gridBuffer,Tt,$t)}}}}(j,this,this.proxySourceCache,p,this._updateTimestamp),this.renderingToTexture=!0,j.gpuTimingDeferredRenderEnd(),p.splice(0,p.length))}renderBatch(p){if(this._drapedRenderBatches.length===0)return p+1;this.renderingToTexture=!0;const j=this.painter,L=this.painter.context,O=this.proxySourceCache,q=this.proxiedCoords[O.id],H=this._drapedRenderBatches.shift(),Y=j.style.order,te=[];this._updateFBOs(j.emissiveMode==="mrt-fallback");let de=0;for(const pe of q){const Ce=O.getTileByID(pe.proxyTileKey),je=O.proxyCachedFBO[pe.key]?O.proxyCachedFBO[pe.key][p]:void 0,Me=je!==void 0?O.renderCache[je]:this.pool[de++],qe=je!==void 0;if(Ce.texture=Me.tex,Ce.emissiveTexture=Me.emissiveTex,qe&&!Me.dirty){te.push(Ce.tileID);continue}L.bindFramebuffer.set(Me.fb.framebuffer);const $e=L.gl;let nt;$e.drawBuffers(j.emissiveMode==="mrt-fallback"?[$e.COLOR_ATTACHMENT0,$e.COLOR_ATTACHMENT1]:[$e.COLOR_ATTACHMENT0]),this.renderedToTile=!1,Me.dirty&&(L.clear({color:o.aq.transparent,stencil:0}),Me.dirty=!1);for(let rt=H.start;rt<=H.end;++rt){const pt=j.style._mergedLayers[Y[rt]];if(pt.isHidden(j.transform.zoom))continue;const vt=j.style.getLayerSourceCache(pt),ot=vt?this.proxyToSource[pe.key][vt.id]:[pe];if(!ot)continue;const Ut=ot;L.viewport.set([0,0,Me.fb.width,Me.fb.height]),nt!==(vt?vt.id:null)&&(this._setupStencil(Me,ot,pt,vt),nt=vt?vt.id:null),j.renderLayer(j,vt,pt,Ut)}if($e.drawBuffers([$e.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const rt of this._pendingGroundEffectLayers){const pt=j.style._mergedLayers[Y[rt]];if(pt.isHidden(j.transform.zoom))continue;const vt=j.style.getLayerSourceCache(pt),ot=vt?this.proxyToSource[pe.key][vt.id]:[pe];if(!ot)continue;const Ut=ot;L.viewport.set([0,0,Me.fb.width,Me.fb.height]),nt!==(vt?vt.id:null)&&(this._setupStencil(Me,ot,pt,vt),nt=vt?vt.id:null),j.renderLayer(j,vt,pt,Ut)}this.renderedToTile?(Me.dirty=!0,te.push(Ce.tileID)):qe||--de,de===5&&(de=0,this.renderToBackBuffer(te))}return this.renderToBackBuffer(te),this.renderingToTexture=!1,L.bindFramebuffer.set(null),L.viewport.set([0,0,j.width,j.height]),H.end+1}postRender(){}isLayerOrderingCorrect(p){const j=p.order.length;let L=-1,O=j;for(let q=0;qL}getMinElevationBelowMSL(){let p=0;return this._visibleDemTiles.filter(j=>j.dem).forEach(j=>{p=Math.min(p,j.dem.tree.minimums[0])}),p===0?p:(p-30)*this._exaggeration}raycast(p,j,L){if(!this._visibleDemTiles)return null;const O=this._visibleDemTiles.filter(q=>q.dem).map(q=>{const H=q.tileID,Y=1<(q.t!==null?q.t:Number.MAX_VALUE)-(H.t!==null?H.t:Number.MAX_VALUE));for(const q of O){if(q.t==null)return null;const H=q.tile.dem.tree.raycast(q.minx,q.miny,q.maxx,q.maxy,p,j,L);if(H!=null)return H}return null}_createFBO(){const p=this.painter.context,j=p.gl,L=this.drapeBufferSize;p.activeTexture.set(j.TEXTURE0);const O=new o.T(p,{width:L[0],height:L[1],data:null},j.RGBA8);O.bind(j.LINEAR,j.CLAMP_TO_EDGE);const q=p.createFramebuffer(L[0],L[1],1,null);let H;return q.colorAttachment0.set(O.texture),this._emissiveTexture&&(H=new o.T(p,{width:L[0],height:L[1],data:null},j.R8),H.bind(j.LINEAR,j.CLAMP_TO_EDGE),q.createColorAttachment(p,1),q.colorAttachment1.set(H.texture)),q.depthAttachment=new fge(p,q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=p.createRenderbuffer(p.gl.DEPTH_STENCIL,L[0],L[1]),this._stencilRef=0,q.depthAttachment.set(this._sharedDepthStencil),p.clear({stencil:0})):q.depthAttachment.set(this._sharedDepthStencil),p.extTextureFilterAnisotropic&&j.texParameterf(j.TEXTURE_2D,p.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,p.extTextureFilterAnisotropicMax),{fb:q,tex:O,emissiveTex:H,dirty:!1}}_updateFBOs(p){if(this._emissiveTexture!==p){for(const j of this.pool)this._updateFBO(j,p);for(const j of this.proxySourceCache.renderCache)this._updateFBO(j,p);this._emissiveTexture=p}}_updateFBO(p,j){const L=p.fb,O=this.painter.context,q=O.gl,H=this.drapeBufferSize;if(j){const Y=new o.T(O,{width:H[0],height:H[1],data:null},q.R8);Y.bind(q.LINEAR,q.CLAMP_TO_EDGE),p.emissiveTex=Y,L.createColorAttachment(O,1),L.colorAttachment1.set(Y.texture)}else p.emissiveTex=void 0,L.removeColorAttachment(O,1);p.dirty=!0}_initFBOPool(){for(;this.pool.length{const j=this._style._mergedLayers[p],L=j.isHidden(this.painter.transform.zoom);return j.type==="hillshade"||j.type==="custom"?!L&&j.shouldRedrape():!L&&j.hasTransition()})}_clearLineLayersFromRenderCache(){let p=!1;for(const L of this._style.getSources())if(L instanceof ju){p=!0;break}if(!p)return;const j={};for(let L=0;Lte>Y.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=L}_setupRenderCache(p){const j=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,j.renderCache.length>j.renderCachePool.length){const H=Object.values(j.proxyCachedFBO);j.proxyCachedFBO={};for(let Y=0;Y=0;H--){const Y=L[H];if(j.getTileByID(Y.key),j.proxyCachedFBO[Y.key]!==void 0){const te=p[Y.key],de=this.proxyToSource[Y.key];let pe=0;for(const Ce in de){const je=de[Ce],Me=te[Ce];if(!Me||Me.length!==je.length||je.some((qe,$e)=>qe!==Me[$e]||O[Ce]&&O[Ce].hasOwnProperty(qe.key))){pe=-1;break}++pe}for(const Ce in j.proxyCachedFBO[Y.key])j.renderCache[j.proxyCachedFBO[Y.key][Ce]].dirty=pe<0||pe!==Object.values(te).length}}const q=[...this._drapedRenderBatches];q.sort((H,Y)=>Y.end-Y.start-(H.end-H.start));for(const H of q)for(const Y of L){if(j.proxyCachedFBO[Y.key])continue;let te=j.renderCachePool.pop();te===void 0&&j.renderCache.length<50&&(te=j.renderCache.length,j.renderCache.push(this._createFBO())),te!==void 0&&(j.proxyCachedFBO[Y.key]={},j.proxyCachedFBO[Y.key][H.start]=te,j.renderCache[te].dirty=!0)}this._tilesDirty={}}_setupStencil(p,j,L,O){if(!O||!this._sourceTilesOverlap[O.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const q=this.painter.context,H=q.gl;if(j.length<=1)return void(this._overlapStencilType=!1);let Y;if(L.isTileClipped())Y=j.length,this._overlapStencilMode.test={func:H.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(j[0].overscaledZ>j[j.length-1].overscaledZ))return void(this._overlapStencilType=!1);Y=1,this._overlapStencilMode.test={func:H.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+Y>255&&(q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=Y,this._overlapStencilMode.ref=this._stencilRef,L.isTileClipped()&&this._renderTileClippingMasks(j,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(p){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[p.key]),this._overlapStencilMode):Mn.disabled}_renderTileClippingMasks(p,j){const L=this.painter,O=this.painter.context,q=O.gl;L._tileClippingMaskIDs={},O.setColorMode(Tn.disabled),O.setDepthMode($r.disabled);const H=L.getOrCreateProgram("clippingMask");for(const Y of p){const te=L._tileClippingMaskIDs[Y.key]=--j;H.draw(L,q.TRIANGLES,$r.disabled,new Mn({func:q.ALWAYS,mask:0},te,255,q.KEEP,q.KEEP,q.REPLACE),Tn.disabled,vn.disabled,R2(Y.projMatrix),"$clipping",L.tileExtentBuffer,L.quadTriangleIndexBuffer,L.tileExtentSegments)}}pointCoordinate(p){const j=this.painter.transform;if(p.x<0||p.x>j.width||p.y<0||p.y>j.height)return null;const L=[p.x,p.y,1,1];o.aE(L,L,j.pixelMatrixInverse),o.cu(L,L,1/L[3]),L[0]/=j.worldSize,L[1]/=j.worldSize;const O=j._camera.position,q=o.bU(1,j.center.lat),H=[O[0],O[1],O[2]/q,0],Y=o.cV([],L.slice(0,3),H);o.ay(Y,Y);const te=this.raycast(H,Y,this._exaggeration);return te!==null&&te?(o.bg(H,H,Y,te),H[3]=H[2],H[2]*=q,H):null}_setupProxiedCoordsForOrtho(p,j,L){if(p.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(p,j,L);this._findCoveringTileCache[p.id]=this._findCoveringTileCache[p.id]||{};const O=this.proxiedCoords[p.id]=[],q=this.proxyCoords;for(let te=0;tepe.overscaledZ-de.overscaledZ)}_setupProxiedCoordsForImageSource(p,j,L){if(!p.getSource().loaded())return;const O=this.proxiedCoords[p.id]=[],q=this.proxyCoords,H=p.getSource(),Y=H.tileID;if(!Y)return;const te=new o.P(Y.x,Y.y)._div(1<(Ce.min.x=Math.min(Ce.min.x,je.x-te.x),Ce.min.y=Math.min(Ce.min.y,je.y-te.y),Ce.max.x=Math.max(Ce.max.x,je.x-te.x),Ce.max.y=Math.max(Ce.max.y,je.y-te.y),Ce),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),pe=(Ce,je)=>{const Me=Ce.wrap+Ce.canonical.x/(1<nt+de.max.x||qe+$ert+de.max.y};for(let Ce=0;CeH.key===j.tileID.key);if(q)return q}if(j.tileID.key!==p.key){const q=p.canonical.z-j.tileID.canonical.z;let H,Y,te;O=o.bb();const de=j.tileID.wrap-p.wrap<0?(H=o.an>>q,Y=H*((j.tileID.canonical.x<=Ce){const je=p.canonical.z-Ce;j.getSource().reparseOverscaled?(Y=Math.max(p.canonical.z+2,j.transform.tileZoom),H=new o.aR(Y,p.wrap,Ce,p.canonical.x>>je,p.canonical.y>>je)):je!==0&&(Y=Ce,H=new o.aR(Y,p.wrap,Ce,p.canonical.x>>je,p.canonical.y>>je))}H.key!==p.key&&(de.push(H.key),L=j.getTile(H))}const pe=Ce=>{de.forEach(je=>{O[je]=Ce}),de.length=0};for(Y-=1;Y>=te&&(!L||!L.hasData());Y--){L&&pe(L.tileID.key);const Ce=H.calculateScaledKey(Y);if(L=j.getTileByID(Ce),L&&L.hasData())break;const je=O[Ce];if(je===null)break;je===void 0?de.push(Ce):L=j.getTileByID(je)}return pe(L?L.tileID.key:null),L&&L.hasData()?L:null}findDEMTileFor(p){return this.enabled?this._findTileCoveringTileID(p,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(p,j){let L=this._tilesDirty[p];L||(L=this._tilesDirty[p]={}),L[j.key]=!0}}function sP(E,p,j){const L=function(Y,te,de){const pe=o.bi(te,Y),Ce=o.bi(de,[.2126,.7152,.0722]),je=(qe,$e,nt)=>(1-nt)*qe+nt*$e,Me=je(1-.3*Math.min(Ce,1),1,Math.min(pe+1,1));return je(.92,1,Math.asin(o.aC(te[2],-1,1))/Math.PI+.5)*Me}(E,[0,0,1],p),O=[0,0,0];o.bJ(O,j.slice(0,3),L);const q=[0,0,0];o.bJ(q,p.slice(0,3),E[2]);const H=[0,0,0];return o.cT(H,O,q),o.cW(H)}const fz=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],pz=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class i1{static cacheKey(p,j,L,O){const q=[j];O&&q.push(O.cacheKey);for(const H of L)(typeof H=="string"&&H.includes(" ")||p.usedDefines.has(H))&&q.push(H);return q.join("/")}constructor(p,j,L,O,q,H){const Y=p.gl;this.program=Y.createProgram(),this.configuration=O,this.name=j,this.fixedDefines=[...H];const te=`#version 300 es ${(O?O.defines():[]).concat(H.map($e=>`#define ${$e}`)).join(` `)}`,de=[te,i_];for(const $e of L.fragmentIncludes)de.push(hp[$e]);de.push(L.fragmentSource);const pe=de.join(` `),Ce=[te,ige];for(const $e of L.vertexIncludes)Ce.push(hp[$e]);this.forceManualRenderingForInstanceIDShaders=p.forceManualRenderingForInstanceIDShaders&&L.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Ce.push("uniform int u_instanceID;"),Ce.push(L.vertexSource);let je=Ce.join(` `);this.forceManualRenderingForInstanceIDShaders&&(je=je.replaceAll("gl_InstanceID","u_instanceID"));const Me=Y.createShader(Y.FRAGMENT_SHADER);if(Y.isContextLost())return void(this.failedToCreate=!0);Y.shaderSource(Me,pe),Y.compileShader(Me),Y.attachShader(this.program,Me);const qe=Y.createShader(Y.VERTEX_SHADER);Y.isContextLost()?this.failedToCreate=!0:(Y.shaderSource(qe,je),Y.compileShader(qe),Y.attachShader(this.program,qe),this.attributes={},Y.linkProgram(this.program),Y.deleteShader(qe),Y.deleteShader(Me),this.fixedUniforms=q(p),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=O?O.getUniforms(p):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=($e=>({u_instanceID:new o.bX($e)}))(p)),(H.includes("TERRAIN")||H.includes("ELEVATED")||j.includes("symbol")||j.includes("circle"))&&(this.terrainUniforms=($e=>({u_dem:new o.bX($e),u_dem_prev:new o.bX($e),u_dem_tl:new o.b_($e),u_dem_scale:new o.bZ($e),u_dem_tl_prev:new o.b_($e),u_dem_scale_prev:new o.bZ($e),u_dem_size:new o.bZ($e),u_dem_lerp:new o.bZ($e),u_exaggeration:new o.bZ($e),u_depth:new o.bX($e),u_depth_size_inv:new o.b_($e),u_depth_range_unpack:new o.b_($e),u_occluder_half_size:new o.bZ($e),u_occlusion_depth_offset:new o.bZ($e),u_meter_to_dem:new o.bZ($e),u_label_plane_matrix_inv:new o.b$($e)}))(p)),H.includes("GLOBE")&&(this.globeUniforms=($e=>({u_tile_tl_up:new o.bY($e),u_tile_tr_up:new o.bY($e),u_tile_br_up:new o.bY($e),u_tile_bl_up:new o.bY($e),u_tile_up_scale:new o.bZ($e)}))(p)),H.includes("FOG")&&(this.fogUniforms=($e=>({u_fog_matrix:new o.b$($e),u_fog_range:new o.b_($e),u_fog_color:new o.cO($e),u_fog_horizon_blend:new o.bZ($e),u_fog_vertical_limit:new o.b_($e),u_fog_temporal_offset:new o.bZ($e),u_frustum_tl:new o.bY($e),u_frustum_tr:new o.bY($e),u_frustum_br:new o.bY($e),u_frustum_bl:new o.bY($e),u_globe_pos:new o.bY($e),u_globe_radius:new o.bZ($e),u_globe_transition:new o.bZ($e),u_is_globe:new o.bX($e),u_viewport:new o.b_($e)}))(p)),H.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=($e=>({u_cutoff_params:new o.cO($e)}))(p)),H.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=($e=>({u_lighting_ambient_color:new o.bY($e),u_lighting_directional_dir:new o.bY($e),u_lighting_directional_color:new o.bY($e),u_ground_radiance:new o.bY($e)}))(p)),H.includes("RENDER_SHADOWS")&&(this.shadowUniforms=($e=>({u_light_matrix_0:new o.b$($e),u_light_matrix_1:new o.b$($e),u_fade_range:new o.b_($e),u_shadow_normal_offset:new o.bY($e),u_shadow_intensity:new o.bZ($e),u_shadow_texel_size:new o.bZ($e),u_shadow_map_resolution:new o.bZ($e),u_shadow_direction:new o.bY($e),u_shadow_bias:new o.bY($e),u_shadowmap_0:new o.bX($e),u_shadowmap_1:new o.bX($e)}))(p)))}getAttributeLocation(p,j){let L=this.attributes[j];return L===void 0&&(L=this.attributes[j]=p.getAttribLocation(this.program,j)),L}setTerrainUniformValues(p,j){if(!this.terrainUniforms)return;const L=this.terrainUniforms;if(!this.failedToCreate){p.program.set(this.program);for(const O in j)L[O]&&L[O].set(this.program,O,j[O])}}setGlobeUniformValues(p,j){if(!this.globeUniforms)return;const L=this.globeUniforms;if(!this.failedToCreate){p.program.set(this.program);for(const O in j)L[O]&&L[O].set(this.program,O,j[O])}}setFogUniformValues(p,j){if(!this.fogUniforms)return;const L=this.fogUniforms;if(!this.failedToCreate){p.program.set(this.program);for(const O in j)L[O].set(this.program,O,j[O])}}setCutoffUniformValues(p,j){if(!this.cutoffUniforms)return;const L=this.cutoffUniforms;if(!this.failedToCreate){p.program.set(this.program);for(const O in j)L[O].set(this.program,O,j[O])}}setLightsUniformValues(p,j){if(!this.lightsUniforms)return;const L=this.lightsUniforms;if(!this.failedToCreate){p.program.set(this.program);for(const O in j)L[O].set(this.program,O,j[O])}}setShadowUniformValues(p,j){if(this.failedToCreate||!this.shadowUniforms)return;const L=this.shadowUniforms;p.program.set(this.program);for(const O in j)L[O].set(this.program,O,j[O])}_drawDebugWireframe(p,j,L,O,q,H,Y,te,de,pe){const Ce=p.options.wireframe;if(Ce.terrain===!1&&Ce.layers2D===!1&&Ce.layers3D===!1)return;const je=p.context;if(!(!(!Ce.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ce.layers2D||p._terrain&&p._terrain.renderingToTexture||!fz.includes(this.name))||!(!Ce.layers3D||!pz.includes(this.name))))return;const Me=je.gl,qe=p.wireframeDebugCache.getLinesFromTrianglesBuffer(p.frameCounter,q,je);if(!qe)return;const $e=[...this.fixedDefines,"DEBUG_WIREFRAME"],nt=p.getOrCreateProgram(this.name,{config:this.configuration,defines:$e});je.program.set(nt.program);const rt=(ot,Ut,Tt)=>{if(Ut[ot]&&Tt[ot])for(const $t in Ut[ot])Tt[ot][$t]&&Tt[ot][$t].set(Tt.program,$t,Ut[ot][$t].current)};de&&de.setUniforms(nt.program,je,nt.binderUniforms,Y,{zoom:te}),rt("fixedUniforms",this,nt),rt("terrainUniforms",this,nt),rt("globeUniforms",this,nt),rt("fogUniforms",this,nt),rt("lightsUniforms",this,nt),rt("shadowUniforms",this,nt),qe.bind(),je.setColorMode(new Tn([Me.ONE,Me.ONE_MINUS_SRC_ALPHA,Me.ZERO,Me.ONE],o.aq.transparent,[!0,!0,!0,!1])),je.setDepthMode(new $r(j.func===Me.LESS?Me.LEQUAL:j.func,$r.ReadOnly,j.range)),je.setStencilMode(Mn.disabled);const pt=3*H.primitiveLength*2,vt=3*H.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ot=pe||1;for(let Ut=0;Ut1?Me.drawElementsInstanced(Me.LINES,pt,Me.UNSIGNED_SHORT,vt,pe):Me.drawElements(Me.LINES,pt,Me.UNSIGNED_SHORT,vt);q.bind(),je.program.set(this.program),je.setDepthMode(j),je.setStencilMode(L),je.setColorMode(O)}checkUniforms(p,j,L){if(this.fixedDefines.includes(j)){for(const O of Object.keys(L))if(!L[O].initialized)throw new Error(`Program '${this.name}', from draw '${p}': uniform ${O} not set but required by ${j} being defined`)}}draw(p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt){const rt=p.context,pt=rt.gl;if(this.failedToCreate)return;rt.program.set(this.program),rt.setDepthMode(L),rt.setStencilMode(O),rt.setColorMode(q),rt.setCullFace(H);for(const[_t,St]of this.fixedUniformsEntries)St.set(this.program,_t,Y[_t]);qe&&qe.setUniforms(this.program,rt,this.binderUniforms,je,{zoom:Me});const vt={[pt.POINTS]:1,[pt.LINES]:2,[pt.TRIANGLES]:3,[pt.LINE_STRIP]:1}[j];this.checkUniforms(te,"RENDER_SHADOWS",this.shadowUniforms);const ot=$e||[],Ut=qe?qe.getPaintVertexBuffers():[],Tt=j===pt.TRIANGLES&&pe,$t=nt&&nt>0?1:void 0;for(const _t of Ce.get()){const St=_t.vaos||(_t.vaos={});if((St[te]||(St[te]=new rz)).bind(rt,this,de,Ut,pe,_t.vertexOffset,ot,$t),this.forceManualRenderingForInstanceIDShaders){const Rt=nt||1;for(let Zt=0;Zt1?pt.drawElementsInstanced(j,_t.primitiveLength*vt,pt.UNSIGNED_SHORT,_t.primitiveOffset*vt*2,nt):pe?pt.drawElements(j,_t.primitiveLength*vt,pt.UNSIGNED_SHORT,_t.primitiveOffset*vt*2):pt.drawArrays(j,_t.vertexOffset,_t.vertexLength);Tt&&this._drawDebugWireframe(p,L,O,q,pe,_t,je,Me,qe,nt)}}}function xz(E,p,j=0){const L=Math.pow(2,p.tileID.overscaledZ),O=p.tileSize*Math.pow(2,E.transform.tileZoom)/L,q=O*(p.tileID.canonical.x+p.tileID.wrap*L),H=O*p.tileID.canonical.y;return{u_image:0,u_texsize:p.imageAtlasTexture?p.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(p,1,E.transform.tileZoom),u_pixel_coord_upper:[q>>16,H>>16],u_pixel_coord_lower:[65535&q,65535&H],u_pattern_transition:j}}const P5={terrain:0,flat:1},pge=o.bb(),gz=(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt,pt=[0,0,1])=>{const vt=p.style.light,ot=vt.properties.get("position"),Ut=[ot.x,ot.y,ot.z],Tt=o.dE();vt.properties.get("anchor")==="viewport"&&(o.dF(Tt,-p.transform.angle),o.dG(Ut,Ut,Tt));const $t=vt.properties.get("color").toPremultipliedRenderColor(null),_t=p.transform,St={u_matrix:E,u_lightpos:Ut,u_lightintensity:vt.properties.get("intensity"),u_lightcolor:[$t.r,$t.g,$t.b],u_vertical_gradient:+j,u_opacity:L,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:pge,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:P5[de],u_base_type:P5[pe],u_ao:O,u_edge_radius:q,u_width_scale:H,u_flood_light_color:qe,u_vertical_scale:$e,u_flood_light_intensity:nt,u_ground_shadow_factor:rt,u_front_cutoff_params:pt};return _t.projection.name==="globe"&&(St.u_tile_id=[Y.canonical.x,Y.canonical.y,1<({u_matrix:E,u_edge_radius:p,u_width_scale:j,u_vertical_scale:L,u_height_type:P5[O],u_base_type:P5[q]}),gge=(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt)=>{const pt=gz(E,p,j,L,O,q,H,Y,de,pe,Ce,je,Me,qe,$e,nt,1,[0,0,0]),vt={u_height_factor:-Math.pow(2,Y.overscaledZ)/te.tileSize/8};return Object.assign(pt,xz(p,te,rt),vt)},D5=(E,p,j)=>({u_matrix:E,u_emissive_strength:p,u_ground_shadow_factor:j}),R5=(E,p,j,L,O,q=0)=>Object.assign(D5(E,p,O),xz(j,L,q)),yz=(E,p,j,L)=>({u_matrix:E,u_world:j,u_emissive_strength:p,u_ground_shadow_factor:L}),h_=(E,p,j,L,O,q,H=0)=>Object.assign(R5(E,p,j,L,q,H),{u_world:O}),vz=(E,p)=>({u_matrix:E,u_depth_bias:p}),bz=(E,p)=>({u_matrix:E,u_ground_shadow_factor:p}),B2=(E,p,j,L,O)=>({u_matrix:E,u_camera_pos:[p[0],p[1],p[2]],u_depth_bias:j,u_height_scale:L,u_reset_depth:O}),O5=(E,p,j)=>({u_image:E,u_opacity:p,u_blend_mode:j}),s0=(E,p,j,L,O,q,H,Y,te,de=[0,0,1])=>({u_matrix:E,u_normal_matrix:p,u_opacity:j,u_faux_facade_ao_intensity:L,u_camera_pos:O,u_tile_to_meter:q,u_facade_emissive_chance:H,u_flood_light_color:Y,u_flood_light_intensity:te,u_front_cutoff_params:de}),F5=E=>({u_matrix:E}),B5=E=>({u_matrix:E}),_z=(E,p,j,L,O,q,H,Y)=>{const te=o.an/q.tileSize;return{u_matrix:E,u_inv_rot_matrix:p,u_camera_to_center_distance:j.getCameraToCenterDistance(Y),u_extrude_scale:[j.pixelsToGLUnits[0]/te,j.pixelsToGLUnits[1]/te],u_zoom_transition:L,u_tile_id:H,u_merc_center:O}},r0=(E,p,j,L)=>({u_matrix:E,u_inv_matrix:p,u_camera_to_center_distance:j.getCameraToCenterDistance(L),u_viewport_size:[j.width,j.height]}),z2=(E,p,j=1)=>({u_matrix:E,u_color:p,u_overlay:0,u_overlay_scale:j}),z5=o.bb(),wz=(E,p,j,L,O,q,H)=>{const Y=E.transform,te=Y.projection.name==="globe",de=te?o.dH(Y.zoom,p.canonical)*Y._pixelsPerMercatorPixel:o.aA(j,1,q),pe={u_matrix:p.projMatrix,u_extrude_scale:de,u_intensity:H,u_inv_rot_matrix:z5,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(te){pe.u_inv_rot_matrix=L,pe.u_merc_center=O,pe.u_tile_id=[p.canonical.x,p.canonical.y,1<({u_matrix:p,u_normalize_matrix:j,u_globe_matrix:L,u_merc_matrix:O,u_grid_matrix:q,u_tl_parent:H,u_scale_parent:pe,u_fade_t:Ce.mix,u_opacity:Ce.opacity*je.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:je.paint.get("raster-brightness-min"),u_brightness_high:je.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(je.paint.get("raster-saturation")),u_contrast_factor:o.dI(je.paint.get("raster-contrast")),u_spin_weights:Nz(je.paint.get("raster-hue-rotate")),u_perspective_transform:Me,u_raster_elevation:qe,u_zoom_transition:Y,u_merc_center:te,u_cutoff_params:de,u_colorization_mix:rP(o.dK,nt,pt),u_colorization_offset:$5(o.dK,rt,pt),u_color_ramp:$e,u_texture_offset:[ot/(vt+2*ot),vt/(vt+2*ot)],u_texture_res:[vt+2*ot,vt+2*ot],u_emissive_strength:Ut,u_zbias_factor:nP(E)});function Nz(E){E*=Math.PI/180;const p=Math.sin(E),j=Math.cos(E);return[(2*j+1)/3,(-Math.sqrt(3)*p-j+1)/3,(Math.sqrt(3)*p-j+1)/3]}const bx=.05,yge=(E,p,j,L,O,q,H,Y,te,de,pe,Ce)=>({u_matrix:E,u_normalize_matrix:p,u_globe_matrix:j,u_merc_matrix:L,u_grid_matrix:O,u_tl_parent:q,u_scale_parent:de,u_fade_t:pe.mix,u_opacity:pe.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ce,u_zoom_transition:H,u_merc_center:Y,u_cutoff_params:te}),vge=(E,p,j,L,O,q,H,Y,te,de)=>({u_particle_texture:E,u_particle_texture_side_len:p,u_tile_offset:j,u_velocity:L,u_color_ramp:q,u_velocity_res:O,u_max_speed:H,u_uv_offset:Y,u_data_scale:[255*te[0],255*te[1]],u_data_offset:de,u_particle_pos_scale:1.1,u_particle_pos_offset:[bx,bx]}),kz=(E,p,j,L,O,q,H,Y,te,de)=>({u_particle_texture:E,u_particle_texture_side_len:p,u_velocity:j,u_velocity_res:L,u_max_speed:O,u_speed_factor:q,u_reset_rate:H,u_rand_seed:Math.random(),u_uv_offset:Y,u_data_scale:[255*te[0],255*te[1]],u_data_offset:de,u_particle_pos_scale:1.1,u_particle_pos_offset:[bx,bx]}),Sz=o.bb(),U5=(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt,pt,vt,ot,Ut,Tt,$t)=>{const _t=O.transform,St={u_is_size_zoom_constant:+(E==="constant"||E==="source"),u_is_size_feature_constant:+(E==="constant"||E==="camera"),u_size_t:p?p.uSizeT:0,u_size:p?p.uSize:0,u_camera_to_center_distance:_t.getCameraToCenterDistance(pt),u_rotate_symbol:+j,u_aspect_ratio:_t.width/_t.height,u_fade_change:O.options.fadeDuration?O.symbolFadeChange:1,u_matrix:q,u_label_plane_matrix:H,u_coord_matrix:Y,u_is_text:+de,u_elevation_from_sea:te?1:0,u_pitch_with_map:+L,u_texsize:pe,u_texsize_icon:Ce,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Sz,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Sz,u_up_vector:[0,-1,0],u_color_adj_mat:Ut,u_icon_transition:Tt||0,u_gamma_scale:L?O.transform.getCameraToCenterDistance(pt)*Math.cos(O.terrain?0:O.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:$t||1,u_ground_shadow_factor:vt,u_inv_matrix:o.b7(o.bb(),H),u_normal_scale:ot,u_lutTexture:10,u_zoom:_t.zoom-Math.floor(_t.zoom),u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0]};return pt.name==="globe"&&(St.u_tile_id=[Me.canonical.x,Me.canonical.y,1<({u_matrix:E,u_emissive_strength:p,u_opacity:j,u_color:L}),n0=(E,p,j,L,O,q,H,Y,te)=>Object.assign(function(de,pe,Ce,je,Me,qe){const{width:$e,height:nt}=je.imageManager.getPixelSize(pe),rt=Math.pow(2,qe.tileID.overscaledZ),pt=qe.tileSize*Math.pow(2,je.transform.tileZoom)/rt,vt=pt*(qe.tileID.canonical.x+qe.tileID.wrap*rt),ot=pt*qe.tileID.canonical.y;return{u_image:0,u_pattern_tl:Ce.tl,u_pattern_br:Ce.br,u_texsize:[$e,nt],u_pattern_size:Ce.displaySize,u_pattern_units_to_pixels:Me?[je.transform.width,-1*je.transform.height]:[1/o.aA(qe,1,je.transform.tileZoom),1/o.aA(qe,1,je.transform.tileZoom)],u_pixel_coord_upper:[vt>>16,ot>>16],u_pixel_coord_lower:[65535&vt,65535&ot]}}(0,q,H,L,Y,te),{u_matrix:E,u_emissive_strength:p,u_opacity:j}),m_=new Float32Array(o.b9([])),o1=(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me=[0,0,0],qe,$e,nt)=>{const rt=O.style.light,pt=rt.properties.get("position"),vt=[-pt.x,-pt.y,pt.z],ot=o.dE();rt.properties.get("anchor")==="viewport"&&(o.dF(ot,-O.transform.angle),o.dG(vt,vt,ot));const Ut=pe.alphaMode==="MASK",Tt=rt.properties.get("color").toNonPremultipliedRenderColor(null),$t=je.paint.get("model-ambient-occlusion-intensity"),_t=je.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return _t.a=je.paint.get("model-color-mix-intensity").constantOr(0),nt&&(_t.r=nt[0],_t.g=nt[1],_t.b=nt[2],_t.a=nt[3]),$e&&(_t.r=$e.color.r,_t.g=$e.color.g,_t.b=$e.color.b,_t.a=$e.colorMix,Ce=$e.emissionStrength,q*=$e.opacity),{u_matrix:E,u_lighting_matrix:p,u_normal_matrix:j,u_node_matrix:L||m_,u_lightpos:vt,u_lightintensity:rt.properties.get("intensity"),u_lightcolor:[Tt.r,Tt.g,Tt.b],u_camera_pos:Me,u_opacity:q,u_baseTextureIsAlpha:0,u_alphaMask:+Ut,u_alphaCutoff:pe.alphaCutoff,u_baseColorFactor:H.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:Y.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:te,u_roughnessFactor:de,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:_t.toArray01(),u_aoIntensity:$t,u_emissive_strength:Ce,u_occlusionTextureTransform:qe||[0,0,0,0]}},aP=(E,p=m_,j=m_)=>({u_matrix:E,u_instance:p,u_node_matrix:j}),q5={fillExtrusion:E=>({u_matrix:new o.b$(E),u_lightpos:new o.bY(E),u_lightintensity:new o.bZ(E),u_lightcolor:new o.bY(E),u_vertical_gradient:new o.bZ(E),u_opacity:new o.bZ(E),u_edge_radius:new o.bZ(E),u_width_scale:new o.bZ(E),u_ao:new o.b_(E),u_height_type:new o.bX(E),u_base_type:new o.bX(E),u_tile_id:new o.bY(E),u_zoom_transition:new o.bZ(E),u_inv_rot_matrix:new o.b$(E),u_merc_center:new o.b_(E),u_up_dir:new o.bY(E),u_height_lift:new o.bZ(E),u_flood_light_color:new o.bY(E),u_vertical_scale:new o.bZ(E),u_flood_light_intensity:new o.bZ(E),u_ground_shadow_factor:new o.bY(E),u_front_cutoff_params:new o.bY(E)}),fillExtrusionDepth:E=>({u_matrix:new o.b$(E),u_edge_radius:new o.bZ(E),u_width_scale:new o.bZ(E),u_vertical_scale:new o.bZ(E),u_height_type:new o.bX(E),u_base_type:new o.bX(E)}),fillExtrusionPattern:E=>({u_matrix:new o.b$(E),u_lightpos:new o.bY(E),u_lightintensity:new o.bZ(E),u_lightcolor:new o.bY(E),u_vertical_gradient:new o.bZ(E),u_height_factor:new o.bZ(E),u_edge_radius:new o.bZ(E),u_width_scale:new o.bZ(E),u_ao:new o.b_(E),u_height_type:new o.bX(E),u_base_type:new o.bX(E),u_tile_id:new o.bY(E),u_zoom_transition:new o.bZ(E),u_inv_rot_matrix:new o.b$(E),u_merc_center:new o.b_(E),u_up_dir:new o.bY(E),u_height_lift:new o.bZ(E),u_image:new o.bX(E),u_texsize:new o.b_(E),u_pixel_coord_upper:new o.b_(E),u_pixel_coord_lower:new o.b_(E),u_tile_units_to_pixels:new o.bZ(E),u_opacity:new o.bZ(E),u_pattern_transition:new o.bZ(E)}),fillExtrusionGroundEffect:E=>({u_matrix:new o.b$(E),u_opacity:new o.bZ(E),u_ao_pass:new o.bZ(E),u_meter_to_tile:new o.bZ(E),u_ao:new o.b_(E),u_flood_light_intensity:new o.bZ(E),u_flood_light_color:new o.bY(E),u_attenuation:new o.bZ(E),u_edge_radius:new o.bZ(E),u_fb:new o.bX(E),u_fb_size:new o.bZ(E),u_dynamic_offset:new o.bZ(E)}),fill:E=>({u_matrix:new o.b$(E),u_emissive_strength:new o.bZ(E),u_ground_shadow_factor:new o.bY(E)}),fillPattern:E=>({u_matrix:new o.b$(E),u_emissive_strength:new o.bZ(E),u_image:new o.bX(E),u_texsize:new o.b_(E),u_pixel_coord_upper:new o.b_(E),u_pixel_coord_lower:new o.b_(E),u_tile_units_to_pixels:new o.bZ(E),u_ground_shadow_factor:new o.bY(E),u_pattern_transition:new o.bZ(E)}),fillOutline:E=>({u_matrix:new o.b$(E),u_emissive_strength:new o.bZ(E),u_world:new o.b_(E),u_ground_shadow_factor:new o.bY(E)}),fillOutlinePattern:E=>({u_matrix:new o.b$(E),u_emissive_strength:new o.bZ(E),u_world:new o.b_(E),u_image:new o.bX(E),u_texsize:new o.b_(E),u_pixel_coord_upper:new o.b_(E),u_pixel_coord_lower:new o.b_(E),u_tile_units_to_pixels:new o.bZ(E),u_ground_shadow_factor:new o.bY(E),u_pattern_transition:new o.bZ(E)}),lineBlendComposite:E=>({u_image:new o.bX(E),u_opacity:new o.bZ(E),u_blend_mode:new o.bX(E)}),building:E=>({u_matrix:new o.b$(E),u_normal_matrix:new o.b$(E),u_opacity:new o.bZ(E),u_faux_facade_ao_intensity:new o.bZ(E),u_camera_pos:new o.bY(E),u_tile_to_meter:new o.bZ(E),u_facade_emissive_chance:new o.bZ(E),u_flood_light_color:new o.bY(E),u_flood_light_intensity:new o.bZ(E),u_front_cutoff_params:new o.bY(E)}),buildingBloom:E=>({u_matrix:new o.b$(E)}),buildingDepth:E=>({u_matrix:new o.b$(E)}),elevatedStructuresDepth:E=>({u_matrix:new o.b$(E),u_depth_bias:new o.bZ(E)}),elevatedStructures:E=>({u_matrix:new o.b$(E),u_ground_shadow_factor:new o.bY(E)}),elevatedStructuresDepthReconstruct:E=>({u_matrix:new o.b$(E),u_camera_pos:new o.bY(E),u_depth_bias:new o.bZ(E),u_height_scale:new o.bZ(E),u_reset_depth:new o.bZ(E)}),circle:o.dO,collisionBox:E=>({u_matrix:new o.b$(E),u_inv_rot_matrix:new o.b$(E),u_camera_to_center_distance:new o.bZ(E),u_extrude_scale:new o.b_(E),u_zoom_transition:new o.bZ(E),u_merc_center:new o.b_(E),u_tile_id:new o.bY(E)}),collisionCircle:E=>({u_matrix:new o.b$(E),u_inv_matrix:new o.b$(E),u_camera_to_center_distance:new o.bZ(E),u_viewport_size:new o.b_(E)}),debug:E=>({u_color:new o.dl(E),u_matrix:new o.b$(E),u_overlay:new o.bX(E),u_overlay_scale:new o.bZ(E)}),clippingMask:E=>({u_matrix:new o.b$(E)}),heatmap:E=>({u_extrude_scale:new o.bZ(E),u_intensity:new o.bZ(E),u_matrix:new o.b$(E),u_inv_rot_matrix:new o.b$(E),u_merc_center:new o.b_(E),u_tile_id:new o.bY(E),u_zoom_transition:new o.bZ(E),u_up_dir:new o.bY(E)}),heatmapTexture:E=>({u_image:new o.bX(E),u_color_ramp:new o.bX(E),u_opacity:new o.bZ(E)}),hillshade:E=>({u_matrix:new o.b$(E),u_image:new o.bX(E),u_latrange:new o.b_(E),u_light:new o.b_(E),u_shadow:new o.dl(E),u_highlight:new o.dl(E),u_emissive_strength:new o.bZ(E),u_accent:new o.dl(E)}),hillshadePrepare:E=>({u_matrix:new o.b$(E),u_image:new o.bX(E),u_dimension:new o.b_(E),u_zoom:new o.bZ(E)}),line:o.dN,linePattern:o.dM,raster:E=>({u_matrix:new o.b$(E),u_normalize_matrix:new o.b$(E),u_globe_matrix:new o.b$(E),u_merc_matrix:new o.b$(E),u_grid_matrix:new o.dm(E),u_tl_parent:new o.b_(E),u_scale_parent:new o.bZ(E),u_fade_t:new o.bZ(E),u_opacity:new o.bZ(E),u_image0:new o.bX(E),u_image1:new o.bX(E),u_brightness_low:new o.bZ(E),u_brightness_high:new o.bZ(E),u_saturation_factor:new o.bZ(E),u_contrast_factor:new o.bZ(E),u_spin_weights:new o.bY(E),u_perspective_transform:new o.b_(E),u_raster_elevation:new o.bZ(E),u_zoom_transition:new o.bZ(E),u_merc_center:new o.b_(E),u_cutoff_params:new o.cO(E),u_colorization_mix:new o.cO(E),u_colorization_offset:new o.bZ(E),u_color_ramp:new o.bX(E),u_texture_offset:new o.b_(E),u_texture_res:new o.b_(E),u_emissive_strength:new o.bZ(E),u_zbias_factor:new o.bZ(E)}),rasterParticle:E=>({u_matrix:new o.b$(E),u_normalize_matrix:new o.b$(E),u_globe_matrix:new o.b$(E),u_merc_matrix:new o.b$(E),u_grid_matrix:new o.dm(E),u_tl_parent:new o.b_(E),u_scale_parent:new o.bZ(E),u_fade_t:new o.bZ(E),u_opacity:new o.bZ(E),u_image0:new o.bX(E),u_image1:new o.bX(E),u_raster_elevation:new o.bZ(E),u_zoom_transition:new o.bZ(E),u_merc_center:new o.b_(E),u_cutoff_params:new o.cO(E)}),rasterParticleTexture:E=>({u_texture:new o.bX(E),u_opacity:new o.bZ(E)}),rasterParticleDraw:E=>({u_particle_texture:new o.bX(E),u_particle_texture_side_len:new o.bZ(E),u_tile_offset:new o.b_(E),u_velocity:new o.bX(E),u_color_ramp:new o.bX(E),u_velocity_res:new o.b_(E),u_max_speed:new o.bZ(E),u_uv_offset:new o.b_(E),u_data_scale:new o.b_(E),u_data_offset:new o.bZ(E),u_particle_pos_scale:new o.bZ(E),u_particle_pos_offset:new o.b_(E)}),rasterParticleUpdate:E=>({u_particle_texture:new o.bX(E),u_particle_texture_side_len:new o.bZ(E),u_velocity:new o.bX(E),u_velocity_res:new o.b_(E),u_max_speed:new o.bZ(E),u_speed_factor:new o.bZ(E),u_reset_rate:new o.bZ(E),u_rand_seed:new o.bZ(E),u_uv_offset:new o.b_(E),u_data_scale:new o.b_(E),u_data_offset:new o.bZ(E),u_particle_pos_scale:new o.bZ(E),u_particle_pos_offset:new o.b_(E)}),symbol:E=>({u_is_size_zoom_constant:new o.bX(E),u_is_size_feature_constant:new o.bX(E),u_size_t:new o.bZ(E),u_size:new o.bZ(E),u_camera_to_center_distance:new o.bZ(E),u_rotate_symbol:new o.bX(E),u_aspect_ratio:new o.bZ(E),u_fade_change:new o.bZ(E),u_matrix:new o.b$(E),u_label_plane_matrix:new o.b$(E),u_coord_matrix:new o.b$(E),u_is_text:new o.bX(E),u_elevation_from_sea:new o.bX(E),u_pitch_with_map:new o.bX(E),u_texsize:new o.b_(E),u_texsize_icon:new o.b_(E),u_texture:new o.bX(E),u_texture_icon:new o.bX(E),u_gamma_scale:new o.bZ(E),u_device_pixel_ratio:new o.bZ(E),u_tile_id:new o.bY(E),u_zoom_transition:new o.bZ(E),u_inv_rot_matrix:new o.b$(E),u_merc_center:new o.b_(E),u_camera_forward:new o.bY(E),u_tile_matrix:new o.b$(E),u_up_vector:new o.bY(E),u_ecef_origin:new o.bY(E),u_is_halo:new o.bX(E),u_icon_transition:new o.bZ(E),u_color_adj_mat:new o.b$(E),u_scale_factor:new o.bZ(E),u_ground_shadow_factor:new o.bY(E),u_inv_matrix:new o.b$(E),u_normal_scale:new o.bZ(E),u_lutTexture:new o.bX(E),u_zoom:new o.bZ(E),u_spp_fill_np_color:new o.cO(E),u_spp_halo_np_color:new o.cO(E),u_spp_opacity:new o.bZ(E),u_spp_halo_width:new o.bZ(E),u_spp_halo_blur:new o.bZ(E),u_spp_emissive_strength:new o.bZ(E),u_spp_occlusion_opacity:new o.bZ(E),u_spp_z_offset:new o.bZ(E),u_spp_translate_rotation:new o.b_(E)}),background:E=>({u_matrix:new o.b$(E),u_emissive_strength:new o.bZ(E),u_opacity:new o.bZ(E),u_color:new o.dl(E)}),backgroundPattern:E=>({u_matrix:new o.b$(E),u_emissive_strength:new o.bZ(E),u_opacity:new o.bZ(E),u_image:new o.bX(E),u_pattern_tl:new o.b_(E),u_pattern_br:new o.b_(E),u_texsize:new o.b_(E),u_pattern_size:new o.b_(E),u_pixel_coord_upper:new o.b_(E),u_pixel_coord_lower:new o.b_(E),u_pattern_units_to_pixels:new o.b_(E)}),terrainRaster:E=>({u_matrix:new o.b$(E),u_image0:new o.bX(E),u_image1:new o.bX(E),u_skirt_height:new o.bZ(E),u_ground_shadow_factor:new o.bY(E),u_emissive_texture_available:new o.bZ(E)}),skybox:E=>({u_matrix:new o.b$(E),u_sun_direction:new o.bY(E),u_cubemap:new o.bX(E),u_opacity:new o.bZ(E),u_temporal_offset:new o.bZ(E)}),skyboxGradient:E=>({u_matrix:new o.b$(E),u_color_ramp:new o.bX(E),u_center_direction:new o.bY(E),u_radius:new o.bZ(E),u_opacity:new o.bZ(E),u_temporal_offset:new o.bZ(E)}),skyboxCapture:E=>({u_matrix_3f:new o.dm(E),u_sun_direction:new o.bY(E),u_sun_intensity:new o.bZ(E),u_color_tint_r:new o.cO(E),u_color_tint_m:new o.cO(E),u_luminance:new o.bZ(E)}),globeRaster:E=>({u_proj_matrix:new o.b$(E),u_globe_matrix:new o.b$(E),u_normalize_matrix:new o.b$(E),u_merc_matrix:new o.b$(E),u_zoom_transition:new o.bZ(E),u_merc_center:new o.b_(E),u_image0:new o.bX(E),u_image1:new o.bX(E),u_grid_matrix:new o.dm(E),u_skirt_height:new o.bZ(E),u_far_z_cutoff:new o.bZ(E),u_frustum_tl:new o.bY(E),u_frustum_tr:new o.bY(E),u_frustum_br:new o.bY(E),u_frustum_bl:new o.bY(E),u_globe_pos:new o.bY(E),u_globe_radius:new o.bZ(E),u_viewport:new o.b_(E),u_emissive_texture_available:new o.bZ(E)}),globeAtmosphere:E=>({u_frustum_tl:new o.bY(E),u_frustum_tr:new o.bY(E),u_frustum_br:new o.bY(E),u_frustum_bl:new o.bY(E),u_horizon:new o.bZ(E),u_transition:new o.bZ(E),u_fadeout_range:new o.bZ(E),u_atmosphere_fog_color:new o.cO(E),u_high_color:new o.cO(E),u_space_color:new o.cO(E),u_temporal_offset:new o.bZ(E),u_horizon_angle:new o.bZ(E)}),model:E=>({u_matrix:new o.b$(E),u_lighting_matrix:new o.b$(E),u_normal_matrix:new o.b$(E),u_node_matrix:new o.b$(E),u_lightpos:new o.bY(E),u_lightintensity:new o.bZ(E),u_lightcolor:new o.bY(E),u_camera_pos:new o.bY(E),u_opacity:new o.bZ(E),u_baseColorFactor:new o.cO(E),u_emissiveFactor:new o.cO(E),u_metallicFactor:new o.bZ(E),u_roughnessFactor:new o.bZ(E),u_baseTextureIsAlpha:new o.bX(E),u_alphaMask:new o.bX(E),u_alphaCutoff:new o.bZ(E),u_baseColorTexture:new o.bX(E),u_metallicRoughnessTexture:new o.bX(E),u_normalTexture:new o.bX(E),u_occlusionTexture:new o.bX(E),u_emissionTexture:new o.bX(E),u_lutTexture:new o.bX(E),u_color_mix:new o.cO(E),u_aoIntensity:new o.bZ(E),u_emissive_strength:new o.bZ(E),u_occlusionTextureTransform:new o.cO(E)}),modelDepth:E=>({u_matrix:new o.b$(E),u_instance:new o.b$(E),u_node_matrix:new o.b$(E)}),groundShadow:E=>({u_matrix:new o.b$(E),u_ground_shadow_factor:new o.bY(E)}),stars:E=>({u_matrix:new o.b$(E),u_up:new o.bY(E),u_right:new o.bY(E),u_intensity_multiplier:new o.bZ(E)}),snowParticle:E=>({u_modelview:new o.b$(E),u_projection:new o.b$(E),u_time:new o.bZ(E),u_cam_pos:new o.bY(E),u_velocityConeAperture:new o.bZ(E),u_velocity:new o.bZ(E),u_horizontalOscillationRadius:new o.bZ(E),u_horizontalOscillationRate:new o.bZ(E),u_boxSize:new o.bZ(E),u_billboardSize:new o.bZ(E),u_simpleShapeParameters:new o.b_(E),u_screenSize:new o.b_(E),u_thinningCenterPos:new o.b_(E),u_thinningShape:new o.bY(E),u_thinningAffectedRatio:new o.bZ(E),u_thinningParticleOffset:new o.bZ(E),u_particleColor:new o.cO(E),u_direction:new o.bY(E)}),rainParticle:E=>({u_modelview:new o.b$(E),u_projection:new o.b$(E),u_time:new o.bZ(E),u_cam_pos:new o.bY(E),u_texScreen:new o.bX(E),u_velocityConeAperture:new o.bZ(E),u_velocity:new o.bZ(E),u_boxSize:new o.bZ(E),u_rainDropletSize:new o.b_(E),u_distortionStrength:new o.bZ(E),u_rainDirection:new o.bY(E),u_color:new o.cO(E),u_screenSize:new o.b_(E),u_thinningCenterPos:new o.b_(E),u_thinningShape:new o.bY(E),u_thinningAffectedRatio:new o.bZ(E),u_thinningParticleOffset:new o.bZ(E),u_shapeDirectionalPower:new o.bZ(E),u_shapeNormalPower:new o.bZ(E),u_mode:new o.bZ(E)}),vignette:E=>({u_vignetteShape:new o.bY(E),u_vignetteColor:new o.cO(E)}),occlusion:E=>({u_matrix:new o.b$(E),u_anchorPos:new o.bY(E),u_screenSizePx:new o.b_(E),u_occluderSizePx:new o.b_(E),u_color:new o.cO(E)})};class mp{constructor(p,j,L,O){this.id=mp.uniqueIdxCounter,mp.uniqueIdxCounter++,this.context=p;const q=p.gl;this.buffer=q.createBuffer(),this.dynamicDraw=!!L,this.context.unbindVAO(),p.bindElementBuffer.set(this.buffer),q.bufferData(q.ELEMENT_ARRAY_BUFFER,j.arrayBuffer,this.dynamicDraw?q.DYNAMIC_DRAW:q.STATIC_DRAW),this.dynamicDraw||O||j.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(p){this.id=mp.uniqueIdxCounter,mp.uniqueIdxCounter++;const j=this.context.gl;this.context.unbindVAO(),this.bind(),j.bufferSubData(j.ELEMENT_ARRAY_BUFFER,0,p.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}mp.uniqueIdxCounter=0;const iP={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Cz{constructor(p,j,L,O,q,H){this.length=j.length,this.attributes=L,this.itemSize=j.bytesPerElement,this.dynamicDraw=O,this.instanceCount=H,this.context=p;const Y=p.gl;this.buffer=Y.createBuffer(),p.bindVertexBuffer.set(this.buffer),Y.bufferData(Y.ARRAY_BUFFER,j.arrayBuffer,this.dynamicDraw?Y.DYNAMIC_DRAW:Y.STATIC_DRAW),this.dynamicDraw||q||j.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(p){const j=this.context.gl;this.bind(),j.bufferSubData(j.ARRAY_BUFFER,0,p.arrayBuffer)}enableAttributes(p,j){for(const L of this.attributes){const O=j.getAttributeLocation(p,L.name);O!==-1&&p.enableVertexAttribArray(O)}}setVertexAttribPointers(p,j,L){for(const O of this.attributes){const q=j.getAttributeLocation(p,O.name);if(q!==-1){const H=O.offset+this.itemSize*(L||0);O.type==="Float32"?p.vertexAttribPointer(q,O.components,p.FLOAT,!1,this.itemSize,H):p.vertexAttribIPointer(q,O.components,p[iP[O.type]],this.itemSize,H)}}}setVertexAttribDivisor(p,j,L){for(let O=0;O0&&p.vertexAttribDivisor(q,L)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class U2{constructor(p,j,L,O,q){this.context=p,this.width=j,this.height=L;const H=this.framebuffer=p.gl.createFramebuffer();O>0&&(this.colorAttachment0=new d_(p,H,0)),O>1&&(this.colorAttachment1=new d_(p,H,1)),q&&(this.depthAttachmentType=q,this.depthAttachment=q==="renderbuffer"?new JL(p,H):new mz(p,H))}static createWithTexture(p,j,L,O,q){const H=p.gl;if(p.activeTexture.set(H.TEXTURE1),p.viewport.set([0,0,L,O]),j&&j.width===L&&j.height===O)return H.bindTexture(H.TEXTURE_2D,j.colorAttachment0.get()),p.bindFramebuffer.set(j.framebuffer),j;j&&j.destroy();const Y=new o.T(p,{width:L,height:O,data:null},p.extRenderToTextureHalfFloat?p.gl.RGBA16F:p.gl.RGBA8);Y.bind(H.LINEAR,H.CLAMP_TO_EDGE);const te=p.createFramebuffer(L,O,1,null);if(te.colorAttachment0.set(Y.texture),q){const de=p.createRenderbuffer(H.DEPTH24_STENCIL8,L,O);p.bindFramebuffer.set(te.framebuffer),H.framebufferRenderbuffer(H.FRAMEBUFFER,H.DEPTH_STENCIL_ATTACHMENT,H.RENDERBUFFER,de),te._stencilRbo=de}return te}createColorAttachment(p,j){j===0?this.colorAttachment0=new d_(p,this.framebuffer,0):j===1&&(this.colorAttachment1=new d_(p,this.framebuffer,1))}removeColorAttachment(p,j){const L=this.context.gl;let O;j===0?(O=this.colorAttachment0.get(),this.colorAttachment0=void 0):j===1&&(O=this.colorAttachment1.get(),this.colorAttachment1=void 0),O&&L.deleteTexture(O)}destroy(){const p=this.context.gl;if(this.colorAttachment0){const j=this.colorAttachment0.get();j&&p.deleteTexture(j)}if(this.colorAttachment1){const j=this.colorAttachment1.get();j&&p.deleteTexture(j)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const j=this.depthAttachment.get();j&&p.deleteRenderbuffer(j)}else{const j=this.depthAttachment.get();j&&p.deleteTexture(j)}this._stencilRbo&&(p.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),p.deleteFramebuffer(this.framebuffer)}}class f_{constructor(p,j){this.gl=p,this.clearColor=new az(this),this.clearDepth=new cge(this),this.clearStencil=new k5(this),this.colorMask=new dge(this),this.depthMask=new iz(this),this.stencilMask=new WL(this),this.stencilFunc=new S5(this),this.stencilOp=new KL(this),this.stencilTest=new n1(this),this.depthRange=new a1(this),this.depthTest=new o_(this),this.depthFunc=new vx(this),this.blend=new oz(this),this.blendFunc=new YL(this),this.blendColor=new lz(this),this.blendEquation=new l_(this),this.cullFace=new C5(this),this.cullFaceSide=new T5(this),this.frontFace=new ZL(this),this.program=new E5(this),this.activeTexture=new M2(this),this.viewport=new cz(this),this.bindFramebuffer=new dz(this),this.bindRenderbuffer=new uz(this),this.bindTexture=new c_(this),this.bindVertexBuffer=new hz(this),this.bindElementBuffer=new uge(this),this.bindVertexArrayOES=new hge(this),this.pixelStoreUnpack=new mge(this),this.pixelStoreUnpackPremultiplyAlpha=new XL(this),this.pixelStoreUnpackFlipY=new QL(this),this.options=j?Object.assign({},j):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=p.getExtension("EXT_texture_filter_anisotropic")||p.getExtension("MOZ_EXT_texture_filter_anisotropic")||p.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=p.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=p.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=p.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=p.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=j&&!!j.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=j&&!!j.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=p.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=p.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=p.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=p.getParameter(p.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(p.getParameter(p.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=p.getParameter(p.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=p.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(p,j,L){return new mp(this,p,j,L)}createVertexBuffer(p,j,L,O,q){return new Cz(this,p,j,L,O,q)}createRenderbuffer(p,j,L){const O=this.gl,q=O.createRenderbuffer();return this.bindRenderbuffer.set(q),O.renderbufferStorage(O.RENDERBUFFER,p,j,L),this.bindRenderbuffer.set(null),q}createFramebuffer(p,j,L,O){return new U2(this,p,j,L,O)}clear({color:p,depth:j,stencil:L,colorMask:O}){const q=this.gl;let H=0;p&&(H|=q.COLOR_BUFFER_BIT,this.clearColor.set(p.toNonPremultipliedRenderColor(null)),this.colorMask.set(O||[!0,!0,!0,!0])),j!==void 0&&(H|=q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(j),this.depthMask.set(!0)),L!==void 0&&(H|=q.STENCIL_BUFFER_BIT,this.clearStencil.set(L),this.stencilMask.set(255)),q.clear(H)}setCullFace(p){p.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(p.mode),this.frontFace.set(p.frontFace))}setDepthMode(p){p.func!==this.gl.ALWAYS||p.mask?(this.depthTest.set(!0),this.depthFunc.set(p.func),this.depthMask.set(p.mask),this.depthRange.set(p.range)):this.depthTest.set(!1)}setStencilMode(p){p.test.func!==this.gl.ALWAYS||p.mask?(this.stencilTest.set(!0),this.stencilMask.set(p.mask),this.stencilOp.set([p.fail,p.depthFail,p.pass]),this.stencilFunc.set({func:p.test.func,ref:p.ref,mask:p.test.mask})):this.stencilTest.set(!1)}setColorMode(p){o.b6(p.blendFunction,Tn.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(p.blendFunction),this.blendColor.set(p.blendColor),p.blendEquation?this.blendEquation.set(p.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(p.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let l1;function Dr(E,p,j,L,O,q,H){const Y=E.context,te=Y.gl,de=E.transform,pe=[o.aH(de.center.lng),o.aL(de.center.lat)],Ce=j.layout.get("symbol-placement"),je=j.layout.get("text-variable-anchor"),Me=j.layout.get("icon-rotation-alignment")==="map",qe=j.layout.get("text-rotation-alignment")==="map",$e=Ce!=="point",nt=[];let rt=0,pt=0;for(let _t=0;_t0){const Kr=o.bb(),Er=Js;o.cz(Kr,Zt.placementInvProjMatrix,de.glCoordMatrix),o.cz(Kr,Kr,Zt.placementViewportMatrix),nt.push({circleArray:Us,circleOffset:pt,transform:Er,invTransform:Kr,projection:Zt.getProjection()}),rt+=Us.length/4,pt=rt}if(!er)continue;E.terrain&&E.terrain.setupElevationDraw(Rt,cr);const Br=vs?[St.canonical.x,St.canonical.y,1<=0&&(Me[vt.associatedIconIndex]={x:qt,y:xs,z:as,angle:us})}else si(Tt,Ce)}if(de){je.clear();const pt=E.icon.placedSymbolArray;for(let vt=0;vt{let qn=[0,0,0];if(ni){const uo=E.style.directionalLight,Ei=E.style.ambientLight;uo&&Ei&&(qn=up(E.style,uo,Ei))}return qn},la=ni=>{if(E.context.disableSymbolUBO)return;ni.push("USE_PAINT_PROPERTIES_UBO");const qn=Math.floor(E.context.maxUniformBlockSize/4),uo=Math.floor(qn/4);ni.push(`MAX_UBO_SIZE_VEC4 ${uo}u`)},Dn=ni=>{St.depthOcclusionForSymbolsAndCircles&&(j.hasOcclusionOpacityProperties||E.terrain)&&(ni.push("DEPTH_D24"),ni.push("DEPTH_OCCLUSION"))},Wa=ni=>{j.lut&&!Tt&&(j.lut.texture||(j.lut.texture=new o.dR(E.context,j.lut.image,[j.lut.image.height,j.lut.image.height,j.lut.image.height],$t.gl.RGBA8)),$t.activeTexture.set($t.gl.TEXTURE0+10),j.lut.texture&&j.lut.texture.bind($t.gl.LINEAR,$t.gl.CLAMP_TO_EDGE),ni.push("APPLY_LUT_ON_GPU"))},Ti=()=>{const ni=Rt&&j.layout.get("symbol-placement")!=="point",qn=[];Dn(qn),Wa(qn);const uo=ni||Fn,Ei=Us.elevationType==="road",jl=E.shadowRenderer,_a=Ei&&qt&&!!jl&&jl.enabled,Ri=pn(_a),Ul=Ei&&qt&&!E.terrain?Qt:Hs,Ud=j.paint.get("icon-image-cross-fade");E.terrainRenderModeElevated()&&qt&&qn.push("PITCH_WITH_MAP_TERRAIN"),Br&&(qn.push("PROJECTION_GLOBE_VIEW"),uo&&qn.push("PROJECTED_POS_ON_VIEWPORT")),Ud>0&&Us.hasAnySecondaryIcon&&qn.push("ICON_TRANSITION"),!Us.icon.zOffsetVertexBuffer||Ei&&E.terrain||qn.push("Z_OFFSET"),rt===0&&pt===0&&vt===0&&ot===1||qn.push("COLOR_ADJUSTMENT"),Us.sdfIcons&&qn.push("RENDER_SDF"),_a&&qn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ei&&qt&&!E.terrain&&Us.icon.orientationVertexBuffer&&qn.push("ELEVATED_ROADS"),la(qn);const rc=$t.disableSymbolUBO?Us.icon.programConfigurations.get(j.id):null,Yc=E.getOrCreateProgram("symbol",{config:rc,defines:qn}),lm=er.imageAtlasTexture?er.imageAtlasTexture.size:[0,0],fi=Us.iconSizeData,$m=o.bj(fi,St.zoom),Um=qt||!St.isOrthographic,qi=yx(Er,er.tileID.canonical,qt,Rt,St,Us.getProjection(),Fr),Yi=Zy(Er,er.tileID.canonical,qt,Rt,St,Us.getProjection(),Fr),ji=Us.icon.uboBinder&&Us.icon.uboBinder.cachedHeader&&256&Us.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:Y,gl=E.translatePosMatrix(Yi,er,ji,de,!0),lu=E.translatePosMatrix(Er,er,ji,de),Vo=uo?q2:qi,cm=Rt&&!qt&&!ni;let i0=cr;!vs&&!St.mercatorFromTransition||Rt||(i0=Rg(St));const x1=Br?i0:cr,g1=j.getColorAdjustmentMatrix(rt,pt,vt,ot),b_=U5(fi.kind,$m,cm,qt,E,lu,Vo,gl,Ut,!1,lm,[0,0],0,Js,Kr,Ht,Pn,x1,Us.getProjection(),Ri,oa,g1,Ud,null),Ug=er.imageAtlasTexture?er.imageAtlasTexture:null,kx=j.layout.get("icon-size").constantOr(0)!==1||Us.iconsNeedLinear,__=Us.sdfIcons||E.options.rotating||E.options.zooming||kx||Um?_t.LINEAR:_t.NEAREST,Ph=Us.sdfIcons&&j.paint.get("icon-halo-width").constantOr(1)!==0,o0=E.terrain&&qt&&ni?o.b7(o.bb(),qi):q2;if(ni&&Us.icon){const l0=o.bu.getAtTileOffsetFunc(Js,St.center.lat,St.worldSize,Us.getProjection()),c0=Pm(Er,er.tileID.canonical,qt,Rt,St,Us.getProjection(),Fr),mT=j.layout.get("icon-size-scale-range"),w_=o.aC(E.scaleFactor,mT[0],mT[1]);kt(Us,Er,E,!1,c0,Yi,qt,$e,l0,Js,w_)}return{program:Yc,buffers:Us.icon,uniformValues:b_,atlasTexture:Ug,atlasTextureIcon:null,atlasInterpolation:__,atlasInterpolationIcon:null,isSDF:Us.sdfIcons,hasHalo:Ph,depthMode:Ul,tile:er,renderWithShadows:_a,labelPlaneMatrixInv:o0}},yo=()=>{const ni=Zt&&j.layout.get("symbol-placement")!=="point",qn=[],uo=ni||us||Fn,Ei=Us.elevationType==="road",jl=E.shadowRenderer,_a=Ei&&xs&&!!jl&&jl.enabled,Ri=pn(_a),Ul=Ei&&xs&&!E.terrain?Qt:Hs;E.terrainRenderModeElevated()&&xs&&qn.push("PITCH_WITH_MAP_TERRAIN"),Br&&(qn.push("PROJECTION_GLOBE_VIEW"),uo&&qn.push("PROJECTED_POS_ON_VIEWPORT")),!Us.text.zOffsetVertexBuffer||Ei&&E.terrain||qn.push("Z_OFFSET"),Us.iconsInText&&qn.push("RENDER_TEXT_AND_SYMBOL"),qn.push("RENDER_SDF"),_a&&qn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ei&&xs&&!E.terrain&&Us.text.orientationVertexBuffer&&qn.push("ELEVATED_ROADS"),Dn(qn),la(qn);const Ud=$t.disableSymbolUBO?Us.text.programConfigurations.get(j.id):null,rc=E.getOrCreateProgram("symbol",{config:Ud,defines:qn});let Yc,lm=[0,0],fi=null;const $m=Us.textSizeData;Us.iconsInText&&(lm=er.imageAtlasTexture?er.imageAtlasTexture.size:[0,0],fi=er.imageAtlasTexture?er.imageAtlasTexture:null,Yc=xs||!St.isOrthographic||E.options.rotating||E.options.zooming||$m.kind==="composite"||$m.kind==="camera"?_t.LINEAR:_t.NEAREST);const Um=er.glyphAtlasTexture?er.glyphAtlasTexture.size:[0,0],qi=j.layout.get("text-size-scale-range"),Yi=o.aC(E.scaleFactor,qi[0],qi[1]),ji=o.bj($m,St.zoom,Yi),gl=yx(Er,er.tileID.canonical,xs,Zt,St,Us.getProjection(),Fr),lu=Zy(Er,er.tileID.canonical,xs,Zt,St,Us.getProjection(),Fr),Vo=Us.text.uboBinder&&Us.text.uboBinder.cachedHeader&&256&Us.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:te,cm=E.translatePosMatrix(lu,er,Vo,pe,!0),i0=E.translatePosMatrix(Er,er,Vo,pe),x1=uo?q2:gl,g1=Zt&&!xs&&!ni;let b_=cr;!vs&&!St.mercatorFromTransition||Zt||(b_=Rg(St));const Ug=U5($m.kind,ji,g1,xs,E,i0,x1,cm,Ut,!0,Um,lm,0,Js,Kr,Ht,Pn,Br?b_:cr,Us.getProjection(),Ri,oa,null,null,Yi),kx=er.glyphAtlasTexture?er.glyphAtlasTexture:null,__=_t.LINEAR,Ph=j.paint.get("text-halo-width").constantOr(1)!==0,o0=E.terrain&&xs&&ni?o.b7(o.bb(),gl):q2;if(ni&&Us.text){const l0=o.bu.getAtTileOffsetFunc(Js,St.center.lat,St.worldSize,Us.getProjection()),c0=Pm(Er,er.tileID.canonical,xs,Zt,St,Us.getProjection(),Fr);kt(Us,Er,E,!0,c0,lu,xs,nt,l0,Js,Yi)}return{program:rc,buffers:Us.text,uniformValues:Ug,atlasTexture:kx,atlasTextureIcon:fi,atlasInterpolation:__,atlasInterpolationIcon:Yc,isSDF:!0,hasHalo:Ph,depthMode:Ul,tile:er,renderWithShadows:_a,labelPlaneMatrixInv:o0}},zi=Us.icon.segments.get().length,ri=Us.text.segments.get().length,Jn=zi&&!H.onlyText?Ti():null,ea=ri&&!H.onlyIcons?yo():null,$i=j.paint.get("icon-opacity").constantOr(1),No=j.paint.get("text-opacity").constantOr(1);if(as&&Us.canOverlap){Os=!0;const ni=$i&&!H.onlyText?Us.icon.segments.get():[],qn=No&&!H.onlyIcons?Us.text.segments.get():[];for(const uo of ni)ks.push({segments:new o.dy([uo]),sortKey:uo.sortKey,state:Jn});for(const uo of qn)ks.push({segments:new o.dy([uo]),sortKey:uo.sortKey,state:ea})}else H.onlyText||ks.push({segments:$i?Us.icon.segments:new o.dy([]),sortKey:0,state:Jn}),H.onlyIcons||ks.push({segments:No?Us.text.segments:new o.dy([]),sortKey:0,state:ea})}Os&&ks.sort((Js,er)=>Js.sortKey-er.sortKey);for(const Js of ks){const er=Js.state;if(er)if(E.terrain?E.terrain.setupElevationDraw(er.tile,er.program,{useDepthForOcclusion:St.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:er.labelPlaneMatrixInv}):E.setupDepthForOcclusion(St.depthOcclusionForSymbolsAndCircles,er.program),$t.activeTexture.set(_t.TEXTURE0),er.atlasTexture&&er.atlasTexture.bind(er.atlasInterpolation,_t.CLAMP_TO_EDGE,!0),er.atlasTextureIcon&&($t.activeTexture.set(_t.TEXTURE1),er.atlasTextureIcon&&er.atlasTextureIcon.bind(er.atlasInterpolationIcon,_t.CLAMP_TO_EDGE,!0)),er.renderWithShadows&&E.shadowRenderer.setupShadows(er.tile.tileID.toUnwrapped(),er.program,"vector-tile"),E.uploadCommonLightUniforms(E.context,er.program),er.hasHalo){const Us=er.uniformValues;Us.u_is_halo=1,H5(er.buffers,Js.segments,j,E,er.program,er.depthMode,O,q,Us,2),Us.u_is_halo=0}else{if(er.isSDF){const Us=er.uniformValues;er.hasHalo&&(Us.u_is_halo=1,H5(er.buffers,Js.segments,j,E,er.program,er.depthMode,O,q,Us,1)),Us.u_is_halo=0}H5(er.buffers,Js.segments,j,E,er.program,er.depthMode,O,q,er.uniformValues,1)}}}function H5(E,p,j,L,O,q,H,Y,te,de){const pe=L.context,Ce=pe.gl,je=[E.dynamicLayoutVertexBuffer,E.opacityVertexBuffer,E.iconTransitioningVertexBuffer,E.globeExtVertexBuffer,E.zOffsetVertexBuffer,E.orientationVertexBuffer];E.featureIdBuffer&&je.push(E.featureIdBuffer);const Me=E.uboBinder?null:E.programConfigurations.get(j.id);if(E.uboBinder){E.uboBinder.layer=j;const nt=L.transform.zoom,rt=L.style.getBrightness?L.style.getBrightness():null,pt=E.uboBinder.getConstantUniformValues(nt,rt);te.u_spp_fill_np_color=pt.fill_np_color,te.u_spp_halo_np_color=pt.halo_np_color,te.u_spp_opacity=pt.opacity,te.u_spp_halo_width=pt.halo_width,te.u_spp_halo_blur=pt.halo_blur,te.u_spp_emissive_strength=pt.emissive_strength,te.u_spp_occlusion_opacity=pt.occlusion_opacity,te.u_spp_z_offset=pt.z_offset;const vt=j.paint.get(E.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),ot=E.uboBinder.cachedHeader&&256&E.uboBinder.cachedHeader.dataDrivenMask&&vt==="map"?L.transform.angle:0;te.u_spp_translate_rotation=[Math.cos(ot),Math.sin(ot)]}const{batchIndices:qe,batchSegments:$e}=E.getBatchGrouping(p);for(const nt of qe){const rt=$e.get(nt);E.uboBinder&&E.uboBinder.bind(pe,O.program,nt),O.draw(L,Ce.TRIANGLES,q,H,Y,vn.disabled,te,j.id,E.layoutVertexBuffer,E.indexBuffer,rt,j.paint,L.transform.zoom,Me,je,de)}}function G5(E,p,j,L,O,q){const H=j.paint.get("line-width"),Y=j.paint.get("line-emissive-strength").isConstant(),te=j.paint.get("line-emissive-strength").constantOr(0),de=j.paint.get("line-occlusion-opacity"),pe=j.layout.get("line-elevation-reference"),Ce=j.layout.get("line-width-unit")==="meters",je=pe==="sea",Me=!(!E.terrain||!E.terrain.enabled),qe=E.context,$e=qe.gl;if(j.hasElevatedBuckets&&E.transform.projection.name==="globe")return;const nt=j.layout.get("line-cross-slope"),rt=nt!==void 0,pt=nt<1,vt=O||E.colorModeForDrapableLayerRenderPass(Y?te:null),ot=E.terrain&&E.terrain.renderingToTexture||q,Ut=ot?1:o.o.devicePixelRatio,Tt=j.paint.get("line-dasharray"),$t=Tt.constantOr(1),_t=j.layout.get("line-cap"),St=Tt.constantOr(null),Rt=_t.constantOr(null),Zt=j.paint.get("line-pattern"),qt=Zt.constantOr(1),xs=j.paint.get("line-pattern-cross-fade"),as=Zt.constantOr(null),Os=j.paint.get("line-opacity").constantOr(1);let Hs=!qt&&Os!==1||E.depthOcclusion&&de>0&&de<1;const Qt=j.paint.get("line-gradient"),Ht=qt?"linePattern":"line",us=o.dU(j);let vs;if(ot&&E.terrain&&E.terrain.clipOrMaskOverlapStencilType()&&(Hs=!1),de!==0&&E.depthOcclusion){const Us=j.paint._values["line-opacity"];Us&&Us.value&&Us.value.kind==="constant"?vs=Us.value:o.w(`Occlusion opacity for layer ${j.id} is supported only when line-opacity isn't data-driven.`)}H.value.kind!=="constant"&&H.value.isLineProgressConstant===!1&&us.push("VARIABLE_LINE_WIDTH"),ot&&(E.emissiveMode!=="dual-source-blending"||Y?E.emissiveMode==="mrt-fallback"&&us.push("USE_MRT1"):us.push("DUAL_SOURCE_BLENDING"));const ks={},cr=(Us,Br,Kr,Er,Fr,_n)=>{for(const Fn of Us){const Pn=p.getTile(Fn);if(qt&&!Pn.patternsLoaded())continue;const oa=Pn.getBucket(j);if(!oa||oa.elevationType!=="none"&&!Fr||oa.elevationType==="none"&&Fr)continue;E.prepareDrawTile();const pn=[...Br],la=E.shadowRenderer,Dn=oa.elevationType==="road"&&!!la&&la.enabled;let Wa=[0,0,0];if(Dn){const _a=E.style.directionalLight,Ri=E.style.ambientLight;_a&&Ri&&(Wa=up(E.style,_a,Ri)),pn.push("RENDER_SHADOWS","NORMAL_OFFSET")}const Ti=oa.programConfigurations.get(j.id);let yo=!1;if(as&&Pn.imageAtlas){const _a=o.dV.from(as),Ri=_a.getPrimary().scaleSelf(Ut).toString(),Ul=Pn.imageAtlas.patternPositions.get(Ri),Ud=_a.getSecondary(),rc=Ud?Pn.imageAtlas.patternPositions.get(Ud.scaleSelf(Ut).toString()):null;yo=!!Ul&&!!rc,Ul&&Ti.setConstantPatternPositions(Ul,rc)}xs>0&&(yo||Ti.getPatternTransitionVertexBuffer("line-pattern"))&&pn.push("LINE_PATTERN_TRANSITION"),oa.elevationGroundScaleVertexBuffer&&pn.push("ELEVATION_GROUND_SCALE");const zi=E.isTileAffectedByFog(Fn),ri=E.getOrCreateProgram(Ht,{config:Ti,defines:pn,overrideFog:zi});if(!qt&&St&&Rt&&Pn.lineAtlas){const _a=Pn.lineAtlas.getDash(St,Rt);_a&&Ti.setConstantPatternPositions(_a)}Dn&&la.setupShadows(Pn.tileID.toUnwrapped(),ri,"vector-tile");let[Jn,ea]=j.paint.get("line-trim-offset");(Rt==="round"||Rt==="square")&&Jn!==ea&&(Jn===0&&(Jn-=1),ea===1&&(ea+=1));const $i=ot?Fn.projMatrix:null,No=Ce?1/oa.tileToMeter/o.aA(Pn,1,E.transform.zoom):1,ni=Ce?1/oa.tileToMeter/o.aA(Pn,1,Math.floor(E.transform.zoom)):1,qn=$t?j.paint._values["line-floorwidth"]:null;let uo;if(qn&&qn.value.kind==="constant"){const _a=oa.zoom;_a in ks||(ks[_a]=Math.max(.01,j.widthExpression().evaluate({zoom:_a}))),uo=qn.value.value;const Ri=Math.floor(E.transform.zoom);qn.value.value=ks[_a]*Math.pow(2,Ri-Pn.tileID.overscaledZ)}const Ei=qt?o.dW(E,Pn,j,$i,Ut,No,ni,[Jn,ea],Wa,xs):o.dX(E,Pn,j,$i,oa.lineClipsArray.length,Ut,No,ni,[Jn,ea],Wa);if(Qt){const _a=oa.gradients[j.id];let Ri=_a.texture;if(j.gradientVersion!==_a.version){let Ul=256;if(j.stepInterpolant){const Ud=p.getSource().maxzoom,rc=Fn.canonical.z===Ud?Math.ceil(1<{vs!=null&&(vs.value=Os*de),ri.draw(E,$e.TRIANGLES,Kr,_a,vt,vn.disabled,Ei,j.id,oa.layoutVertexBuffer,oa.indexBuffer,oa.segments,j.paint,E.transform.zoom,Ti,[oa.layoutVertexBuffer2,oa.patternVertexBuffer,oa.zOffsetVertexBuffer,oa.elevationGroundScaleVertexBuffer]),vs!=null&&(vs.value=Os)};if(Hs&&!Fr){const _a=E.stencilModeForClipping(Fn).ref;_a===0&&ot&&qe.clear({stencil:0});const Ri={func:$e.EQUAL,mask:255};Ei.u_alpha_discard_threshold=.8,jl(new Mn(Ri,_a,255,$e.KEEP,$e.KEEP,$e.INVERT)),Ei.u_alpha_discard_threshold=0,jl(new Mn(Ri,_a,255,$e.KEEP,$e.KEEP,$e.KEEP))}else Ei.u_alpha_discard_threshold=Hs&&Fr&&_n?.8:0,jl(Fr?Er:E.stencilModeForClipping(Fn));uo!==void 0&&(qn.value.value=uo)}};let Js=E.depthModeForSublayer(0,$r.ReadOnly);const er=new $r(E.depthOcclusion?$e.GREATER:$e.LEQUAL,$r.ReadOnly,E.depthRangeFor3D);if(j.hasNonElevatedBuckets){const Us=!ot&&E.terrain;de!==0&&Us?o.w(`Occlusion opacity for layer ${j.id} is supported on terrain only if the layer has line-z-offset enabled.`):Us?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${j.id}.`):cr(L,us,Js,Mn.disabled,!1,!0)}if(j.hasElevatedBuckets){pe==="hd-road-markup"?Me||(Js=er,us.push("ELEVATED_ROADS")):(us.push("ELEVATED"),Js=er,rt&&us.push(pt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),je&&us.push("ELEVATION_REFERENCE_SEA"));const Us=Hs?E.stencilModeFor3D():Mn.disabled;E.forceTerrainMode=!0,cr(L,us,Js,Us,!0,!0),Hs&&cr(L,us,Js,Us,!0,!1),E.forceTerrainMode=!1}Hs&&(E.resetStencilClippingMasks(),ot&&qe.clear({stencil:0})),de===0||E.depthOcclusion||ot||E.layersWithOcclusionOpacity.push(E.currentLayer)}const Og={additive:{clearColor:new o.aq(0,0,0,0),colorMode:Tn.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:Tn.multiply,compositeUniformValue:0}};function oP(E,p){const j=1<=t1?1:Me.pitch/t1))),2*qe}(E.transform),de=E.transform.getFreeCameraOptions().position,pe="elevatedStructuresDepthReconstruct",Ce=E.getOrCreateProgram(pe,{defines:["DEPTH_RECONSTRUCTION"]}),je=E.getOrCreateProgram(pe);for(const Me of L){const qe=p.getTile(Me),$e=qe.getBucket(j);if(!$e)continue;const nt=$e.elevatedStructures;if(!nt)continue;const rt=$e.elevationBufferData.heightRange,pt=oP(Me.toUnwrapped(),de),vt=E.translatePosMatrix(Me.projMatrix,qe,j.paint.get("fill-translate"),j.paint.get("fill-translate-anchor"));let ot,Ut,Tt,$t;if(O==="initialize"){if(!rt||rt.min>=1||nt.depthSegments.segments[0].primitiveLength===0)continue;ot=B2(vt,pt,te,1,0),Ut=H,Tt=nt.depthSegments,$t=Ce}else if(O==="reset"){if(!rt||rt.min>=0||nt.maskSegments.segments[0].primitiveLength===0)continue;ot=B2(vt,pt,0,0,1),Ut=Y,Tt=nt.maskSegments,$t=Ce}else if(O==="geometry"){if(nt.depthSegments.segments[0].primitiveLength===0)continue;ot=B2(vt,pt,te,1,0),Ut=H,Tt=nt.depthSegments,$t=je}$t.draw(E,q.TRIANGLES,Ut,Mn.disabled,Tn.disabled,vn.disabled,ot,j.id,nt.vertexBuffer,nt.indexBuffer,Tt,j.paint,E.transform.zoom)}}function H2(E,p,j,L){const{painter:O,sourceCache:q,layer:H,coords:Y,colorMode:te,elevationType:de,terrainEnabled:pe,pass:Ce}=E,je=O.context.gl,Me=H.paint.get("fill-pattern"),qe=H.paint.get("fill-pattern-cross-fade"),$e=Me.constantOr(null);let nt=de;de!=="road"||p&&!pe||(nt="none");const rt=nt==="road",pt=E.painter.shadowRenderer,vt=rt&&!!pt&&pt.enabled,ot=new $r(O.context.gl.LEQUAL,$r.ReadOnly,O.depthRangeFor3D);let Ut=[0,0,0];if(vt){const St=O.style.directionalLight,Rt=O.style.ambientLight;St&&Rt&&(Ut=up(O.style,St,Rt))}const Tt=Me&&Me.constantOr(1),$t=O.terrain&&O.terrain.renderingToTexture,_t=(St,Rt)=>{let Zt,qt,xs,as,Os;Rt?(Zt=Tt&&!H.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",xs=je.LINES):(Zt=Tt?"fillPattern":"fill",xs=je.TRIANGLES);for(const Hs of Y){const Qt=q.getTile(Hs);if(Tt&&!Qt.patternsLoaded())continue;const Ht=Qt.getBucket(H);if(!Ht)continue;const us=p?Ht.elevationBufferData:Ht.bufferData;if(us.isEmpty())continue;O.prepareDrawTile();const vs=us.programConfigurations.get(H.id),ks=O.isTileAffectedByFog(Hs),cr=[],Js=[];rt&&(cr.push("ELEVATED_ROADS"),Js.push(us.elevatedLayoutVertexBuffer)),vt&&cr.push("RENDER_SHADOWS","NORMAL_OFFSET"),$t&&j&&cr.push("USE_MRT1"),Tt&&(O.context.activeTexture.set(je.TEXTURE0),Qt.imageAtlasTexture&&Qt.imageAtlasTexture.bind(je.LINEAR,je.CLAMP_TO_EDGE),vs.updatePaintBuffers());let er=!1;if($e&&Qt.imageAtlas){const Fr=Qt.imageAtlas,_n=o.dV.from($e),Fn=_n.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Pn=_n.getSecondary(),oa=Fr.patternPositions.get(Fn),pn=Pn?Fr.patternPositions.get(Pn.scaleSelf(o.o.devicePixelRatio).toString()):null;er=!!oa&&!!pn,oa&&vs.setConstantPatternPositions(oa,pn)}qe>0&&(er||vs.getPatternTransitionVertexBuffer("fill-pattern"))&&cr.push("FILL_PATTERN_TRANSITION");const Us=O.getOrCreateProgram(Zt,{config:vs,overrideFog:ks,defines:cr}),Br=O.translatePosMatrix(Hs.projMatrix,Qt,H.paint.get("fill-translate"),H.paint.get("fill-translate-anchor"));vt&&pt.setupShadows(Qt.tileID.toUnwrapped(),Us,"vector-tile");const Kr=H.paint.get("fill-emissive-strength");if(Rt){as=us.lineIndexBuffer,Os=us.lineSegments;const Fr=O.terrain&&O.terrain.renderingToTexture?O.terrain.drapeBufferSize:[je.drawingBufferWidth,je.drawingBufferHeight];qt=Zt==="fillOutlinePattern"&&Tt?h_(Br,Kr,O,Qt,Fr,Ut,qe):yz(Br,Kr,Fr,Ut)}else as=us.indexBuffer,Os=us.triangleSegments,qt=Tt?R5(Br,Kr,O,Qt,Ut,qe):D5(Br,Kr,Ut);O.uploadCommonUniforms(O.context,Us,Hs.toUnwrapped());let Er=St;(de==="road"&&!pe||de==="offset")&&(Er=ot),Us.draw(O,xs,Er,L||O.stencilModeForClipping(Hs),te,vn.disabled,qt,H.id,us.layoutVertexBuffer,as,Os,H.paint,O.transform.zoom,vs,Js)}};O.renderPass===Ce&&_t(O.depthModeForSublayer(1,O.renderPass==="opaque"?$r.ReadWrite:$r.ReadOnly),!1),nt==="none"&&O.renderPass==="translucent"&&H.paint.get("fill-antialias")&&_t(O.depthModeForSublayer(H.getPaintProperty("fill-outline-color")?2:0,$r.ReadOnly),!0)}function c1(E,p,j,L,O,q,H,Y){j.resetLayerRenderingStats(E);const te=E.context,de=te.gl,pe=E.transform,Ce=j.paint.get("fill-extrusion-pattern"),je=j.paint.get("fill-extrusion-pattern-cross-fade"),Me=Ce.constantOr(null),qe=Ce.constantOr(1),$e=j.paint.get("fill-extrusion-opacity"),nt=E.style.enable3dLights(),rt=j.paint.get(nt&&!qe?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),pt=[j.paint.get("fill-extrusion-ambient-occlusion-intensity"),rt],vt=j.layout.get("fill-extrusion-edge-radius"),ot=vt>0&&!j.paint.get("fill-extrusion-rounded-roof"),Ut=ot?0:vt,Tt=pe.projection.name==="globe"?o.e1():0,$t=pe.projection.name==="globe",_t=$t?o.al(pe.zoom):0,St=[o.aH(pe.center.lng),o.aL(pe.center.lat)],Rt=j.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Zt=j.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Rt?null:j.lut).toArray01().slice(0,3),qt=j.paint.get("fill-extrusion-flood-light-intensity"),xs=j.paint.get("fill-extrusion-vertical-scale"),as=j.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Os=j.paint.get("fill-extrusion-height-alignment"),Hs=j.paint.get("fill-extrusion-base-alignment"),Qt=Mc(E,j.paint.get("fill-extrusion-cutoff-fade-range")),Ht=j.paint.get("fill-extrusion-front-cutoff"),us=W5(pe.pitch,Ht,!!E.terrain),vs=us[2]<1;vs&&(E.maxFrontCutoffRawStart=Math.max(E.maxFrontCutoffRawStart,Ht[0]));const ks=[];let cr;$t&&ks.push("PROJECTION_GLOBE_VIEW"),pt[0]>0&&ks.push("FAUX_AO"),ot&&ks.push("ZERO_ROOF_RADIUS"),Y&&ks.push("HAS_CENTROID"),qt>0&&ks.push("FLOOD_LIGHT"),Qt.shouldRenderCutoff&&ks.push("RENDER_CUTOFF"),vs&&ks.push("RENDER_FRONT_CUTOFF"),as&&ks.push("RENDER_WALL_MODE");const Js=E.renderPass==="shadow",er=E.shadowRenderer,Us=Js&&!!er,Br=Js?vn.disabled:vn.backCCW;E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!0);let Kr=[0,0,0];if(er){const _n=E.style.directionalLight,Fn=E.style.ambientLight;_n&&Fn&&(Kr=up(E.style,_n,Fn)),Js||(ks.push("RENDER_SHADOWS"),er.useNormalOffset&&ks.push("NORMAL_OFFSET")),cr=ks.concat(["SHADOWS_SINGLE_CASCADE"])}const Er=Us?"fillExtrusionDepth":qe?"fillExtrusionPattern":"fillExtrusion",Fr=j.getLayerRenderingStats();for(const _n of L){const Fn=p.getTile(_n),Pn=Fn.getBucket(j);if(!Pn||Pn.projection.name!==pe.projection.name)continue;let oa=!1;er&&(oa=er.getMaxCascadeForTile(_n.toUnwrapped())===0);const pn=E.isTileAffectedByFog(_n),la=Pn.programConfigurations.get(j.id);let Dn=!1;if(Me&&Fn.imageAtlas){const ea=Fn.imageAtlas,$i=o.dV.from(Me),No=$i.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ni=$i.getSecondary(),qn=ea.patternPositions.get(No),uo=ni?ea.patternPositions.get(ni.scaleSelf(o.o.devicePixelRatio).toString()):null;Dn=!!qn&&!!uo,qn&&la.setConstantPatternPositions(qn,uo)}je>0&&(Dn||la.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&ks.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Wa=E.getOrCreateProgram(Er,{config:la,defines:oa?cr:ks,overrideFog:pn});if(E.terrain&&E.terrain.setupElevationDraw(Fn,Wa,{useMeterToDem:!0}),!Pn.centroidVertexBuffer){const ea=Wa.getAttributeLocation(de,"a_centroid_pos");ea!==-1&&de.vertexAttribI4ui(ea,0,0,0,0)}!Js&&er&&er.setupShadows(Fn.tileID.toUnwrapped(),Wa,"vector-tile"),qe&&(E.context.activeTexture.set(de.TEXTURE0),Fn.imageAtlasTexture&&Fn.imageAtlasTexture.bind(de.LINEAR,de.CLAMP_TO_EDGE),la.updatePaintBuffers());const Ti=j.paint.get("fill-extrusion-vertical-gradient"),yo=1/Pn.tileToMeter;let zi;if(Js&&er){if(K5(Fn.tileID,Pn.maxHeight,E))continue;const ea=er.calculateShadowPassMatrixFromTile(Fn.tileID.toUnwrapped());zi=xge(ea,Ut,yo,xs,Os,Hs)}else{const ea=E.translatePosMatrix(_n.expandedProjMatrix,Fn,j.paint.get("fill-extrusion-translate"),j.paint.get("fill-extrusion-translate-anchor")),$i=pe.projection.createInversionMatrix(pe,_n.canonical);zi=qe?gge(ea,E,Ti,$e,pt,Ut,yo,_n,Fn,Tt,Os,Hs,_t,St,$i,Zt,xs,je):gz(ea,E,Ti,$e,pt,Ut,yo,_n,Tt,Os,Hs,_t,St,$i,Zt,xs,qt,Kr,us)}E.uploadCommonUniforms(te,Wa,_n.toUnwrapped(),null,Qt);let ri=Pn.segments;if(pe.projection.name==="mercator"&&!Js&&(ri=Pn.getVisibleSegments(Fn.tileID,E.terrain,E.transform.getFrustum(0)),!ri.get().length))continue;if(Fr)if(Js)for(const ea of ri.get())Fr.numRenderedVerticesInShadowPass+=ea.primitiveLength;else for(const ea of ri.get())Fr.numRenderedVerticesInTransparentPass+=ea.primitiveLength;const Jn=[];(E.terrain||Y)&&Jn.push(Pn.centroidVertexBuffer),$t&&Jn.push(Pn.layoutVertexExtBuffer),as&&Jn.push(Pn.wallVertexBuffer),Wa.draw(E,te.gl.TRIANGLES,O,q,H,Br,zi,j.id,Pn.layoutVertexBuffer,Pn.indexBuffer,ri,j.paint,E.transform.zoom,la,Jn)}E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!1)}class lP{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function W5(E,p,j){if(!(p[2]<1)||j)return[0,0,1];const L=180*E/Math.PI;if(L<15)return[-.5,p[1],p[2]];const O=Math.min(1,Math.max(0,(L-15)/5)),q=O*O*(3-2*O);return[-.5*(1-q)+p[0]*q,p[1],p[2]]}function _x(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me,qe,$e,nt,rt,pt,vt,ot){const Ut=p.context,Tt=Ut.gl,$t=p.transform,_t=p.transform.zoom,St=[],Rt=E.translate,Zt=E.translateAnchor,qt=E.edgeRadius,xs=Mc(p,E.cutoffFadeRange);pe==="clear"?(St.push("CLEAR_SUBPASS"),vt&&(St.push("CLEAR_FROM_TEXTURE"),Ut.activeTexture.set(Tt.TEXTURE0),vt.bind(Tt.LINEAR,Tt.CLAMP_TO_EDGE))):pe==="sdf"?St.push("SDF_SUBPASS"):pe==="emissive"&&(St.push("USE_MRT1"),Ut.activeTexture.set(Tt.TEXTURE0),vt.bind(Tt.LINEAR,Tt.CLAMP_TO_EDGE)),rt&&St.push("HAS_CENTROID"),xs.shouldRenderCutoff&&St.push("RENDER_CUTOFF");const as=(Os,Hs,Qt,Ht,us)=>{let vs=St;Hs.groundRadiusBuffer!=null&&(vs=St.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const ks=Hs.programConfigurations.get(L.id),cr=p.isTileAffectedByFog(Os),Js=p.getOrCreateProgram("fillExtrusionGroundEffect",{config:ks,defines:vs,overrideFog:cr}),er=((Br,Kr,Er,Fr,_n,Fn,Pn,oa,pn,la,Dn)=>({u_matrix:Kr,u_opacity:Er,u_ao_pass:Fr?1:0,u_meter_to_tile:_n,u_ao:Fn,u_flood_light_intensity:Pn,u_flood_light_color:oa,u_attenuation:pn,u_edge_radius:la,u_fb:0,u_fb_size:Dn,u_dynamic_offset:1}))(0,Ht,Ce,de,us,[je,Me*us],qe,$e,nt,_t>=17?0:qt*us,vt?vt.size[0]:0),Us=[];rt&&Us.push(Hs.hiddenByLandmarkVertexBuffer),Hs.groundRadiusBuffer!=null&&Us.push(Hs.groundRadiusBuffer),p.uploadCommonUniforms(Ut,Js,Os.toUnwrapped(),null,xs),Js.draw(p,Ut.gl.TRIANGLES,q,H,Y,te,er,L.id,Hs.vertexBuffer,Hs.indexBuffer,Qt,L.paint,_t,ks,Us)};for(const Os of O){const Hs=j.getTile(Os),Qt=Hs.getBucket(L);if(!Qt||Qt.projection.name!==$t.projection.name||!Qt.groundEffect||Qt.groundEffect&&!Qt.groundEffect.hasData())continue;const Ht=Qt.groundEffect,us=1/Qt.tileToMeter;{const vs=p.translatePosMatrix(Os.projMatrix,Hs,Rt,Zt),ks=Ht.getDefaultSegment();as(Os,Ht,ks,vs,us)}if(pt)for(let vs=0;vs<4;vs++){const ks=o.d$[vs](Os),cr=j.getTile(ks);if(!cr)continue;const Js=cr.getBucket(L);if(!Js||Js.projection.name!==$t.projection.name||!Js.groundEffect||Js.groundEffect&&!Js.groundEffect.hasData())continue;const er=Js.groundEffect;let Us,Br;vs===0?(Us=[-o.an,0,0],Br=1):vs===1?(Us=[o.an,0,0],Br=0):vs===2?(Us=[0,-o.an,0],Br=3):(Us=[0,o.an,0],Br=2);const Kr=er.regionSegments[Br];if(!Kr)continue;const Er=new Float32Array(16);o.bx(Er,Os.projMatrix,Us),as(Os,er,Kr,p.translatePosMatrix(Er,Hs,Rt,Zt),us)}}}function Ez(E,p,j,L,O,q,H){L.centroidVertexArray.length===0&&L.createCentroidsBuffer();const Y=q?q.findDEMTileFor(j):null;if(!(Y&&Y.dem||H))return;q&&Y&&Y.dem&&L.selfDEMTileTimestamp!==Y.dem._timestamp&&(L.borderDoneWithNeighborZ=[-1,-1,-1,-1],L.selfDEMTileTimestamp=Y.dem._timestamp);const te=(rt,pt)=>{(rt.flags|pt.flags)&o.e3?(rt.flags|=o.e3,pt.flags|=o.e3):(rt.flags&=~o.e3,pt.flags&=~o.e3)},de=rt=>new o.P(Math.ceil((rt+o.e4)*o.e5),0),pe=(rt,pt,vt)=>{const ot=Math.ceil((rt+o.e4)*o.e5),Ut=Math.floor(Math.max(0,Math.min(o.an-1,vt))/4);return new o.P(ot,Ut<<5|(3&pt)<<3|7)},Ce=rt=>{const pt=p.getSource().minzoom,vt=Ut=>{const Tt=p.getTileByID(Ut);if(Tt&&Tt.hasData())return Tt.getBucket(O)},ot=[0,-1,1];for(const Ut of ot){if(rt.overscaledZ+Ut(je[0]=Math.min(rt.min.y,pt.min.y),je[1]=Math.max(rt.max.y,pt.max.y),je[2]=o.an-pt.min.x>rt.max.x?pt.min.x-o.an:rt.max.x,je),qe=(rt,pt)=>(je[0]=Math.min(rt.min.x,pt.min.x),je[1]=Math.max(rt.max.x,pt.max.x),je[2]=o.an-pt.min.y>rt.max.y?pt.min.y-o.an:rt.max.y,je),$e=[(rt,pt)=>Me(rt,pt),(rt,pt)=>Me(pt,rt),(rt,pt)=>qe(rt,pt),(rt,pt)=>qe(pt,rt)],nt=(rt,pt,vt,ot,Ut,Tt,$t)=>{if(!q)return 0;const _t=[[Tt?vt:rt,Tt?rt:vt,0],[Tt?vt:pt,Tt?pt:vt,0]],St=$t<0?o.an+$t:$t,Rt=[Tt?St:(rt+pt)/2,Tt?(rt+pt)/2:St,0];return vt===0&&$t<0||vt!==0&&$t>0?q.getForTilePoints(Ut,[Rt],!0,ot):_t.push(Rt),q.getForTilePoints(j,_t,!0,Y),Math.max(_t[0][2],_t[1][2],Rt[2])/q.exaggeration()};for(let rt=0;rt<4;rt++){const pt=L.borderFeatureIndices[rt];if(pt.length===0)continue;const vt=o.d$[rt](j),ot=Ce(vt);if(!(ot&&ot instanceof o.e0))continue;const Ut=q?q.findDEMTileFor(vt):null;if(!(Ut&&Ut.dem||H)||(q&&Ut&&Ut.dem&&L.borderDEMTileTimestamp[rt]!==Ut.dem._timestamp&&(L.borderDoneWithNeighborZ[rt]=-1,L.borderDEMTileTimestamp[rt]=Ut.dem._timestamp),L.borderDoneWithNeighborZ[rt]===ot.canonical.z))continue;ot.centroidVertexArray.length===0&&ot.createCentroidsBuffer();const Tt=(rt<2?1:5)-rt,$t=ot.borderDoneWithNeighborZ[Tt]!==L.canonical.z,_t=ot.borderFeatureIndices[Tt];let St=0;if(L.canonical.z!==ot.canonical.z){for(const xs of pt)L.showCentroid(L.featuresOnBorder[xs]);if($t)for(const xs of _t)ot.showCentroid(ot.featuresOnBorder[xs]);L.borderDoneWithNeighborZ[rt]=ot.canonical.z,ot.borderDoneWithNeighborZ[Tt]=L.canonical.z;continue}const Rt=new Map,Zt=new Set,qt=new Set;for(let xs=0;xs<_t.length;xs++){const as=ot.featuresOnBorder[_t[xs]];as.buildingId!==void 0&&Rt.set(as.buildingId,xs)}for(const xs of pt){const as=L.featuresOnBorder[xs],Os=L.centroidData[as.centroidDataIndex];if(as.buildingId===void 0)continue;const Hs=Rt.get(as.buildingId);if(Hs===void 0)continue;const Qt=ot.featuresOnBorder[_t[Hs]],Ht=ot.centroidData[Qt.centroidDataIndex];Zt.add(xs),qt.add(Hs),H&&te(Os,Ht);const us=Os.groupCentroidPos.x!==0||Os.groupCentroidPos.y!==0?Os.groupCentroidPos:as.centroid(),vs=Ht.groupCentroidPos.x!==0||Ht.groupCentroidPos.y!==0?Ht.groupCentroidPos:Qt.centroid(),ks=rt<2?Math.round((us.y+vs.y)/2):Math.round((us.x+vs.x)/2),cr=as.intersectsCount()>1||Qt.intersectsCount()>1;{let Js=0;if(Ut&&Ut.dem&&!cr){const er=$e[rt](Os,Ht),Us=rt%2?o.an-1:0;Js=nt(er[0],Math.min(o.an-1,er[1]),Us,Ut,vt,rt<2,er[2])}Os.centroidXY=pe(Js,rt,ks),Ht.centroidXY=pe(Js,Tt,ks)}if(L.writeCentroidToBuffer(Os),ot.writeCentroidToBuffer(Ht),as.buildingId!==void 0){for(const Js of L.centroidData)Js.buildingId===as.buildingId&&Js!==Os&&(Js.centroidXY=Os.centroidXY,L.writeCentroidToBuffer(Js));for(const Js of ot.centroidData)Js.buildingId===as.buildingId&&Js!==Ht&&(Js.centroidXY=Ht.centroidXY,ot.writeCentroidToBuffer(Js))}}for(const xs of pt){if(Zt.has(xs))continue;const as=L.featuresOnBorder[xs],Os=L.centroidData[as.centroidDataIndex],Hs=as.borders[rt];let Qt;for(;St<_t.length;){if(qt.has(St)){St++;continue}Qt=ot.featuresOnBorder[_t[St]];const Ht=Qt.borders[Tt];if(Ht[1]>Hs[0]+3||Ht[0]>Hs[0]-3)break;ot.showCentroid(Qt),St++}if(Qt&&St<_t.length){let Ht=St,us=0;for(;;)if(qt.has(St)){if(++St===_t.length)break;Qt=ot.featuresOnBorder[_t[St]]}else{if(Qt.borders[Tt][0]>Hs[1]-3||(us++,++St===_t.length))break;Qt=ot.featuresOnBorder[_t[St]]}for(;Ht<_t.length&&qt.has(Ht);)Ht++;if(Ht>=_t.length){L.showCentroid(as);continue}Qt=ot.featuresOnBorder[_t[Ht]];let vs=!1;if(us>=1){const Js=Qt.borders[Tt];Math.abs(Hs[0]-Js[0])<3&&Math.abs(Hs[1]-Js[1])<3&&(us=1,vs=!0,St=Ht+1)}else if(us===0){L.showCentroid(as);continue}const ks=ot.centroidData[Qt.centroidDataIndex];H&&vs&&te(Os,ks);const cr=as.intersectsCount()>1||Qt.intersectsCount()>1;if(us>1)St=Ht,Os.centroidXY=ks.centroidXY=new o.P(0,0);else if(Ut&&Ut.dem&&!cr){const Js=$e[rt](Os,ks),er=rt%2?o.an-1:0,Us=nt(Js[0],Math.min(o.an-1,Js[1]),er,Ut,vt,rt<2,Js[2]);Os.centroidXY=ks.centroidXY=de(Us)}else cr?Os.centroidXY=ks.centroidXY=new o.P(0,0):(Os.centroidXY=L.encodeBorderCentroid(as),ks.centroidXY=ot.encodeBorderCentroid(Qt));L.writeCentroidToBuffer(Os),ot.writeCentroidToBuffer(ks)}else L.showCentroid(as)}L.borderDoneWithNeighborZ[rt]=ot.canonical.z,ot.borderDoneWithNeighborZ[Tt]=L.canonical.z}(L.needsCentroidUpdate||!L.centroidVertexBuffer&&L.centroidVertexArray.length!==0)&&L.uploadCentroid(E)}const Az=[1,0,0],Mz=[0,1,0],cP=[0,0,1];function K5(E,p,j){const L=j.transform,O=j.shadowRenderer;if(!O)return!0;const q=E.toUnwrapped(),H=L.tileSize*O._cascades[j.currentShadowCascade].scale;let Y=p;if(L.elevation){const qe=L.elevation.getMinMaxForTile(E);qe&&(Y+=qe.max)}const te=L.scaleZoom(H);Y/=o.e2(L.center.lat,te);const de=[...O.shadowDirection];de[2]=-de[2];const pe=O.computeSimplifiedTileShadowVolume(q,Y,H,de);if(!pe)return!1;const Ce=[Az,Mz,cP,de,[de[0],0,de[2]],[0,de[1],de[2]]],je=o.cl.fromInvProjectionMatrix(L.invProjMatrix,L.worldSize,te,L.projection.name!=="globe"),Me=O.getCurrentCascadeFrustum();return je.intersectsPrecise(pe.vertices,pe.planes,Ce)===0||Me.intersectsPrecise(pe.vertices,pe.planes,Ce)===0}function G2(E){const{painter:p,source:j,layer:L,coords:O}=E;let q=E.defines;const H=p.context,Y=p.renderPass==="shadow",te=p.renderPass==="light-beam",de=p.shadowRenderer,pe=o.e2(p.transform.center.lat,p.transform.zoom),Ce=Mc(p,L.paint.get("building-cutoff-fade-range"));Ce.shouldRenderCutoff&&(q=q.concat("RENDER_CUTOFF"));const je=L.paint.get("building-front-cutoff"),Me=je[2]<1&&!p.terrain,qe=W5(p.transform.pitch,je,!!p.terrain);Me&&(q=q.concat("RENDER_FRONT_CUTOFF"),p.maxFrontCutoffRawStart=Math.max(p.maxFrontCutoffRawStart,je[0])),E.floodLightIntensity>0&&(q=q.concat("FLOOD_LIGHT"));for(const $e of O){const nt=j.getTile($e),rt=nt.getBucket(L);if(!rt)continue;de&&de.getMaxCascadeForTile($e.toUnwrapped())===0&&(q=q.concat("SHADOWS_SINGLE_CASCADE"));const pt=rt.programConfigurations.get(L.id);let vt,ot,Ut,Tt=p.translatePosMatrix($e.expandedProjMatrix,nt,[0,0],"map");if(Tt=o.cC(o.bb(),Tt,[1,1,E.verticalScale]),Y&&de){if(K5(nt.tileID,rt.maxHeight*pe,p))continue;let _t=de.calculateShadowPassMatrixFromTile(nt.tileID.toUnwrapped());_t=o.cC(o.bb(),_t,[1,1,E.verticalScale]),Ut=B5(_t),vt=ot=p.getOrCreateProgram("buildingDepth",{config:pt,defines:q,overrideFog:!1})}else if(te)vt=ot=p.getOrCreateProgram("buildingBloom",{config:pt,defines:q,overrideFog:!1}),Ut=F5(Tt);else{const _t=p.transform.calculatePosMatrix($e.toUnwrapped(),p.transform.worldSize);o.cC(_t,_t,[1,1,E.verticalScale]);const St=o.bb();o.cC(St,_t,[1,-1,1/pe]),o.b7(St,St),o.e6(St,St);const Rt=p.transform.getFreeCameraOptions().position,Zt=1<<$e.canonical.z;if(Ut=s0(Tt,St,E.opacity,E.facadeAOIntensity,[((Rt.x-$e.wrap)*Zt-$e.canonical.x)*o.an,(Rt.y*Zt-$e.canonical.y)*o.an,Rt.z*Zt*o.an],rt.tileToMeter,E.facadeEmissiveChance,E.floodLightColor,E.floodLightIntensity,qe),ot=p.getOrCreateProgram("building",{config:pt,defines:q,overrideFog:!1}),E.depthOnly===!0)vt=ot;else{const qt=q.concat(["BUILDING_FAUX_FACADE","HAS_ATTRIBUTE_a_faux_facade_color_emissive"]);vt=p.getOrCreateProgram("building",{config:pt,defines:qt,overrideFog:!1})}de&&(de.setupShadowsFromMatrix(_t,ot,!0),vt!==ot&&de.setupShadowsFromMatrix(_t,vt,!0))}const $t=(_t,St)=>{if(te){const Rt=_t.entranceBloom;St.draw(p,H.gl.TRIANGLES,E.depthMode,Mn.disabled,E.blendMode,vn.disabled,Ut,L.id,Rt.layoutVertexBuffer,Rt.indexBuffer,Rt.segmentsBucket,L.paint,p.transform.zoom,pt,[Rt.layoutAttenuationBuffer,Rt.layoutColorBuffer])}else{const Rt=_t.segmentsBucket;let Zt=[_t.layoutNormalBuffer,_t.layoutCentroidBuffer,_t.layoutColorBuffer,_t.layoutFloodLightDataBuffer];_t.layoutFacadePaintBuffer&&(Zt=Zt.concat([_t.layoutFacadeDataBuffer,_t.layoutFacadeVerticalRangeBuffer,_t.layoutFacadePaintBuffer])),St.draw(p,H.gl.TRIANGLES,E.depthMode,Mn.disabled,E.blendMode,Y?vn.disabled:vn.backCW,Ut,L.id,_t.layoutVertexBuffer,_t.indexBuffer,Rt,L.paint,p.transform.zoom,pt,Zt)}};p.uploadCommonUniforms(H,ot,$e.toUnwrapped(),null,Ce),rt.buildingWithoutFacade&&$t(rt.buildingWithoutFacade,ot),rt.buildingWithFacade&&(vt!==ot&&p.uploadCommonUniforms(H,vt,$e.toUnwrapped(),null,Ce),$t(rt.buildingWithFacade,vt))}}function dP(E,p,j,L,O,q,H,Y,te,de,pe,Ce,je,Me){const qe=E.context.gl,$e=E.depthModeForSublayer(1,$r.ReadOnly,qe.LEQUAL,!0),nt=.1*(1-(rt=pe))+3*rt;var rt;const pt=E._showOverdrawInspector,vt=Ce,ot=new lP;pt||_x(ot,E,p,j,L,$e,new Mn({func:qe.ALWAYS,mask:255},255,255,qe.KEEP,qe.KEEP,qe.REPLACE),new Tn([qe.ONE,qe.ONE,qe.ONE,qe.ONE],o.aq.transparent,[!1,!1,!1,!0],qe.MIN),vn.disabled,O,"sdf",q,H,Y,te,de,nt,vt,!1,void 0);{const Ut=pt?Mn.disabled:new Mn({func:qe.EQUAL,mask:255},255,255,qe.KEEP,qe.DECR,qe.DECR),Tt=pt?E.colorModeForRenderPass():new Tn([qe.ONE_MINUS_DST_ALPHA,qe.DST_ALPHA,qe.ONE,qe.ONE],o.aq.transparent,[!0,!0,!0,!0]);_x(ot,E,p,j,L,$e,Ut,Tt,vn.disabled,O,"color",q,H,Y,te,de,nt,vt,!1,void 0)}}function uP(E){return[E[0]*o.e7,E[1]*o.e7,E[2]*o.e7,0]}function Y5(E,p,j,L,O,q,H,Y,te){const de=L.getSource(),pe=j.globeSharedBuffers;if(!pe)return;let Ce,je,Me;if(p&&(Ce=L.getTile(p)),de instanceof o.aV?(je=de.texture,Me=o.dw(0,0,j.transform)):Ce&&p&&(je=Ce.texture,Me=o.dw(p.canonical.z,p.canonical.x,j.transform)),!je||!Me)return;E||(Me=o.cC(o.bb(),Me,[1,-1,1]));const qe=j.context,$e=qe.gl,nt=O.paint.get("raster-resampling")==="nearest"?$e.NEAREST:$e.LINEAR,rt=j.colorModeForDrapableLayerRenderPass(q),pt=H.defines;pt.push("GLOBE_POLES");const vt=new $r($e.LEQUAL,$r.ReadWrite,j.depthRangeFor3D),ot=Float32Array.from(j.transform.expandedFarZProjMatrix),Ut=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));j.terrain&&j.terrain.prepareDrawTile(),qe.activeTexture.set($e.TEXTURE0),je.bind(nt,$e.CLAMP_TO_EDGE),qe.activeTexture.set($e.TEXTURE1),je.bind(nt,$e.CLAMP_TO_EDGE),"useMipmap"in je&&qe.extTextureFilterAnisotropic&&j.transform.pitch>20&&$e.texParameterf($e.TEXTURE_2D,qe.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,qe.extTextureFilterAnisotropicMax);const[Tt,$t,_t,St]=p?pe.getPoleBuffers(p.canonical.z,!1):pe.getPoleBuffers(0,!0),Rt=O.paint.get("raster-elevation");let Zt;E?(Zt=Tt,j.renderDefaultNorthPole=Rt!==0):(Zt=$t,j.renderDefaultSouthPole=Rt!==0);const qt=uP(H.mix),xs=((Os,Hs,Qt,Ht,us,vs,ks,cr,Js,er,Us,Br,Kr,Er)=>jz(Os,Hs,Qt,Ht,new Float32Array(16),new Float32Array(9),[0,0],us,[0,0],[0,0,0,0],1,{opacity:1,mix:0},ks,[0,0],Js,2,Us,Br,Kr,1,0,Er))(j,ot,Ut,Me,o.al(j.transform.zoom),0,O,0,Rt,0,qt,H.offset,H.range,q),as=j.getOrCreateProgram("raster",{defines:pt});j.uploadCommonUniforms(qe,as,null),as.draw(j,$e.TRIANGLES,vt,te,rt,Y,xs,O.id,Zt,_t,St)}function hP(E){if(E.isOrthographic)return[0,0,0,0];const p=E._nearZ,j=E.projection.farthestPixelDistance(E),L=j-p,O=.2*E.height,q=p+O;return[p,j,(q-O-p)/L,(q-p)/L]}function Iz(E,p,j,L){if(E)return p instanceof Im&&E instanceof Mh?p.getTextureDescriptor(E,j,!0):{texture:E.texture,mix:uP(L.mix),offset:L.offset,buffer:0,tileSize:1}}var mP=o.e8([{name:"a_index",type:"Int16",components:1}]);class Lz{constructor(p,j,L,O){const q={width:L[0],height:L[1],data:null},H=p.gl;this.targetColorTexture=new o.T(p,q,H.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(p,q,H.RGBA8,{useMipmap:!1}),this.context=p,this.updateParticleTexture(j,O),this.lastInvalidatedAt=0}updateParticleTexture(p,j){if(this.particleTextureDimension===j.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const L=this.context.gl,O=j.width*j.height;this.particleTexture0=new o.T(this.context,j,L.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,j,L.RGBA8,{premultiply:!1,useMipmap:!1});const q=new o.e9;q.reserve(O);for(let H=0;H0){const qt=o.ec(j.canonical,te),xs=o.ed(qt);je=o.aD(new Float32Array(16),te.globeMatrix,xs),o.aD(je,te.projMatrix,je)}const Me=o.bb();Me[12]+=2*O/(o.o.devicePixelRatio*te.width),Me[13]+=2*q/(o.o.devicePixelRatio*te.height),o.aD(je,Me,je);const qe=E.getOrCreateProgram("debug",{defines:Ce}),$e=p.getTileByID(j.key);E.terrain&&E.terrain.setupElevationDraw($e,qe);const nt=$r.disabled,rt=Mn.disabled,pt=E.colorModeForRenderPass(),vt="$debug";Y.activeTexture.set(de.TEXTURE0),E.emptyTexture.bind(de.LINEAR,de.CLAMP_TO_EDGE),pe?$e._makeGlobeTileDebugBuffers(E.context,te):$e._makeDebugTileBoundsBuffers(E.context,te.projection);const ot=$e._tileDebugBuffer||E.debugBuffer,Ut=$e._tileDebugIndexBuffer||E.debugIndexBuffer,Tt=$e._tileDebugSegments||E.debugSegments;if(qe.draw(E,de.LINE_STRIP,nt,rt,pt,vn.disabled,z2(je,L.toPremultipliedRenderColor(null)),vt,ot,Ut,Tt,null,null,null,[$e._globeTileDebugBorderBuffer]),H){const qt=$e.latestRawTileData,xs=Math.floor((qt&&qt.byteLength||0)/1024);let as=j.canonical.toString();j.overscaledZ!==j.canonical.z&&(as+=` => ${j.overscaledZ}`),as+=` ${$e.state}`,as+=` ${xs}kb`,function(Os,Hs){Os.initDebugOverlayCanvas();const Qt=Os.debugOverlayCanvas,Ht=Os.context.gl,us=Os.debugOverlayCanvas.getContext("2d");us.clearRect(0,0,Qt.width,Qt.height),us.shadowColor="white",us.shadowBlur=2,us.lineWidth=1.5,us.strokeStyle="white",us.textBaseline="top",us.font="bold 36px Open Sans, sans-serif",us.fillText(Hs,5,5),us.strokeText(Hs,5,5),Os.debugOverlayTexture.update(Qt),Os.debugOverlayTexture.bind(Ht.LINEAR,Ht.CLAMP_TO_EDGE)}(E,as)}const $t=p.getTile(j).tileSize,_t=512/Math.min($t,512)*(j.overscaledZ/te.zoom)*.5,St=$e._tileDebugTextBuffer||E.debugBuffer,Rt=$e._tileDebugTextIndexBuffer||E.quadTriangleIndexBuffer,Zt=$e._tileDebugTextSegments||E.debugSegments;qe.draw(E,de.TRIANGLES,nt,rt,Tn.alphaBlended,vn.disabled,z2(je,o.aq.transparent.toPremultipliedRenderColor(null),_t),vt,St,Rt,Zt,null,null,null,[$e._globeTileDebugTextBuffer])}function Dz(E,p,j,L){Z5(E,0,p+j/2,E.transform.width,j,L)}function yP(E,p,j,L){Z5(E,p-j/2,0,j,E.transform.height,L)}function Z5(E,p,j,L,O,q){const H=E.context,Y=H.gl;Y.enable(Y.SCISSOR_TEST),Y.scissor(p*o.o.devicePixelRatio,j*o.o.devicePixelRatio,L*o.o.devicePixelRatio,O*o.o.devicePixelRatio),H.clear({color:q}),Y.disable(Y.SCISSOR_TEST)}const jge=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:im}=jge;function wx(E,p,j,L){E.emplaceBack(p,j,L)}class Cu{constructor(p){this.vertexArray=new o.ee,this.indices=new o.dC,wx(this.vertexArray,-1,-1,1),wx(this.vertexArray,1,-1,1),wx(this.vertexArray,-1,1,1),wx(this.vertexArray,1,1,1),wx(this.vertexArray,-1,-1,-1),wx(this.vertexArray,1,-1,-1),wx(this.vertexArray,-1,1,-1),wx(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=p.createVertexBuffer(this.vertexArray,im),this.indexBuffer=p.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function Fm(E,p,j,L,O,q){const H=E.context.gl,Y=p.paint.get("sky-atmosphere-color"),te=p.paint.get("sky-atmosphere-halo-color"),de=p.paint.get("sky-atmosphere-sun-intensity"),pe=((Ce,je,Me,qe,$e)=>({u_matrix_3f:Ce,u_sun_direction:je,u_sun_intensity:Me,u_color_tint_r:[qe.r,qe.g,qe.b,qe.a],u_color_tint_m:[$e.r,$e.g,$e.b,$e.a],u_luminance:5e-5}))(o.eg(o.dE(),L),O,de,Y.toPremultipliedRenderColor(null),te.toPremultipliedRenderColor(null));H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+q,p.skyboxTexture,0),j.draw(E,H.TRIANGLES,$r.disabled,Mn.disabled,Tn.unblended,vn.frontCW,pe,"skyboxCapture",p.skyboxGeometry.vertexBuffer,p.skyboxGeometry.indexBuffer,p.skyboxGeometry.segment)}const Rz=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class vP{constructor(p){const j=new o.eh;j.emplaceBack(-1,1,1,0,0),j.emplaceBack(1,1,1,1,0),j.emplaceBack(1,-1,1,1,1),j.emplaceBack(-1,-1,1,0,1);const L=new o.dC;L.emplaceBack(0,1,2),L.emplaceBack(2,3,0),this.vertexBuffer=p.createVertexBuffer(j,Rz.members),this.indexBuffer=p.createIndexBuffer(L),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const bP=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 _P{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class Oz{constructor(p){this.colorModeAlphaBlendedWriteRGB=new Tn([1,xl,1,xl],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Tn([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new _P,this.updateNeeded=!0}update(p){const j=p.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new vP(j);const L=this.params.sizeRange,O=this.params.intensityRange,q=function(pe){const Ce=o.em(30),je=[];for(let Me=0;Me{const _t=q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];$t&&_t.push("ALPHA_PASS");const St=p.getOrCreateProgram("globeAtmosphere",{defines:_t}),Rt=((qt,xs,as,Os,Hs,Qt,Ht,us,vs,ks,cr,Js)=>({u_frustum_tl:qt,u_frustum_tr:xs,u_frustum_br:as,u_frustum_bl:Os,u_horizon:Hs,u_transition:Qt,u_fadeout_range:Ht,u_atmosphere_fog_color:us.toArray01(),u_high_color:vs.toArray01(),u_space_color:ks.toArray01(),u_temporal_offset:cr,u_horizon_angle:Js}))(q.frustumCorners.TL,q.frustumCorners.TR,q.frustumCorners.BR,q.frustumCorners.BL,q.frustumCorners.horizon,Y,nt,pe,je,qe,pt,Ut);p.uploadCommonUniforms(L,St);const Zt=this.atmosphereBuffer;Zt&&St.draw(p,O.TRIANGLES,H,Mn.disabled,$t?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,vn.backCW,Rt,$t?"atmosphere_glow_alpha":"atmosphere_glow",Zt.vertexBuffer,Zt.indexBuffer,Zt.segments)};Tt(!1),Tt(!0)}drawStars(p,j){const L=o.aC(j.properties.get("star-intensity"),0,1);if(L===0)return;const O=p.context,q=O.gl,H=p.transform,Y=p.getOrCreateProgram("stars"),te=o.bL([]);o.bN(te,te,-H._pitch),o.bM(te,te,-H.angle),o.bN(te,te,o.ap(H._center.lat)),o.ek(te,te,-o.ap(H._center.lng));const de=o.bR(new Float32Array(16),te),pe=o.aD([],H.starsProjMatrix,de),Ce=o.eg([],de),je=o.el([],Ce),Me=[0,1,0];o.dG(Me,Me,je),o.bJ(Me,Me,this.params.sizeMultiplier);const qe=[1,0,0];o.dG(qe,qe,je),o.bJ(qe,qe,this.params.sizeMultiplier);const $e=(nt=Me,rt=qe,pt=L,{u_matrix:Float32Array.from(pe),u_up:nt,u_right:rt,u_intensity_multiplier:pt});var nt,rt,pt;p.uploadCommonUniforms(O,Y),this.starsVx&&this.starsIdx&&Y.draw(p,q.TRIANGLES,$r.disabled,Mn.disabled,this.colorModeAlphaBlendedWriteRGB,vn.disabled,$e,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Fg{constructor(){this.visibleTiles=[]}updateBorders(p,j){const L=[],O=[],q=p._getRenderableCoordinates(!1,!0);for(const te of q){const de=p.getTile(te);if(!de.hasData())continue;const pe=de.getBucket(j);pe&&(pe.isEmpty()||(L.push(te.key),O.push({bucket:pe,tileID:te.canonical})))}let H=L.length!==this.visibleTiles.length;if(!H){L.sort();for(let te=0;tete.tileID.z-de.tileID.z||te.tileID.x-de.tileID.x||te.tileID.y-de.tileID.y);for(const te of O){const de=new Array,pe=new Array,Ce=te.bucket;for(const je of Ce.featuresOnBorder)Y.has(je.featureId)?pe.push(je.footprintIndex):(Y.add(je.featureId),de.push(je.footprintIndex));Ce.updateFootprintHiddenFlags(de,o.en,!1),Ce.updateFootprintHiddenFlags(pe,o.en,!0)}}}function Fz(E,p){const j=[...E],L=p.cameraWorldSizeForFog/p.worldSize,O=o.b9([]);return o.cC(O,O,[L,L,1]),o.aD(j,O,j),o.aD(j,p.worldToFogMatrix,j),j}function ui(E,p,j,L,O){const q=j.material,H=L.context,{baseColorTexture:Y,metallicRoughnessTexture:te}=q.pbrMetallicRoughness,{normalTexture:de,occlusionTexture:pe,emissionTexture:Ce}=q;function je(qe,$e,nt){if(qe&&(E.push($e),H.activeTexture.set(H.gl.TEXTURE0+nt),qe.gfxTexture)){const{minFilter:rt,magFilter:pt,wrapS:vt,wrapT:ot}=qe.sampler;qe.gfxTexture.bindExtraParam(rt,pt,vt,ot)}}je(Y,"HAS_TEXTURE_u_baseColorTexture",5),je(te,"HAS_TEXTURE_u_metallicRoughnessTexture",6),je(de,"HAS_TEXTURE_u_normalTexture",7),je(pe,"HAS_TEXTURE_u_occlusionTexture",8),je(Ce,"HAS_TEXTURE_u_emissionTexture",9),O&&(O.texture||(O.texture=new o.dR(L.context,O.image,[O.image.height,O.image.height,O.image.height],H.gl.RGBA8)),H.activeTexture.set(H.gl.TEXTURE0+10),O.texture&&O.texture.bind(H.gl.LINEAR,H.gl.CLAMP_TO_EDGE),E.push("APPLY_LUT_ON_GPU")),j.texcoordBuffer&&(E.push("HAS_ATTRIBUTE_a_uv_2f"),p.push(j.texcoordBuffer)),j.colorBuffer&&(E.push(j.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),p.push(j.colorBuffer)),j.normalBuffer&&(E.push("HAS_ATTRIBUTE_a_normal_3f"),p.push(j.normalBuffer)),j.pbrBuffer&&(E.push("HAS_ATTRIBUTE_a_pbr"),E.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),p.push(j.pbrBuffer)),q.alphaMode!=="OPAQUE"&&q.alphaMode!=="MASK"||E.push("UNPREMULT_TEXTURE_IN_SHADER"),q.defined||E.push("DIFFUSE_SHADED");const Me=L.shadowRenderer;Me&&(E.push("RENDER_SHADOWS"),Me.useNormalOffset&&E.push("NORMAL_OFFSET"))}function p_(E,p,j,L,O,q){const H=E.modelOpacity,Y=p.context,te=new $r(p.context.gl.LEQUAL,E.isLightMesh?$r.ReadOnly:$r.ReadWrite,p.depthRangeFor3D),de=p.transform,pe=E.mesh,Ce=pe.material,je=Ce.pbrMetallicRoughness,Me=p.style.fog;let qe;qe=p.transform.projection.zAxisUnit==="pixels"?[...E.nodeModelMatrix]:o.aD([],L.zScaleMatrix,E.nodeModelMatrix),o.aD(qe,L.negCameraPosMatrix,qe);const $e=o.b7([],qe);o.e6($e,$e);const nt=j.paint.get("model-color-use-theme").constantOr("default")==="none",rt=j.paint.get("model-emissive-strength").constantOr(0),pt=o1(new Float32Array(E.worldViewProjection),new Float32Array(qe),new Float32Array($e),null,p,H,je.baseColorFactor,Ce.emissiveFactor,je.metallicFactor,je.roughnessFactor,Ce,rt,j,void 0,void 0,E.materialOverride,E.modelColor),vt={defines:[]},ot=[],Ut=p.shadowRenderer;Ut&&(Ut.useNormalOffset=!1),ui(vt.defines,ot,pe,p,nt?null:j.lut);let Tt=null;if(Me){const St=Fz(E.nodeModelMatrix,p.transform);if(Tt=new Float32Array(St),de.projection.name!=="globe"){const Rt=pe.aabb.min,Zt=pe.aabb.max,[qt,xs]=Me.getOpacityForBounds(St,Rt[0],Rt[1],Zt[0],Zt[1]);vt.overrideFog=qt>=un||xs>=un}}const $t=Mc(p,j.paint.get("model-cutoff-fade-range"));$t.shouldRenderCutoff&&vt.defines.push("RENDER_CUTOFF");const _t=p.getOrCreateProgram("model",vt);p.uploadCommonUniforms(Y,_t,null,Tt,$t),p.renderPass!=="shadow"&&Ut&&Ut.setupShadowsFromMatrix(E.nodeModelMatrix,_t),_t.draw(p,Y.gl.TRIANGLES,te,O,q,pe.material.doubleSided?vn.disabled:vn.backCCW,pt,j.id,pe.vertexBuffer,pe.indexBuffer,pe.segments,j.paint,p.transform.zoom,void 0,ot)}function X5(E,p){return E.style._importedAsBasemap?"basemap":p.scope}function Q5(E,p,j,L,O,q,H,Y,te,de){const pe=E.transform,Ce=!!p.isGeometryBloom&&p.isGeometryBloom;if(Ce&&E.renderPass==="shadow")return;const je=pe.projection.name==="globe"?o.ev(j,pe):[...j];o.aD(je,je,p.globalMatrix);const Me=o.aD([],L,je);if(p.meshes)for(const qe of p.meshes){const $e=Y.get(qe.material.name);if($e&&$e.opacity<=0)continue;if(qe.material.alphaMode!=="BLEND"){H.push({mesh:qe,depth:0,modelIndex:O,worldViewProjection:Me,nodeModelMatrix:je,isLightMesh:Ce,materialOverride:$e,modelOpacity:te,modelColor:de,node:p,modelMatrix:j});continue}const nt=o.ah([],qe.centroid,Me);!pe.isOrthographic&&nt[2]<=0||q.push({mesh:qe,depth:nt[2],modelIndex:O,worldViewProjection:Me,nodeModelMatrix:je,isLightMesh:Ce,materialOverride:$e,modelOpacity:te,modelColor:de,node:p,modelMatrix:j})}if(p.children)for(const qe of p.children)Q5(E,qe,j,L,O,q,H,Y,te,de)}function x_(E,p,j,L){const O=j.shadowRenderer;if(!O)return;const q=O.getShadowPassDepthMode(),H=O.calculateShadowPassMatrixFromMatrix(p),Y=aP(H);j.getOrCreateProgram("modelDepth").draw(j,j.context.gl.TRIANGLES,q,Mn.disabled,Tn.disabled,vn.disabled,Y,L.id,E.vertexBuffer,E.indexBuffer,E.segments,L.paint,j.transform.zoom,void 0,void 0)}function wP(E,p,j,L){const O=function(pe,Ce){if(Ce.footprintDebugMesh)return Ce.footprintDebugMesh;if(!Ce.footprint)return null;const je=pe.context,Me=Ce.footprint.vertices,qe=Ce.footprint.indices,$e=new o.dB;$e.reserve(Me.length);for(const Rt of Me)$e.emplaceBack(Rt.x,Rt.y);const nt=new o.dC;nt.reserve(qe.length);for(let Rt=0;Rt0){const je=q.terrain,Me=je.findDEMTileFor(Y);Me&&Me.dem?te=o.ex.create(je,Y,Me):Ce=0}if(Ce===0&&(H.terrainElevationMin=0,H.terrainElevationMax=0),Ce===H.validForExaggeration&&(Ce===0||te&&te._demTile&&te._demTile.tileID===H.validForDEMTile.id&&te._dem._timestamp===H.validForDEMTile.timestamp))return!1;for(const je in H.instancesPerModel){const Me=H.instancesPerModel[je];for(let qe=0;qede&&(de=Me.max)}const pe=o.aC(L.x,q,H)-L.x,Ce=o.aC(L.y,Y,te)-L.y,je=o.bU(de,p.center.lat)-L.z;return p._zoomFromMercatorZ(Math.sqrt(pe*pe+Ce*Ce+je*je))}function jo(E,p,j,L,O,q,H){const Y=E.context,te=E.renderPass==="shadow",de=E.shadowRenderer,pe=te&&de?de.getShadowPassDepthMode():new $r(Y.gl.LEQUAL,$r.ReadWrite,E.depthRangeFor3D),Ce=E.isTileAffectedByFog(q),je=E.transform.projection.name==="globe";if(j.meshes)for(const Me of j.meshes){const qe=je?[]:["MODEL_POSITION_ON_GPU"],$e=[];let nt,rt,pt;const vt=!je&&L.instancedDataArray.length>20;vt&&qe.push("INSTANCED_ARRAYS");const ot=Mc(E,p.paint.get("model-cutoff-fade-range"));if(ot.shouldRenderCutoff&&qe.push("RENDER_CUTOFF"),te&&de)nt=E.getOrCreateProgram("modelDepth",{defines:qe}),rt=aP(H.shadowTileMatrix,H.shadowTileMatrix,Float32Array.from(j.globalMatrix)),pt=Tn.disabled;else{ui(qe,$e,Me,E,p.paint.get("model-color-use-theme").constantOr("default")==="none"?null:p.lut),nt=E.getOrCreateProgram("model",{defines:qe,overrideFog:Ce});const Tt=Me.material,$t=Tt.pbrMetallicRoughness,_t=p.paint.get("model-opacity").constantOr(1),St=p.paint.get("model-emissive-strength").constantOr(0);rt=o1(q.expandedProjMatrix,Float32Array.from(j.globalMatrix),new Float32Array(16),null,E,_t,$t.baseColorFactor,Tt.emissiveFactor,$t.metallicFactor,$t.roughnessFactor,Tt,St,p,O),de&&(H.shadowUniformsInitialized?nt.setShadowUniformValues(Y,de.getShadowUniformValues()):(de.setupShadows(q.toUnwrapped(),nt,"model-tile"),H.shadowUniformsInitialized=!0)),pt=ot.shouldRenderCutoff||_t<1||Tt.alphaMode!=="OPAQUE"?Tn.alphaBlended:Tn.unblended}E.uploadCommonUniforms(Y,nt,q.toUnwrapped(),null,ot);const Ut=Me.material.doubleSided?vn.disabled:vn.backCCW;if(vt)$e.push(L.instancedDataBuffer),nt.draw(E,Y.gl.TRIANGLES,pe,Mn.disabled,pt,Ut,rt,p.id,Me.vertexBuffer,Me.indexBuffer,Me.segments,p.paint,E.transform.zoom,void 0,$e,L.instancedDataArray.length);else{const Tt=te?"u_instance":"u_normal_matrix";for(let $t=0;$tte[1]?H:te,q[0]=j.max[0],H=o.aE(o.bE(),q,O),Y=H[1]te[1]?H:te,q[1]=j.min[1],H=o.aE(o.bE(),q,O),Y=H[1]te[1]?H:te;const de=o.aC(L[0],0,1),pe=100*p.pixelsPerMeter*o.aC(L[1],0,1),Ce=o.aC(L[2],0,1),je=o.ey(o.bE(),Y,te,de),Me=Math.tan(.5*p.fovX),qe=-je[2]*Me;if(pe===0)return je[1]<-Math.abs(qe)?Ce:1;const $e=(-Math.abs(qe)-je[1])/pe,nt=(pt,vt,ot)=>(1-ot)*pt+ot*vt,rt=o.aC(nt(1,Ce,$e),Ce,1);return nt(1,rt,o.aC((p.pitch-20)/20,0,1))}class eT{}class zz{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(p,j,L){{const Ce=this._storage.get(j.id);if(Ce)return Ce.lastUsedFrameIdx=p,Ce.buf}const O=L.gl,q=O.getBufferParameter(O.ELEMENT_ARRAY_BUFFER,O.BUFFER_SIZE),H=new ArrayBuffer(q),Y=new Int16Array(H);O.getBufferSubData(O.ELEMENT_ARRAY_BUFFER,0,new Int16Array(H));const te=new o.eA;for(let Ce=0;Ce30&&(L.buf.destroy(),this._storage.delete(j))}destroy(){for(const[p,j]of this._storage)j.buf.destroy(),this._storage.delete(p)}}class $z{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const y_=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 Uz{constructor(p){this.revealStart=11,this.revealRange=2}}const Nge=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class qz{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(p,j){const L=p.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const H=new o.eB,Y=new o.dC;H.emplaceBack(-1,-1),H.emplaceBack(1,-1),H.emplaceBack(1,1),H.emplaceBack(-1,1),Y.emplaceBack(0,1,2),Y.emplaceBack(0,2,3),this.vignetteVx=p.context.createVertexBuffer(H,Nge.members),this.vignetteIdx=p.context.createIndexBuffer(Y)}const O=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){p.uploadCommonUniforms(p.context,L);const H={u_vignetteShape:(q={vignetteShape:[j.start,j.range,Math.pow(10,j.fadePower)],vignetteColor:[j.color.r,j.color.g,j.color.b,j.color.a*j.strength]}).vignetteShape,u_vignetteColor:q.vignetteColor};L.draw(p,p.context.gl.TRIANGLES,$r.disabled,Mn.disabled,Tn.alphaBlended,vn.disabled,H,"vignette",this.vignetteVx,this.vignetteIdx,O)}var q}}class tT{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(p,j){const L=p.getFreeCameraOptions().position,O=L.toAltitude(),q=L.toLngLat(),H=o.ap(q.lng),Y=o.ap(q.lat),te=p.pixelsPerMeter/j,de=H*o.eD,pe=o.eD*Math.log(Math.tan(Math.PI/4+Y/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 Ce=-this._offsetYPrev+pe,je=-this._elevationPrev+O;this._accumulatedOffsetX+=(-this._offsetXPrev+de)*te,this._accumulatedOffsetY+=Ce*te,this._accumulatedElevation+=je*te,this._offsetXPrev=de,this._offsetYPrev=pe,this._elevationPrev=O}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function sT(E,p){return[-(E[0]-Math.floor(E[0]/p)*p),-(E[1]-Math.floor(E[1]/p)*p),-(E[2]-Math.floor(E[2]/p)*p)]}function kP(E){const p=o.em(1323123451230),j=[];for(let L=0;L Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(p){const j=p.context;if(!this.particlesVx){const L=kP(this.particlesCount),O=new o.eE,q=new o.dC;let H=0;const Y=o.em(1323123451230);for(let te=0;teL)return;const O=zg(0,1,j.revealStart,j.revealStart+j.revealRange,L);if(!this.particlesVx||!this.particlesIdx)return;const q=structuredClone(this._params);let H=[-q.direction.x,q.direction.y,-100];o.ay(H,H);const Y=structuredClone(this._vignetteParams);Y.strength*=O,q.overrideStyleParameters||(q.intensity=p.style.rain.state.density,q.timeFactor=p.style.rain.state.intensity,q.color=structuredClone(p.style.rain.state.color),H=structuredClone(p.style.rain.state.direction),q.screenThinning.intensity=p.style.rain.state.centerThinning,q.dropletSizeX=p.style.rain.state.dropletSize[0],q.dropletSizeYScale=p.style.rain.state.dropletSize[1]/p.style.rain.state.dropletSize[0],q.distortionStrength=100*p.style.rain.state.distortionStrength,Y.strength=1,Y.color=structuredClone(p.style.rain.state.vignetteColor));const te=this.updateOnRender(p,q.timeFactor),de=p.context,pe=de.gl,Ce=p.transform;this.screenTexture&&this.screenTexture.size[0]===p.width&&this.screenTexture.size[1]===p.height||(this.screenTexture=new o.T(de,{width:p.width,height:p.height,data:null},pe.RGBA8)),q.distortionStrength>0&&(de.activeTexture.set(pe.TEXTURE0),this.screenTexture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE),pe.copyTexSubImage2D(pe.TEXTURE_2D,0,0,0,0,0,p.width,p.height));const je=p.getOrCreateProgram("rainParticle");p.uploadCommonUniforms(de,je),de.activeTexture.set(pe.TEXTURE0),this.screenTexture.bind(pe.LINEAR,pe.CLAMP_TO_EDGE);const Me=[q.color.r,q.color.g,q.color.b,q.color.a],qe=($e,nt)=>{const rt=sT(this._movement.getPosition(),$e),pt=q.dropletSizeX,vt=q.dropletSizeX*q.dropletSizeYScale,ot=p.width/2,Ut=p.height/2,Tt=zg(0,q.screenThinning.start,0,1,q.screenThinning.intensity),$t=zg(.001,q.screenThinning.range,0,1,q.screenThinning.intensity),_t=zg(0,q.screenThinning.particleOffset,0,1,q.screenThinning.intensity),St=(Rt={modelview:te.modelviewMatrix,projection:te.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:rt,velocityConeAperture:q.velocityConeAperture,velocity:q.velocity,boxSize:$e,rainDropletSize:[pt,vt],distortionStrength:q.distortionStrength,rainDirection:H,color:Me,screenSize:[Ce.width,Ce.height],thinningCenterPos:[ot,Ut],thinningShape:[Tt,$t,Math.pow(10,q.screenThinning.fadePower)],thinningAffectedRatio:q.screenThinning.affectedRatio,thinningParticleOffset:_t,shapeDirectionalPower:q.shapeDirPower,shapeNormalPower:q.shapeNormalPower,mode:nt?0:1},{u_modelview:Float32Array.from(Rt.modelview),u_projection:Float32Array.from(Rt.projection),u_time:Rt.time,u_cam_pos:Rt.camPos,u_texScreen:0,u_velocityConeAperture:Rt.velocityConeAperture,u_velocity:Rt.velocity,u_boxSize:Rt.boxSize,u_rainDropletSize:Rt.rainDropletSize,u_distortionStrength:Rt.distortionStrength,u_rainDirection:Rt.rainDirection,u_color:Rt.color,u_screenSize:Rt.screenSize,u_thinningCenterPos:Rt.thinningCenterPos,u_thinningShape:Rt.thinningShape,u_thinningAffectedRatio:Rt.thinningAffectedRatio,u_thinningParticleOffset:Rt.thinningParticleOffset,u_shapeDirectionalPower:Rt.shapeDirectionalPower,u_shapeNormalPower:Rt.shapeNormalPower,u_mode:Rt.mode});var Rt;const Zt=Math.round(q.intensity*this.particlesCount),qt=o.dy.simpleSegment(0,0,4*Zt,2*Zt);je.draw(p,pe.TRIANGLES,$r.disabled,Mn.disabled,Tn.alphaBlended,vn.disabled,St,"rain_particles",this.particlesVx,this.particlesIdx,qt)};q.distortionStrength>0&&qe(q.boxSize,!0),qe(q.boxSize,!1),this._vignette.draw(p,Y)}}const h1=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 Vz extends W2{constructor(p){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 Uz("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(p){const j=p.context;if(!this.particlesVx){const L=kP(this.particlesCount),O=new o.eF,q=new o.dC;let H=0;const Y=o.em(1323123451230);for(let te=0;teH)return;const Y=zg(0,1,q.revealStart,q.revealStart+q.revealRange,H);O.strength*=Y,j.overrideStyleParameters||(j.intensity=p.style.snow.state.density,j.timeFactor=p.style.snow.state.intensity,j.color=structuredClone(p.style.snow.state.color),L=structuredClone(p.style.snow.state.direction),j.screenThinning.intensity=p.style.snow.state.centerThinning,j.billboardSize=2.79*p.style.snow.state.flakeSize,O.strength=1,O.color=structuredClone(p.style.snow.state.vignetteColor));const te=this.updateOnRender(p,j.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const de=p.context,pe=de.gl,Ce=p.transform,je=p.getOrCreateProgram("snowParticle");p.uploadCommonUniforms(de,je),((Me,qe,$e)=>{const nt=sT(this._movement.getPosition(),Me),rt=Ce.width/2,pt=Ce.height/2,vt=zg(0,$e.screenThinning.start,0,1,$e.screenThinning.intensity),ot=zg(.001,$e.screenThinning.range,0,1,$e.screenThinning.intensity),Ut=zg(0,$e.screenThinning.particleOffset,0,1,$e.screenThinning.intensity),Tt=($t={modelview:te.modelviewMatrix,projection:te.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:nt,velocityConeAperture:$e.velocityConeAperture,velocity:$e.velocity,horizontalOscillationRadius:$e.horizontalOscillationRadius,horizontalOscillationRate:$e.horizontalOscillationRate,boxSize:Me,billboardSize:1*$e.billboardSize,simpleShapeParameters:[$e.shapeFadeStart,$e.shapeFadePower],screenSize:[Ce.width,Ce.height],thinningCenterPos:[rt,pt],thinningShape:[vt,ot,Math.pow(10,$e.screenThinning.fadePower)],thinningAffectedRatio:$e.screenThinning.affectedRatio,thinningParticleOffset:Ut,color:[$e.color.r,$e.color.g,$e.color.b,$e.color.a],direction:L},{u_modelview:Float32Array.from($t.modelview),u_projection:Float32Array.from($t.projection),u_time:$t.time,u_cam_pos:$t.camPos,u_velocityConeAperture:$t.velocityConeAperture,u_velocity:$t.velocity,u_horizontalOscillationRadius:$t.horizontalOscillationRadius,u_horizontalOscillationRate:$t.horizontalOscillationRate,u_boxSize:$t.boxSize,u_billboardSize:$t.billboardSize,u_simpleShapeParameters:$t.simpleShapeParameters,u_screenSize:$t.screenSize,u_thinningCenterPos:$t.thinningCenterPos,u_thinningShape:$t.thinningShape,u_thinningAffectedRatio:$t.thinningAffectedRatio,u_thinningParticleOffset:$t.thinningParticleOffset,u_particleColor:$t.color,u_direction:$t.direction});var $t;const _t=Math.round($e.intensity*this.particlesCount),St=o.dy.simpleSegment(0,0,4*_t,2*_t);this.particlesVx&&this.particlesIdx&&je.draw(p,pe.TRIANGLES,$r.disabled,Mn.disabled,Tn.alphaBlended,vn.disabled,Tt,"snow_particles",this.particlesVx,this.particlesIdx,St)})(j.boxSize,0,j),this._vignette.draw(p,O)}}const Hz={symbol:function(E,p,j,L,O){if(E.renderPass!=="translucent")return;const q=Mn.disabled,H=E.colorModeForRenderPass(),Y=j.layout.get("text-variable-anchor"),te=j.layout.get("text-size-scale-range"),de=o.aC(E.scaleFactor,te[0],te[1]);Y&&function(je,Me,qe,$e,nt,rt,pt,vt){const ot=Me.transform,Ut=nt==="map",Tt=rt==="map";for(const $t of je){const _t=$e.getTile($t),St=_t.getBucket(qe);if(!St||!St.text||!St.text.segments.get().length)continue;const Rt=o.bj(St.textSizeData,ot.zoom,vt),Zt=Mg($t,St.getProjection(),ot),qt=ot.calculatePixelsToTileUnitsMatrix(_t),xs=yx(Zt,_t.tileID.canonical,Tt,Ut,ot,St.getProjection(),qt),as=St.hasIconTextFit()&&St.hasIconData();Rt&&Tz(St,Ut,Tt,pt,ot,xs,$t,Math.pow(2,ot.zoom-_t.tileID.overscaledZ),Rt,as)}}(L,E,j,p,j.layout.get("text-rotation-alignment"),j.layout.get("text-pitch-alignment"),O,de);const pe=j.paint.get("icon-opacity").constantOr(1)!==0,Ce=j.paint.get("text-opacity").constantOr(1)!==0;j.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(pe||Ce)?V5(E,p,j,L,q,H):(pe&&V5(E,p,j,L,q,H,{onlyIcons:!0}),Ce&&V5(E,p,j,L,q,H,{onlyText:!0})),p.map.showCollisionBoxes&&(Dr(E,p,j,L,j.paint.get("text-translate"),j.paint.get("text-translate-anchor"),!0),Dr(E,p,j,L,j.paint.get("icon-translate"),j.paint.get("icon-translate-anchor"),!1))},circle:function(E,p,j,L){if(E.renderPass!=="translucent")return;const O=j.paint.get("circle-opacity"),q=j.paint.get("circle-stroke-width"),H=j.paint.get("circle-stroke-opacity"),Y=j.layout.get("circle-sort-key").constantOr(1)!==void 0,te=j.paint.get("circle-emissive-strength");if(O.constantOr(1)===0&&(q.constantOr(1)===0||H.constantOr(1)===0))return;const de=E.context,pe=de.gl,Ce=E.transform,je=!(!E.terrain||!E.terrain.enabled),Me=j.layout.get("circle-elevation-reference"),qe=E.depthModeForSublayer(0,$r.ReadOnly),$e=new $r(E.context.gl.LEQUAL,$r.ReadOnly,E.depthRangeFor3D),nt=Me==="none"||je?qe:$e,rt=Mn.disabled,pt=E.colorModeForDrapableLayerRenderPass(te),vt=Ce.projection.name==="globe",ot=[o.aH(Ce.center.lng),o.aL(Ce.center.lat)],Ut=[];for(let $t=0;$t$t.sortKey-_t.sortKey);const Tt={useDepthForOcclusion:Ce.depthOcclusionForSymbolsAndCircles};for(const $t of Ut){const{programConfiguration:_t,program:St,layoutVertexBuffer:Rt,dynamicBuffers:Zt,indexBuffer:qt,uniformValues:xs,tile:as}=$t.state,Os=$t.segments;E.terrain&&E.terrain.setupElevationDraw(as,St,Tt),E.uploadCommonUniforms(de,St,as.tileID.toUnwrapped()),St.draw(E,pe.TRIANGLES,nt,rt,pt,vn.disabled,xs,j.id,Rt,qt,Os,j.paint,Ce.zoom,_t,Zt)}},heatmap:function(E,p,j,L){if(j.paint.get("heatmap-opacity")!==0)if(E.renderPass==="offscreen"){const O=E.context,q=O.gl,H=Mn.disabled,Y=new Tn([q.ONE,q.ONE,q.ONE,q.ONE],o.aq.transparent,[!0,!0,!0,!0]),te=E.transform.projection.name==="globe"?.5:.25;j.heatmapFbo=U2.createWithTexture(O,j.heatmapFbo,E.width*te,E.height*te),O.clear({color:o.aq.transparent});const de=E.transform,pe=de.projection.name==="globe",Ce=pe?["PROJECTION_GLOBE_VIEW"]:[],je=pe?vn.frontCCW:vn.disabled,Me=[o.aH(de.center.lng),o.aL(de.center.lat)];for(let qe=0;qe({u_image:0,u_color_ramp:1,u_opacity:Ce.paint.get("heatmap-opacity")}))(0,q),q.id,O.viewportBuffer,O.quadTriangleIndexBuffer,O.viewportSegments,q.paint,O.transform.zoom)}(E,j))},line:function(E,p,j,L){const O=j.paint.get("line-opacity"),q=j.paint.get("line-width");if(O.constantOr(1)===0||q.constantOr(1)===0)return;const H=j.paint.get("line-blend-mode");if(H!=="default"&&E.transform.projection.name!=="globe")return E.terrain&&E.terrain.renderingToTexture?void function(Y,te,de,pe,Ce){if(Y.renderPass!=="translucent")return;const je=Y.context,Me=je.gl,qe=Y.terrain;if(!qe)return;const $e=je.bindFramebuffer.current,nt=Y.emissiveMode==="mrt-fallback";de.lineBlendDrapeFbo=U2.createWithTexture(je,de.lineBlendDrapeFbo,qe.drapeBufferSize[0],qe.drapeBufferSize[1],!0),de.lineBlendDrapeStencil=de.lineBlendDrapeFbo._stencilRbo,nt&&Me.drawBuffers([Me.COLOR_ATTACHMENT0]),je.clear({color:Og[Ce].clearColor,depth:1,stencil:0});const rt=Y.currentStencilSource,pt=Y._tileClippingMaskIDs,vt=Y.nextStencilID;Y.currentStencilSource=void 0,Y._tileClippingMaskIDs={},Y.nextStencilID=1;const ot=Y._terrain;Y._terrain=null,Y._renderTileClippingMasks(de,te,pe),G5(Y,te,de,pe,Og[Ce].colorMode,!0),Y._terrain=ot,Y.currentStencilSource=rt,Y._tileClippingMaskIDs=pt,Y.nextStencilID=vt,je.bindFramebuffer.set($e),nt&&Me.drawBuffers([Me.COLOR_ATTACHMENT0,Me.COLOR_ATTACHMENT1]);const Ut=qe.drapeBufferSize;je.viewport.set([0,0,Ut[0],Ut[1]]);const Tt=de.lineBlendDrapeFbo;if(!Tt)return;je.activeTexture.set(Me.TEXTURE0),Me.bindTexture(Me.TEXTURE_2D,Tt.colorAttachment0.get());const $t=Ce==="additive"?1:de.paint.get("line-opacity").constantOr(1),_t=de.paint.get("line-emissive-strength").constantOr(0),St=Ce==="additive"?Y.colorModeForDrapableLayerRenderPass(_t):Og[Ce].colorMode;Y.getOrCreateProgram("lineBlendComposite").draw(Y,Me.TRIANGLES,$r.disabled,Mn.disabled,St,vn.disabled,O5(0,$t,Og[Ce].compositeUniformValue),de.id,Y.viewportBuffer,Y.quadTriangleIndexBuffer,Y.viewportSegments,de.paint,Y.transform.zoom)}(E,p,j,L,H):E.renderPass==="offscreen"?void function(Y,te,de,pe,Ce){const je=Y.context,Me=Math.ceil(Y.width),qe=Math.ceil(Y.height);de.lineBlendFbo=U2.createWithTexture(je,de.lineBlendFbo,Me,qe,!0),de.lineBlendStencil=de.lineBlendFbo._stencilRbo,je.clear({color:Og[Ce].clearColor,depth:1,stencil:0});const $e=Y.currentStencilSource,nt=Y._tileClippingMaskIDs,rt=Y.nextStencilID;Y.currentStencilSource=void 0,Y._tileClippingMaskIDs={},Y.nextStencilID=1,Y._renderTileClippingMasks(de,te,pe);const pt=Y.renderPass;Y.renderPass="translucent",G5(Y,te,de,pe,Og[Ce].colorMode),Y.renderPass=pt,Y.currentStencilSource=$e,Y._tileClippingMaskIDs=nt,Y.nextStencilID=rt,je.viewport.set([0,0,Y.width,Y.height])}(E,p,j,L,H):E.renderPass==="translucent"?void function(Y,te,de){const pe=Y.context,Ce=pe.gl,je=te.lineBlendFbo;if(!je)return;pe.activeTexture.set(Ce.TEXTURE0),Ce.bindTexture(Ce.TEXTURE_2D,je.colorAttachment0.get());const Me=de==="additive"?1:te.paint.get("line-opacity").constantOr(1),qe=de==="additive"?Y.colorModeForDrapableLayerRenderPass(te.paint.get("line-emissive-strength").constantOr(0)):Og[de].colorMode;Y.getOrCreateProgram("lineBlendComposite").draw(Y,Ce.TRIANGLES,$r.disabled,Mn.disabled,qe,vn.disabled,O5(0,Me,Og[de].compositeUniformValue),te.id,Y.viewportBuffer,Y.quadTriangleIndexBuffer,Y.viewportSegments,te.paint,Y.transform.zoom)}(E,j,H):void 0;E.renderPass==="translucent"&&G5(E,p,j,L)},fill:function(E,p,j,L){const O=j.paint.get("fill-color"),q=j.paint.get("fill-opacity");if(q.constantOr(1)===0)return;const H=j.paint.get("fill-emissive-strength"),Y=E.colorModeForDrapableLayerRenderPass(H),te=j.paint.get("fill-pattern"),de=E.opaquePassEnabledForLayer()&&!te.constantOr(1)&&O.constantOr(o.aq.transparent).a===1&&q.constantOr(0)===1?"opaque":"translucent";let pe="none";j.layout.get("fill-elevation-reference")!=="none"?pe="road":j.paint.get("fill-z-offset").constantOr(1)!==0&&(pe="offset");const Ce=!(!E.terrain||!E.terrain.enabled),je={painter:E,sourceCache:p,layer:j,coords:L,colorMode:Y,elevationType:pe,terrainEnabled:Ce,pass:de};if(E.renderPass==="shadow")return void(E.shadowRenderer&&pe==="road"&&!Ce&&function(qe){const{painter:$e,sourceCache:nt,layer:rt,coords:pt}=qe,vt=$e.context.gl,ot=qe.painter.shadowRenderer;for(const Ut of pt){const Tt=nt.getTile(Ut),$t=Tt.getBucket(rt);if(!$t)continue;const _t=$t.elevatedStructures;if(!_t||!_t.shadowCasterSegments||_t.shadowCasterSegments.segments[0].primitiveLength===0)continue;$e.prepareDrawTile();const St=$t.bufferData.programConfigurations.get(rt.id),Rt=$e.isTileAffectedByFog(Ut),Zt=$e.getOrCreateProgram("elevatedStructuresDepth",{config:St,overrideFog:Rt}),qt=ot.calculateShadowPassMatrixFromTile(Tt.tileID.toUnwrapped());$e.uploadCommonUniforms($e.context,Zt,Ut.toUnwrapped());const xs=vz(qt,0);Zt.draw($e,vt.TRIANGLES,ot.getShadowPassDepthMode(),Mn.disabled,Tn.disabled,vn.disabled,xs,rt.id,_t.vertexBuffer,_t.indexBuffer,_t.shadowCasterSegments,rt.paint,$e.transform.zoom,St)}}(je));const Me=E.emissiveMode==="mrt-fallback";if(pe!=="offset"){if(H2(je,!1,Me),pe==="road"){const qe=!Ce&&E.renderPass==="translucent";qe&&V2(E,p,j,L,"geometry"),H2(je,!0,Me,Mn.disabled),qe&&function($e){const{painter:nt,sourceCache:rt,layer:pt,coords:vt,colorMode:ot}=$e,Ut=nt.context.gl,Tt=$e.painter.shadowRenderer,$t=!!Tt&&Tt.enabled,_t=new $r(nt.context.gl.LEQUAL,$r.ReadOnly,nt.depthRangeFor3D);let St=[0,0,0];if($t){const Zt=nt.style.directionalLight,qt=nt.style.ambientLight;Zt&&qt&&(St=up(nt.style,Zt,qt))}const Rt=Zt=>{for(const qt of vt){const xs=rt.getTile(qt),as=xs.getBucket(pt);if(!as)continue;const Os=as.elevatedStructures;if(!Os)continue;let Hs,Qt;if(Zt?(Hs=Os.renderableBridgeSegments,Qt=Os.bridgeProgramConfigurations.get(pt.id)):(Hs=Os.renderableTunnelSegments,Qt=Os.tunnelProgramConfigurations.get(pt.id)),!Hs||Hs.segments[0].primitiveLength===0)continue;Qt.updatePaintBuffers(),nt.prepareDrawTile();const Ht=nt.isTileAffectedByFog(qt),us=[];$t&&us.push("RENDER_SHADOWS","NORMAL_OFFSET");const vs=nt.getOrCreateProgram("elevatedStructures",{config:Qt,overrideFog:Ht,defines:us}),ks=nt.translatePosMatrix(qt.projMatrix,xs,pt.paint.get("fill-translate"),pt.paint.get("fill-translate-anchor"));$t&&Tt.setupShadows(xs.tileID.toUnwrapped(),vs,"vector-tile");const cr=bz(ks,St);nt.uploadCommonUniforms(nt.context,vs,qt.toUnwrapped()),vs.draw(nt,Ut.TRIANGLES,_t,Mn.disabled,ot,vn.backCCW,cr,pt.id,Os.vertexBuffer,Os.indexBuffer,Hs,pt.paint,nt.transform.zoom,Qt,[Os.vertexBufferNormal])}};Rt(!0),Rt(!1)}(je)}}else H2(je,!1,Me,E.stencilModeFor3D())},"fill-extrusion":function(E,p,j,L){const O=j.paint.get("fill-extrusion-opacity"),q=E.context,H=q.gl,Y=E.terrain,te=Y&&Y.renderingToTexture;if(O===0)return;const de=E.emissiveMode==="mrt-fallback",pe=E.conflationActive&&E.style.isLayerClipped(j,p.getSource()),Ce=E.style.order.indexOf(j.fqid);if(pe&&function(je,Me,qe,$e,nt){for(const rt of $e){const pt=Me.getTile(rt).getBucket(qe);pt&&(pt.updateReplacement(rt,je.replacementSource,nt),pt.uploadCentroid(je.context))}}(E,p,j,L,Ce),Y||pe)for(const je of L){const Me=p.getTile(je).getBucket(j);Me&&Ez(E.context,p,je,Me,j,Y,pe)}if(E.renderPass==="shadow"&&E.shadowRenderer){if(Y&&O<.65&&j._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const je=E.shadowRenderer.getShadowPassDepthMode();c1(E,p,j,L,je,Mn.disabled,Tn.disabled,pe)}else if(E.renderPass==="translucent"){const je=!j.paint.get("fill-extrusion-pattern").constantOr(1),Me=j.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!te&&Me.a!==0){const qe=new $r(E.context.gl.LEQUAL,$r.ReadWrite,E.depthRangeFor3D);O===1&&je?c1(E,p,j,L,qe,Mn.disabled,Tn.unblended,pe):(c1(E,p,j,L,qe,Mn.disabled,Tn.disabled,pe),c1(E,p,j,L,qe,E.stencilModeFor3D(),E.colorModeForRenderPass(),pe),E.resetStencilClippingMasks())}if(E.style.enable3dLights()&&je&&(!Y&&E.transform.projection.name!=="globe"||te)){const qe=j.paint.get("fill-extrusion-opacity"),$e=j.paint.get("fill-extrusion-ambient-occlusion-intensity"),nt=j.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),rt=j.paint.get("fill-extrusion-flood-light-intensity"),pt=j.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",vt=j.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(pt?null:j.lut).toArray01().slice(0,3),ot=$e>0&&nt>0,Ut=rt>0,Tt=(St,Rt,Zt)=>(1-Zt)*St+Zt*Rt,$t=new lP;$t.translate=j.paint.get("fill-extrusion-translate"),$t.translateAnchor=j.paint.get("fill-extrusion-translate-anchor"),$t.edgeRadius=j.layout.get("fill-extrusion-edge-radius"),$t.cutoffFadeRange=j.paint.get("fill-extrusion-cutoff-fade-range");const _t=St=>{const Rt=E.depthModeForSublayer(1,$r.ReadOnly,H.LEQUAL,!0),Zt=j.paint.get(St?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),qt=Tt(.1,3,Zt),xs=E._showOverdrawInspector;if(!xs){const as=new Mn({func:H.ALWAYS,mask:255},255,255,H.KEEP,H.KEEP,H.REPLACE),Os=new Tn([H.ONE,H.ONE,H.ONE,H.ONE],o.aq.transparent,[!1,!1,!1,!0],H.MIN);_x($t,E,p,j,L,Rt,as,Os,vn.disabled,St,"sdf",qe,$e,nt,rt,vt,qt,pe,!1)}{const as=xs?Mn.disabled:new Mn({func:H.EQUAL,mask:255},255,255,H.KEEP,H.DECR,H.DECR),Os=xs?E.colorModeForRenderPass():new Tn([H.ONE_MINUS_DST_ALPHA,H.DST_ALPHA,H.ONE,H.ONE],o.aq.transparent,[!0,!0,!0,!0]);_x($t,E,p,j,L,Rt,as,Os,vn.disabled,St,"color",qe,$e,nt,rt,vt,qt,pe,!1)}};if(te){const St=()=>{const Zt=Y.drapeBufferSize[0],qt=Y.drapeBufferSize[1];let xs=Y.framebufferCopyTexture;return xs&&(!xs||xs.size[0]===Zt&&xs.size[1]===qt)||(xs&&xs.destroy(),xs=Y.framebufferCopyTexture=new o.T(q,new o.q({width:Zt,height:qt}),H.RGBA8)),xs.bind(H.LINEAR,H.CLAMP_TO_EDGE),H.copyTexSubImage2D(H.TEXTURE_2D,0,0,0,0,0,Zt,qt),xs},Rt=(Zt,qt,xs)=>{const as=E.depthModeForSublayer(1,$r.ReadOnly,H.LEQUAL,!1),Os=j.paint.get(Zt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Hs=Tt(.1,3,Os);{const Qt=new Tn([H.ONE,H.ONE,H.ONE,H.ONE],o.aq.transparent,[!1,!1,!1,!0]);_x($t,E,p,j,L,as,Mn.disabled,Qt,vn.disabled,Zt,"clear",qe,$e,nt,rt,vt,Hs,pe,qt)}{const Qt=new Mn({func:H.ALWAYS,mask:255},255,255,H.KEEP,H.KEEP,H.REPLACE),Ht=new Tn([H.ONE,H.ONE,H.ONE,H.ONE],o.aq.transparent,[!1,!1,!1,!0],H.MIN);_x($t,E,p,j,L,as,Qt,Ht,vn.disabled,Zt,"sdf",qe,$e,nt,rt,vt,Hs,pe,qt)}de&&!Zt&&(xs=St());{const Qt=Zt?H.ZERO:H.ONE_MINUS_DST_ALPHA,Ht=new Mn({func:H.EQUAL,mask:255},255,255,H.KEEP,H.DECR,H.DECR),us=new Tn([Qt,H.DST_ALPHA,H.ONE_MINUS_DST_ALPHA,H.ZERO],o.aq.transparent,[!0,!0,!0,!0]);_x($t,E,p,j,L,as,Ht,us,vn.disabled,Zt,"color",qe,$e,nt,rt,vt,Hs,pe,qt)}if(!de||Zt){const Qt=new Tn([H.ONE,H.ONE,H.ONE,Zt?H.ZERO:H.ONE],o.aq.transparent,[!1,!1,!1,!0],Zt?H.FUNC_ADD:H.MAX);_x($t,E,p,j,L,as,Mn.disabled,Qt,vn.disabled,Zt,"clear",qe,$e,nt,rt,vt,Hs,pe,qt,xs)}else{H.drawBuffers([H.NONE,H.COLOR_ATTACHMENT1]);const Qt=new Mn({func:H.EQUAL,mask:255},254,255,H.KEEP,H.DECR,H.DECR),Ht=new Tn([H.ONE,H.ONE,H.ONE,H.ONE],o.aq.transparent,[!0,!1,!1,!1],H.MAX);_x($t,E,p,j,L,as,Qt,Ht,vn.disabled,Zt,"emissive",qe,$e,nt,rt,vt,Hs,pe,qt,xs),H.drawBuffers([H.COLOR_ATTACHMENT0])}};if(ot||Ut){let Zt;E.prepareDrawTile(),de&&!ot||(Zt=St()),ot&&Rt(!0,!1,Zt),Ut&&Rt(!1,!0,Zt)}}else ot&&_t(!0),Ut&&_t(!1),(ot||Ut)&&E.resetStencilClippingMasks()}}},building:function(E,p,j,L){E.currentLayer0&&q>0,de=!0;const pe=j.paint.get("building-vertical-scale");if(pe<=0)return;E.shadowRenderer||(de=!1);const Ce=E.conflationActive&&E.style.isLayerClipped(j,p.getSource()),je=E.style.order.indexOf(j.fqid);if(function(Me,qe,$e,nt,rt,pt){for(const vt of pt){const ot=qe.getTile(vt).getBucket($e);ot&&(rt&&ot.updateReplacement(vt,Me.replacementSource,nt),ot.uploadUpdatedIndexBuffer(Me.context))}}(E,p,j,je,Ce,L),function(Me,qe,$e,nt){for(const rt of nt){const pt=qe.getTile(rt).getBucket($e);pt&&pt.needsEvaluation()&&pt.uploadUpdatedColorBuffer(Me.context)}}(E,p,j,L),j.resetLayerRenderingStats(E),E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!0),E.renderPass==="shadow"&&E.shadowRenderer){const Me=[],qe=E.shadowRenderer.getShadowPassDepthMode();G2({painter:E,source:p,layer:j,coords:L,defines:Me,blendMode:Tn.disabled,depthMode:qe,opacity:Y,verticalScale:pe,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(E.renderPass==="translucent"){let Me=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];de&&(Me=Me.concat("RENDER_SHADOWS")),E.shadowRenderer&&E.shadowRenderer.useNormalOffset&&(Me=Me.concat("NORMAL_OFFSET"));const qe=j.paint.get("building-facade-emissive-chance"),$e=j.paint.get("building-ambient-occlusion-intensity"),nt=j.paint.get("building-flood-light-intensity"),rt=j.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",pt=j.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(rt?null:j.lut).toArray01().slice(0,3),vt=j.paint.get("building-flood-light-ground-attenuation"),ot=nt>0,Ut=new $r(E.context.gl.LEQUAL,$r.ReadWrite,E.depthRangeFor3D);Y<1&&G2({painter:E,source:p,layer:j,coords:L,defines:Me,blendMode:Tn.disabled,depthMode:Ut,opacity:Y,verticalScale:pe,facadeEmissiveChance:qe,facadeAOIntensity:$e,floodLightIntensity:nt,floodLightColor:pt,depthOnly:!0});const Tt=E.colorModeForRenderPass();G2({painter:E,source:p,layer:j,coords:L,defines:Me,blendMode:Tt,depthMode:Ut,opacity:Y,verticalScale:pe,facadeEmissiveChance:qe,facadeAOIntensity:$e,floodLightIntensity:nt,floodLightColor:pt});const $t=j.paint.get("building-front-cutoff");W5(E.transform.pitch,$t,!!E.terrain),te&&dP(E,p,j,L,!0,Y,O,q,nt,pt,H,Ce),ot&&dP(E,p,j,L,!1,Y,O,q,nt,pt,vt,Ce)}else if(E.renderPass==="light-beam"){const Me=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],qe=new $r(E.context.gl.LEQUAL,$r.ReadOnly,E.depthRangeFor3D);G2({painter:E,source:p,layer:j,coords:L,defines:Me,blendMode:Tn.alphaBlended,depthMode:qe,opacity:Y,verticalScale:pe,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}E.shadowRenderer&&(E.shadowRenderer.useNormalOffset=!1),E.resetStencilClippingMasks()},hillshade:function(E,p,j,L){if(E.renderPass!=="offscreen"&&E.renderPass!=="translucent"||E.style.disableElevatedTerrain)return;const O=E.context,q=E.terrain&&E.terrain.renderingToTexture,[H,Y]=E.renderPass!=="translucent"||q?[{},L]:E.stencilConfigForOverlap(L);for(const te of Y){const de=p.getTile(te);if(de.needsHillshadePrepare&&E.renderPass==="offscreen")lge(E,de,j);else if(E.renderPass==="translucent"){const pe=E.depthModeForSublayer(0,$r.ReadOnly),Ce=j.paint.get("hillshade-emissive-strength"),je=E.colorModeForDrapableLayerRenderPass(Ce),Me=q&&E.terrain?E.terrain.stencilModeForRTTOverlap(te):H[te.overscaledZ];oge(E,te,de,j,pe,Me,je)}}O.viewport.set([0,0,E.width,E.height]),E.resetStencilClippingMasks()},raster:function(E,p,j,L,O,q){if(E.renderPass!=="translucent")return;const H=j.paint.get("raster-opacity");if(H===0)return;const Y=E.transform.projection.name==="globe",te=j.paint.get("raster-elevation")!==0,de=te&&Y,pe=E.terrain&&E.terrain.exaggeration()>0&&te&&j.paint.get("raster-elevation-reference")==="ground",Ce=!Y&&pe;if(E.renderElevatedRasterBackface&&!de)return;const je=E.context,Me=je.gl,qe=p.getSource(),$e=function(St,Rt,Zt,qt,xs){const as=Rt.paint.get("raster-color"),Os=St.type==="raster-array",Hs=[],Qt=Rt.paint.get("raster-resampling"),Ht=Rt.paint.get("raster-color-mix");let us=Rt.paint.get("raster-color-range");const vs=[Ht[0],Ht[1],Ht[2],0],ks=Ht[3];let cr=Qt==="nearest"?qt.NEAREST:qt.LINEAR;if(Os&&(Hs.push("RASTER_ARRAY"),as||Hs.push("RASTER_COLOR"),Qt==="linear"&&Hs.push("RASTER_ARRAY_LINEAR"),cr=qt.NEAREST,!us&&St.rasterLayers)){const Js=St.rasterLayers.find(({id:er})=>er===Rt.sourceLayer);Js&&Js.fields&&Js.fields.range&&(us=Js.fields.range)}if(us=us||[0,1],as){Hs.push("RASTER_COLOR"),Zt.activeTexture.set(qt.TEXTURE2),Rt.updateColorRamp(us);let Js=Rt.colorRampTexture;Js||(Js=Rt.colorRampTexture=new o.T(Zt,Rt.colorRamp,qt.RGBA8)),Js.bind(cr,qt.CLAMP_TO_EDGE)}return xs&&Hs.push("USE_MRT1"),{mix:vs,range:us,offset:ks,defines:Hs,resampling:cr}}(qe,j,je,Me,E.terrain&&E.terrain.renderingToTexture&&E.emissiveMode==="mrt-fallback");if(qe instanceof o.aV&&!L.length&&!Y)return;const nt=j.paint.get("raster-emissive-strength"),rt=E.colorModeForDrapableLayerRenderPass(nt),pt=E.terrain&&E.terrain.renderingToTexture,vt=!E.options.moving,ot=j.paint.get("raster-resampling")==="nearest"?Me.NEAREST:Me.LINEAR;if(qe instanceof o.aV&&!L.length&&(qe.onNorthPole||qe.onSouthPole)){const St=te?E.stencilModeFor3D():Mn.disabled;return void Y5(!!qe.onNorthPole,null,E,p,j,nt,$e,vn.disabled,St)}if(!L.length)return;const[Ut,Tt]=qe instanceof o.aV||pt?[{},L]:E.stencilConfigForOverlap(L),$t=Tt[Tt.length-1].overscaledZ;de&&$e.defines.push("PROJECTION_GLOBE_VIEW"),te&&$e.defines.push("RENDER_CUTOFF","ELEVATED"),pe&&$e.defines.push("ELEVATION_REFERENCE_GROUND");const _t=(St,Rt,Zt)=>{for(const qt of St){const xs=qt.toUnwrapped(),as=p.getTile(qt);if(pt&&(!as||!as.hasData()))continue;je.activeTexture.set(Me.TEXTURE0);const Os=Iz(as,qe,j,$e);if(!Os||!Os.texture)continue;const{texture:Hs,mix:Qt,offset:Ht,tileSize:us,buffer:vs}=Os;let ks,cr;pt?(ks=$r.disabled,cr=qt.projMatrix):te?(ks=new $r(Me.LEQUAL,$r.ReadWrite,E.depthRangeFor3D),cr=Y?Float32Array.from(E.transform.expandedFarZProjMatrix):E.transform.calculateProjMatrix(xs,vt)):(ks=E.depthModeForSublayer(qt.overscaledZ-$t,H===1?$r.ReadWrite:$r.ReadOnly,Me.LESS),cr=E.transform.calculateProjMatrix(xs,vt));const Js=E.terrain&&pt?E.terrain.stencilModeForRTTOverlap(qt):Ut[qt.overscaledZ],er=q?0:j.paint.get("raster-fade-duration");as.registerFadeDuration(er);const Us=p.findLoadedParent(qt,0),Br=O2(as,Us,p,E.transform,er);let Kr,Er;!Br.isFading&&as.refreshedUponExpiration&&(as.refreshedUponExpiration=!1),E.terrain&&E.terrain.prepareDrawTile(),je.activeTexture.set(Me.TEXTURE0),Hs.bind(ot,Me.CLAMP_TO_EDGE),je.activeTexture.set(Me.TEXTURE1),Us?(Us.texture&&Us.texture.bind(ot,Me.CLAMP_TO_EDGE),Kr=Math.pow(2,Us.tileID.overscaledZ-as.tileID.overscaledZ),Er=[as.tileID.canonical.x*Kr%1,as.tileID.canonical.y*Kr%1]):Hs.bind(ot,Me.CLAMP_TO_EDGE),"useMipmap"in Hs&&je.extTextureFilterAnisotropic&&E.transform.pitch>20&&Me.texParameterf(Me.TEXTURE_2D,je.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,je.extTextureFilterAnisotropicMax);const Fr=E.transform;let _n;const Fn=te?hP(Fr):[0,0,0,0];let Pn,oa,pn,la,Dn,Wa=0;if(de&&qe instanceof o.aV&&qe.coordinates.length>3)Pn=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),oa=Float32Array.from(Fr.globeMatrix),pn=Float32Array.from(o.dq(Fr)),la=[o.aH(Fr.center.lng),o.aL(Fr.center.lat)],_n=qe.elevatedGlobePerspectiveTransform,Dn=qe.elevatedGlobeGridMatrix||new Float32Array(9);else if(de){const ri=o.dr(qt.canonical);Wa=o.ds(ri.getCenter().lat),Pn=Float32Array.from(o.du(o.dv(qt.canonical))),oa=Float32Array.from(Fr.globeMatrix),pn=Float32Array.from(o.dq(Fr)),la=[o.aH(Fr.center.lng),o.aL(Fr.center.lat)],_n=[0,0],Dn=Float32Array.from(o.dt(qt.canonical,ri,Wa,Fr.worldSize/Fr._pixelsPerMercatorPixel))}else _n=qe instanceof o.aV?qe.perspectiveTransform:[0,0],Pn=new Float32Array(16),oa=new Float32Array(9),pn=new Float32Array(16),la=[0,0],Dn=new Float32Array(9);const Ti=jz(E,cr,Pn,oa,pn,Dn,Er||[0,0],o.al(E.transform.zoom),la,Fn,Kr||1,Br,j,_n,te?j.paint.get("raster-elevation"):0,2,Qt,Ht,$e.range,us,vs,nt),yo=E.isTileAffectedByFog(qt),zi=E.getOrCreateProgram("raster",{defines:$e.defines,overrideFog:yo});if(E.uploadCommonUniforms(je,zi,xs),qe instanceof o.aV){const ri=qe.elevatedGlobeVertexBuffer,Jn=qe.elevatedGlobeIndexBuffer;if(pt||!Y)qe.boundsBuffer&&qe.boundsSegments&&zi.draw(E,Me.TRIANGLES,ks,Mn.disabled,rt,vn.disabled,Ti,j.id,qe.boundsBuffer,E.quadTriangleIndexBuffer,qe.boundsSegments);else if(ri&&Jn){const ea=Fr.zoom<=o.cJ?qe.elevatedGlobeSegments:qe.getSegmentsForLongitude(Fr.center.lng);ea&&zi.draw(E,Me.TRIANGLES,ks,Mn.disabled,rt,Rt,Ti,j.id,ri,Jn,ea)}}else if(de){ks=new $r(Me.LEQUAL,$r.ReadOnly,E.depthRangeFor3D);const ri=E.globeSharedBuffers;if(ri){pe&&(E.terrain.setupElevationDraw(as,zi),E.uploadCommonUniforms(je,zi,as.tileID.toUnwrapped()));const[Jn,ea,$i]=ri.getGridBuffers(Wa,!1),No=zi.getAttributeLocation(Me,"a_texture_pos");No!==-1&&Me.vertexAttribI4ui(No,0,0,0,0),zi.draw(E,Me.TRIANGLES,ks,Zt||Js,E.colorModeForRenderPass(),Rt,Ti,j.id,Jn,ea,$i)}}else if(Ce)ks=new $r(Me.LEQUAL,$r.ReadWrite,E.depthRangeFor3D),E.terrain.setupElevationDraw(as,zi),E.uploadCommonUniforms(je,zi,as.tileID.toUnwrapped()),Fr.pitch>20&&zi.draw(E,Me.TRIANGLES,ks,Mn.disabled,Tn.disabled,vn.frontCCW,Ti,j.id,E.terrain.gridBuffer,E.terrain.gridIndexBuffer,E.terrain.gridSegments),zi.draw(E,Me.TRIANGLES,ks,Js,rt,vn.backCCW,Ti,j.id,E.terrain.gridBuffer,E.terrain.gridIndexBuffer,E.terrain.gridSegments);else{const{tileBoundsBuffer:ri,tileBoundsIndexBuffer:Jn,tileBoundsSegments:ea}=E.getTileBoundsBuffers(as);zi.draw(E,Me.TRIANGLES,ks,Js,rt,vn.disabled,Ti,j.id,ri,Jn,ea)}}if(!(qe instanceof o.aV)&&de)for(const qt of St){const xs=qt.canonical.y===(1<o.d$[vs](xs));Qt.push(xs);const Ht=xs.canonical.x,us=xs.canonical.y;for(const vs of Qt){const ks=ot.getTile(Rt?vs.wrapped():vs);if(!ks)continue;const cr=ks.rasterParticleState;if(!cr)continue;const Js=vs.canonical.x+(1<$t.tileID)),Me&&(de.activeTexture.set(pe.TEXTURE0),E.imageManager.bind(E.context,j.scope));const Tt=[];if(E.terrain&&E.terrain.renderingToTexture&&E.emissiveMode==="mrt-fallback"&&Tt.push("USE_MRT1"),te){const $t=E.getOrCreateProgram(vt,{overrideFog:!1,overrideRtt:!0,defines:Tt}),_t=new Float32Array(o.b9([])),St=new o.aR(0,0,0,0,0),Rt=Me?n0(_t,Y,H,E,0,j.scope,qe,te,{tileID:St,tileSize:je}):$2(_t,Y,H,O.toPremultipliedRenderColor(q?null:j.lut));return void $t.draw(E,pe.TRIANGLES,rt,nt,pt,vn.disabled,Rt,j.id,E.viewportBuffer,E.quadTriangleIndexBuffer,E.viewportSegments)}for(const $t of Ut){const _t=E.isTileAffectedByFog($t),St=E.getOrCreateProgram(vt,{overrideFog:_t,defines:Tt}),Rt=$t.toUnwrapped(),Zt=L?$t.projMatrix:E.transform.calculateProjMatrix(Rt);E.prepareDrawTile();const qt=p?p.getTile($t):ot?ot[$t.key]:new o.b0($t,je,Ce.zoom,E),xs=Me?n0(Zt,Y,H,E,0,j.scope,qe,te,{tileID:$t,tileSize:je}):$2(Zt,Y,H,O.toPremultipliedRenderColor(q?null:j.lut));E.uploadCommonUniforms(de,St,Rt);const{tileBoundsBuffer:as,tileBoundsIndexBuffer:Os,tileBoundsSegments:Hs}=E.getTileBoundsBuffers(qt);St.draw(E,pe.TRIANGLES,rt,nt,pt,vn.disabled,xs,j.id,as,Os,Hs)}},sky:function(E,p,j){const L=E._atmosphere?o.al(E.transform.zoom):1,O=j.paint.get("sky-opacity")*L;if(O===0)return;const q=E.context,H=j.paint.get("sky-type"),Y=new $r(q.gl.LEQUAL,$r.ReadOnly,[0,1]),te=E.frameCounter/1e3%1;H==="atmosphere"?E.renderPass==="offscreen"?j.needsSkyboxCapture(E)&&(function(de,pe){const Ce=de.context,je=Ce.gl;let Me=pe.skyboxFbo;if(!Me){Me=pe.skyboxFbo=Ce.createFramebuffer(32,32,1,null),pe.skyboxGeometry=new Cu(Ce),pe.skyboxTexture=Ce.gl.createTexture(),je.bindTexture(je.TEXTURE_CUBE_MAP,pe.skyboxTexture),je.texParameteri(je.TEXTURE_CUBE_MAP,je.TEXTURE_WRAP_S,je.CLAMP_TO_EDGE),je.texParameteri(je.TEXTURE_CUBE_MAP,je.TEXTURE_WRAP_T,je.CLAMP_TO_EDGE),je.texParameteri(je.TEXTURE_CUBE_MAP,je.TEXTURE_MIN_FILTER,je.LINEAR),je.texParameteri(je.TEXTURE_CUBE_MAP,je.TEXTURE_MAG_FILTER,je.LINEAR);for(let rt=0;rt<6;++rt)je.texImage2D(je.TEXTURE_CUBE_MAP_POSITIVE_X+rt,0,je.RGBA,32,32,0,je.RGBA,je.UNSIGNED_BYTE,null)}Ce.bindFramebuffer.set(Me.framebuffer),Ce.viewport.set([0,0,32,32]);const qe=pe.getCenter(de,!0),$e=de.getOrCreateProgram("skyboxCapture"),nt=new Float64Array(16);o.b9(nt),o.ef(nt,nt,.5*-Math.PI),Fm(de,pe,$e,nt,qe,0),o.b9(nt),o.ef(nt,nt,.5*Math.PI),Fm(de,pe,$e,nt,qe,1),o.b9(nt),o.cE(nt,nt,.5*-Math.PI),Fm(de,pe,$e,nt,qe,2),o.b9(nt),o.cE(nt,nt,.5*Math.PI),Fm(de,pe,$e,nt,qe,3),o.b9(nt),Fm(de,pe,$e,nt,qe,4),o.b9(nt),o.ef(nt,nt,Math.PI),Fm(de,pe,$e,nt,qe,5),Ce.viewport.set([0,0,de.width,de.height])}(E,j),j.markSkyboxValid(E)):E.renderPass==="sky"&&function(de,pe,Ce,je,Me){const qe=de.context,$e=qe.gl,nt=de.transform,rt=de.getOrCreateProgram("skybox");qe.activeTexture.set($e.TEXTURE0),$e.bindTexture($e.TEXTURE_CUBE_MAP,pe.skyboxTexture);const pt=((vt,ot,Ut,Tt,$t)=>({u_matrix:vt,u_sun_direction:ot,u_cubemap:0,u_opacity:Tt,u_temporal_offset:$t}))(nt.skyboxMatrix,pe.getCenter(de,!1),0,je,Me);de.uploadCommonUniforms(qe,rt),rt.draw(de,$e.TRIANGLES,Ce,Mn.disabled,de.colorModeForRenderPass(),vn.backCW,pt,"skybox",pe.skyboxGeometry.vertexBuffer,pe.skyboxGeometry.indexBuffer,pe.skyboxGeometry.segment)}(E,j,Y,O,te):H==="gradient"&&E.renderPass==="sky"&&function(de,pe,Ce,je,Me){const qe=de.context,$e=qe.gl,nt=de.transform,rt=de.getOrCreateProgram("skyboxGradient");pe.skyboxGeometry||(pe.skyboxGeometry=new Cu(qe)),qe.activeTexture.set($e.TEXTURE0);let pt=pe.colorRampTexture;pt||(pt=pe.colorRampTexture=new o.T(qe,pe.colorRamp,$e.RGBA8)),pt.bind($e.LINEAR,$e.CLAMP_TO_EDGE);const vt=((ot,Ut,Tt,$t,_t)=>({u_matrix:ot,u_color_ramp:0,u_center_direction:Ut,u_radius:o.ap(Tt),u_opacity:$t,u_temporal_offset:_t}))(nt.skyboxMatrix,pe.getCenter(de,!1),pe.paint.get("sky-gradient-radius"),je,Me);de.uploadCommonUniforms(qe,rt),rt.draw(de,$e.TRIANGLES,Ce,Mn.disabled,de.colorModeForRenderPass(),vn.backCW,vt,"skyboxGradient",pe.skyboxGeometry.vertexBuffer,pe.skyboxGeometry.indexBuffer,pe.skyboxGeometry.segment)}(E,j,Y,O,te)},custom:function(E,p,j,L){const O=E.context,q=j.implementation;if(!E.transform.projection.unsupportedLayers||!E.transform.projection.unsupportedLayers.includes("custom")||E.terrain&&(E.terrain.renderingToTexture||E.renderPass==="offscreen")&&j.isDraped(p)){if(E.renderPass==="offscreen"){const H=q.prerender;if(H){if(E.setCustomLayerDefaults(),O.setColorMode(E.colorModeForRenderPass()),E.transform.projection.name==="globe"){const Y=E.transform.pointMerc;H.call(q,O.gl,E.transform.customLayerMatrix(),E.transform.getProjection(),E.transform.globeToMercatorMatrix(),o.al(E.transform.zoom),[Y.x,Y.y],E.transform.pixelsPerMeterRatio)}else H.call(q,O.gl,E.transform.customLayerMatrix());O.setDirty(),E.setBaseState()}}else if(E.renderPass==="translucent"){if(E.terrain&&E.terrain.renderingToTexture){const Y=q.renderToTile;if(Y){const te=L[0].canonical,de={x:te.x+L[0].wrap*(q.wrapTileId?0:1<{de&&(de.useNormalOffset=!0,pe||(de.enabled=!0))},je=p.getSource();if(E.renderPass==="light-beam"&&je.type!=="batched-model")return;if(je.type==="vector"||je.type==="geojson")return function(ot,Ut,Tt,$t,_t){const St=ot.transform,Rt=St.projection.name==="globe",Zt=St.getFreeCameraOptions().position;if(!ot.modelManager)return;const qt=ot.modelManager;Tt.modelManager=qt;const xs=ot.shadowRenderer;if(!Tt._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const as=Tt._unevaluatedLayout._values["model-id"],Os=Object.assign({},Tt.layout.get("model-id").parameters),Hs=ot.style.order.indexOf(Tt.fqid),Qt=Tt.paint.get("model-opacity").constantOr(1);for(const Ht of $t){const us=Ut.getTile(Ht).getBucket(Tt);if(!us||us.projection.name!==St.projection.name)continue;const vs=us.getModelUris();if(vs&&!us.modelsRequested&&(qt.addModelsFromBucket(vs,_t),us.modelsRequested=!0),Rt)Os.zoom=Ht.overscaledZ;else{const Er=g_(Ht,St);Os.zoom=Er}const ks=as.possiblyEvaluate(Os);if(nr(ot,us,Ht),Qs.shadowUniformsInitialized=!1,Qs.useSingleShadowCascade=!!xs&&xs.getMaxCascadeForTile(Ht.toUnwrapped())===0,ot.renderPass==="shadow"&&xs){if(ot.currentShadowCascade===1&&us.isInsideFirstShadowMapFrustum)continue;const Er=St.calculatePosMatrix(Ht.toUnwrapped(),St.worldSize);if(Qs.tileMatrix.set(Er),Qs.shadowTileMatrix=Float32Array.from(xs.calculateShadowPassMatrixFromMatrix(Er)),Qs.aabb.min=[0,0,0],Qs.aabb.max[0]=Qs.aabb.max[1]=o.an,Qs.aabb.max[2]=0,Bz(us,Qs,ot,Tt.scope))continue}const cr=1<0&&ot.style.isLayerClipped(Tt,Ut.getSource())&&us.updateReplacement(Ht,ot.replacementSource,Hs,Tt.scope)&&(us.uploaded=!1,us.upload(ot.context));let er=0;const Us=new Array,Br=new Array,Kr=new Array;for(let Er in us.instancesPerModel){const Fr=us.instancesPerModel[Er];Fr.features.length>0&&!Rt&&(Er=ks.evaluate(Fr.features[0].feature,{}));const _n=qt.getModel(Er,_t);if(_n||qt.hasURLBeenRequested(Er)||us.modelUris.includes(Er)||(us.modelUris.push(Er),us.modelsRequested=!1),_n&&_n.uploaded)if(Rt){const Fn=o.bJ([],[Zt.x,Zt.y,Zt.z],ot.transform.worldSize);o.eo(Fn,Fn);for(let Pn=0;Pn0&&la.elevationUpdate(Er.terrain,Pn,pn,_n.source),la.needsReEvaluation(Er,oa,_n)&&la.evaluate(_n))}})(ot,Ut,Tt,$t),function(){const Er=new Map;let Fr,_n,Fn;Us?(Fr=$t.length-1,_n=-1,Fn=-1):(Fr=0,_n=$t.length,Fn=1);const Pn=new Float64Array(16),oa=o.ce(),pn=new o.P(0,0);for(let la=Fr;la!==_n;la+=Fn){const Dn=$t[la],Wa=Ut.getTile(Dn).getBucket(Tt);if(!Wa||!Wa.uploaded)continue;let Ti=!1;Zt&&(Ti=Zt.getMaxCascadeForTile(Dn.toUnwrapped())===0);const yo=St.calculatePosMatrix(Dn.toUnwrapped(),St.worldSize),zi=Wa.modelTraits;!cr&&Us&&(o.b7(Pn,yo),o.ah(oa,xs,Pn),pn.x=oa[0],pn.y=oa[1]);const ri=[];Wa.setFilter(Tt.filter);for(const Jn of Wa.getNodesInfo()){if(Jn.hiddenByReplacement||!Jn.node.meshes)continue;const ea=Jn.node;let $i=0;ot.terrain&&ea.elevation&&($i=ea.elevation*ot.terrain.exaggeration());const No=(()=>{const Yc=Jn.aabb;return ks.min=[...Yc.min],ks.max=[...Yc.max],ks.min[2]+=$i,ks.max[2]+=$i,o.ah(ks.min,ks.min,yo),o.ah(ks.max,ks.max,yo),ks})(),ni=Jn.evaluatedScale;if(ni[0]<=1&&ni[1]<=1&&ni[2]<=1&&No.intersects(Js)===0)continue;if(!cr&&Us){const Yc=.16666666666666666;Jn.cameraCollisionOpacity=xs[0]>No.min[0]&&xs[0]No.min[1]&&xs[1]!Us||Jn.opacity===1&&ea.opacity===1?Jn.depthea.depth?-1:1);for(const Jn of ri){const ea=Jn.nodeInfo,$i=ea.node;if(ot._debugParams.show3DModelFootprints&&$i.footprint){const _a=$i.id||$i.name||"footprint";Er.has(_a)||Er.set(_a,{node:$i,mvp:Jn.wvpForTile})}let No=o.aD([],Qt,Jn.tileModelMatrix);o.aD(No,Os,No);const ni=o.b7([],No);o.e6(ni,ni),o.cC(ni,ni,Yt),No=o.aD(No,No,$i.globalMatrix);const qn=ot.renderPass==="light-beam",uo=Tt.paint.get("model-color-use-theme").constantOr("default")==="none",Ei=zi&o.ez.HasMapboxMeshFeatures,jl=Ei?0:ea.evaluatedRMEA[0][2];for(let _a=0;_a<$i.meshes.length;++_a){const Ri=$i.meshes[_a],Ul=_a===$i.lightMeshIndex;let Ud=Jn.wvpForNode;if(Ul){if(!qn&&!ot.terrain&&ot.shadowRenderer){ot.currentLayer=un||cm>=un}}const fi=Ri.material;let $m;fi.occlusionTexture&&fi.occlusionTexture.offsetScale&&($m=fi.occlusionTexture.offsetScale,rc.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Um=ot.getOrCreateProgram("model",rc);!cr&&Zt&&Zt.setupShadowsFromMatrix(Jn.tileModelMatrix,Um,Zt.useNormalOffset),ot.uploadCommonUniforms(_t,Um,null,lm);const qi=fi.pbrMetallicRoughness;qi.metallicFactor=.9,qi.roughnessFactor=.5;const Yi=o1(new Float32Array(Ud),new Float32Array(No),new Float32Array(ni),new Float32Array($i.globalMatrix),ot,Jn.opacity,qi.baseColorFactor,fi.emissiveFactor,qi.metallicFactor,qi.roughnessFactor,fi,jl,Tt,[0,0,0],$m);!Ul&&(ea.hasTranslucentParts||Jn.opacity<1)&&Um.draw(ot,_t.gl.TRIANGLES,us,Mn.disabled,Tn.disabled,vn.backCCW,Yi,Tt.id,Ri.vertexBuffer,Ri.indexBuffer,Ri.segments,Tt.paint,ot.transform.zoom,void 0,Yc),Um.draw(ot,_t.gl.TRIANGLES,Ul?vs:us,Mn.disabled,Ul||Jn.opacity<1||ea.hasTranslucentParts?Tn.alphaBlended:Tn.unblended,vn.backCCW,Yi,Tt.id,Ri.vertexBuffer,Ri.indexBuffer,Ri.segments,Tt.paint,ot.transform.zoom,void 0,Yc)}}}if(ot._debugParams.show3DModelFootprints&&Er.size>0){const la=Array.from(Er.keys()).sort();for(const Dn of la){const{node:Wa,mvp:Ti}=Er.get(Dn);wP(ot,0,Wa,Ti)}}}()}(E,p,j,L),void Ce();if(je.type!=="model")return;const Me=je.getModels(),qe=[],$e=E.transform.getFreeCameraOptions().position,nt=o.bJ([],[$e.x,$e.y,$e.z],E.transform.worldSize);o.eo(nt,nt);const rt=[],pt=[];let vt=0;for(const ot of Me){const Ut=p.getFeatureState("",ot.id),Tt={type:"Unknown",id:ot.id,properties:ot.featureProperties},$t=j.paint.get("model-rotation").evaluate(Tt,Ut),_t=j.paint.get("model-scale").evaluate(Tt,Ut),St=j.paint.get("model-translation").evaluate(Tt,Ut),Rt=j.paint.get("model-opacity").evaluate(Tt,Ut);jP(j,ot.id,Ut,ot.featureProperties,ot.nodeOverrideNames,ot.nodeOverrides),u1(j,ot.id,Ut,ot.featureProperties,ot.materialOverrideNames,ot.materialOverrides),ot.nodeOverrides.size>0&&ot.computeBoundsAndApplyParent(),ot.computeModelMatrix(E,$t,_t,St,Y,H,!1);const Zt=o.b9([]),qt=o.e2(ot.position.lat,E.transform.zoom),xs=o.bP([],[1,1,1/qt]);o.bx(Zt,Zt,nt),qe.push({zScaleMatrix:xs,negCameraPosMatrix:Zt});for(const as of ot.nodes)Q5(E,as,ot.matrix,E.transform.expandedFarZProjMatrix,vt,rt,pt,ot.materialOverrides,Rt);vt++}if(rt.sort((ot,Ut)=>Ut.depth-ot.depth),E.renderPass!=="shadow"){if(E._debugParams.show3DModelFootprints){const ot=E.transform.projMatrix,Ut=new Map,Tt=(_t,St)=>{if(_t.footprint){const Rt=_t.id||_t.name||"footprint";if(!Ut.has(Rt)){const Zt=o.aD([],ot,St);Ut.set(Rt,{node:_t,mvp:Zt})}}};for(const _t of pt)Tt(_t.node,_t.modelMatrix);for(const _t of rt)Tt(_t.node,_t.modelMatrix);const $t=Array.from(Ut.keys()).sort();for(const _t of $t){const{node:St,mvp:Rt}=Ut.get(_t);wP(E,0,St,Rt)}}Bg(E,j,rt,pt,qe),Ce()}else{for(const ot of pt)x_(ot.mesh,ot.nodeModelMatrix,E,j);for(const ot of rt)x_(ot.mesh,ot.nodeModelMatrix,E,j);Ce()}}},SP={line:function(E,p,j){if(E.hasElevatedBuckets=!1,E.hasNonElevatedBuckets=!1,E._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||E._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(p){const L=p.getVisibleCoordinates();for(const O of L){const q=p.getTile(O).getBucket(E);if(q&&(q.elevationType!=="none"?E.hasElevatedBuckets=!0:E.hasNonElevatedBuckets=!0,E.hasElevatedBuckets&&E.hasNonElevatedBuckets))break}}}else E.hasNonElevatedBuckets=!0},model:function(E,p,j){const L=p.getSource();if(!L.loaded())return;if(L.type==="vector"||L.type==="geojson")return void(j.modelManager&&j.modelManager.upload(j,X5(j,E)));if(L.type==="batched-model"||L.type!=="model")return;const O=L.getModels();for(const q of O)q.upload(j.context)},raster:function(E,p,j){const L=p.getSource();if(!(L instanceof Im&&L.loaded()))return;const O=E.sourceLayer||L.rasterLayerIds&&L.rasterLayerIds[0];if(!O)return;const q=E.paint.get("raster-array-band")||L.getInitialBand(O);if(q==null)return;const H=p.getIds().map(Y=>p.getTileByID(Y));for(const Y of H)Y.updateNeeded(E.id,q)&&L.prepareTile(Y,O,E.id,q)},"raster-particle":function(E,p,j){const L=p.getSource();if(!(L instanceof Im&&L.loaded()))return;const O=E.sourceLayer||L.rasterLayerIds&&L.rasterLayerIds[0];if(!O)return;const q=E.paint.get("raster-particle-array-band")||L.getInitialBand(O);if(q==null)return;const H=p.getIds().map(Y=>p.getTileByID(Y));for(const Y of H)Y.updateNeeded(E.id,q)&&L.prepareTile(Y,O,E.id,q)}},CP={fill:V2},TP={fill:function(E,p,j,L){if(!j.layout||j.layout.get("fill-elevation-reference")==="none"||j.paint.get("fill-opacity").constantOr(1)===0)return;const O=E.context.gl,q=new $r(O.LEQUAL,$r.ReadOnly,E.depthRangeFor3D),H=new Mn({func:O.ALWAYS,mask:255},255,255,O.KEEP,O.KEEP,O.REPLACE),Y=E.transform.getFreeCameraOptions().position,te=E.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const de of L){const pe=p.getTile(de),Ce=pe.getBucket(j);if(!Ce)continue;const je=Ce.elevatedStructures;if(!je||je.depthSegments.segments[0].primitiveLength===0)continue;const Me=oP(de.toUnwrapped(),Y),qe=E.translatePosMatrix(de.projMatrix,pe,j.paint.get("fill-translate"),j.paint.get("fill-translate-anchor")),$e=B2(qe,Me,0,1,0);te.draw(E,O.TRIANGLES,q,H,Tn.disabled,vn.disabled,$e,j.id,je.vertexBuffer,je.indexBuffer,je.depthSegments,j.paint,E.transform.zoom)}}};class kge{constructor(p,j,L,O,q){this.context=new f_(p,j),this.transform=L,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 H=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const te of H)this._debugParams.enabledLayers[te]=!0;for(const te of H);this.occlusionParams=new $z,this.setup(),this.numSublayers=ku.maxUnderzooming+ku.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 k2(this),this._wireframeDebugCache=new zz,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const Y=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,Y,p.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=O,this.maxFrontCutoffRawStart=0,this.worldview=q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(p,j){const L=!!p&&!!p.terrain&&this.transform.projection.supportsTerrain;if(!(L||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new F2(this,p));const O=this._terrain;this.transform.elevation=L?O:null,O.update(p,this.transform,j),this.transform.elevation&&!O.enabled&&(this.transform.elevation=null)}_updateFog(p){const j=p.fog;if(!j||this.transform.projection.name==="globe"||j.getOpacity(this.transform.pitch)<1||j.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[L,O]=j.getFovAdjustedRange(this.transform._fov);if(L>O)return void(this.transform.fogCullDistSq=null);const q=L+.78*(O-L);this.transform.fogCullDistSq=q*q}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(p){p&&!this._terrain&&(this._terrain=new F2(this,this.style)),this._forceTerrainMode=p}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(p,j){if(this.width=p*o.o.devicePixelRatio,this.height=j*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const L of this.style.order)this.style._mergedLayers[L].resize()}setup(){const p=this.context,j=new o.dB;j.emplaceBack(0,0),j.emplaceBack(o.an,0),j.emplaceBack(0,o.an),j.emplaceBack(o.an,o.an),this.tileExtentBuffer=p.createVertexBuffer(j,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const L=new o.dB;L.emplaceBack(0,0),L.emplaceBack(o.an,0),L.emplaceBack(0,o.an),L.emplaceBack(o.an,o.an),this.debugBuffer=p.createVertexBuffer(L,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const O=new o.dB;O.emplaceBack(-1,-1),O.emplaceBack(1,-1),O.emplaceBack(-1,1),O.emplaceBack(1,1),this.viewportBuffer=p.createVertexBuffer(O,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const q=new o.eH;q.emplaceBack(0,0,0,0),q.emplaceBack(o.an,0,o.an,0),q.emplaceBack(0,o.an,0,o.an),q.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=p.createVertexBuffer(q,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const H=new o.dC;H.emplaceBack(0,1,2),H.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=p.createIndexBuffer(H);const Y=new o.eJ;for(const de of[0,1,3,2,0])Y.emplaceBack(de);this.debugIndexBuffer=p.createIndexBuffer(Y),this.emptyTexture=new o.T(p,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),p.gl.RGBA8),this.identityMat=o.bb();const te=this.context.gl;this.stencilClearMode=new Mn({func:te.ALWAYS,mask:0},0,255,te.ZERO,te.ZERO,te.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(p){return p._makeTileBoundsBuffers(this.context,this.transform.projection),p._tileBoundsBuffer?{tileBoundsBuffer:p._tileBoundsBuffer,tileBoundsIndexBuffer:p._tileBoundsIndexBuffer,tileBoundsSegments:p._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const p=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,p.TRIANGLES,$r.disabled,this.stencilClearMode,Tn.disabled,vn.disabled,R2(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(p,j,L){if(!j||this.currentStencilSource===j.id||!p.isTileClipped()||!L||L.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let Y=!1;for(const te of L)if(this._tileClippingMaskIDs[te.key]===void 0){Y=!0;break}if(!Y)return}this.currentStencilSource=j.id;const O=this.context,q=O.gl;this.nextStencilID+L.length>256&&this.clearStencil(),O.setColorMode(Tn.disabled),O.setDepthMode($r.disabled);const H=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const Y of L){const te=j.getTile(Y),de=this._tileClippingMaskIDs[Y.key]=this.nextStencilID++,{tileBoundsBuffer:pe,tileBoundsIndexBuffer:Ce,tileBoundsSegments:je}=this.getTileBoundsBuffers(te);H.draw(this,q.TRIANGLES,$r.disabled,new Mn({func:q.ALWAYS,mask:0},de,255,q.KEEP,q.KEEP,q.REPLACE),Tn.disabled,vn.disabled,R2(Y.projMatrix),"$clipping",pe,Ce,je)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const p=this.nextStencilID++,j=this.context.gl;return new Mn({func:j.NOTEQUAL,mask:255},p,255,j.KEEP,j.KEEP,j.REPLACE)}stencilModeForClipping(p){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(p);const j=this.context.gl;return new Mn({func:j.EQUAL,mask:255},this._tileClippingMaskIDs[p.key],0,j.KEEP,j.KEEP,j.REPLACE)}stencilConfigForOverlap(p){const j=this.context.gl,L=p.sort((H,Y)=>Y.overscaledZ-H.overscaledZ),O=L[L.length-1].overscaledZ,q=L[0].overscaledZ-O+1;if(q>1){this.currentStencilSource=void 0,this.nextStencilID+q>256&&this.clearStencil();const H={};for(let Y=0;Ythis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((p,j)=>p+j/this._fpsHistory.length,0))}render(p,j){const L=o.o.now();this._dt=L-this._timeStamp,this._timeStamp=L,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=p.map.repaint,this.style=p,this.options=j;const O=this.style._mergedLayers,q=!(!this.terrain||!this.terrain.enabled),H=()=>this.style._getOrder(q).filter(Qt=>{const Ht=O[Qt];return!(Ht.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Ht.type]});let Y=H(),te=!1,de=!1,pe=null,Ce=0,je=!1;for(const Qt of Y){const Ht=O[Qt];Ht.visibility!=="none"&&(Ht.type==="circle"?te=!0:Ht.type==="building"?(pe=Ht,++Ce):Ht.type==="symbol"&&(Ht.hasOcclusionOpacityProperties?de=!0:te=!0))}this.updateEmissiveMode();let Me=Y.map(Qt=>O[Qt]);const qe=this.style._mergedSourceCaches;this.imageManager=p.imageManager,this.modelManager=p.modelManager,this.symbolFadeChange=p.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const Qt in qe){const Ht=qe[Qt];Ht.used&&(Ht.prepare(this.context),Ht.getSource().usedInConflation&&++Ce)}let $e=!1;for(const Qt of Me)Qt.isHidden(this.transform.zoom)||(Qt.type==="clip"&&($e=!0),this.prepareLayer(Qt));const nt={},rt={},pt={},vt={},ot={};for(const Qt in qe){const Ht=qe[Qt];nt[Qt]=Ht.getVisibleCoordinates(),rt[Qt]=nt[Qt].slice().reverse(),pt[Qt]=Ht.getVisibleCoordinates(!0).reverse(),vt[Qt]=Ht.getShadowCasterCoordinates(),ot[Qt]=Ht.sortCoordinatesByDistance(nt[Qt])}const Ut=Qt=>{const Ht=this.style.getLayerSourceCache(Qt);return Ht&&Ht.used?Ht.getSource():null};if(Ce||$e||this._clippingActiveLastFrame){const Qt=[],Ht=[];let us=0;for(const vs of Me)this.isSourceForClippingOrConflation(vs,Ut(vs))&&(Qt.push(vs),Ht.push(us)),us++;if(Qt&&($e||Qt.length>1)||this._clippingActiveLastFrame){$e=!1;const vs=[];for(let ks=0;ks0){const vs=Ut(Ht);vs&&(this.minCutoffZoom=Math.max(vs.minzoom,this.minCutoffZoom)),Ht.minzoom&&(this.minCutoffZoom=Math.max(Ht.minzoom,this.minCutoffZoom))}Ht.is3D(q)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=Qt),this._lastOcclusionLayer=Qt)}const Tt=this.style&&this.style.fog;Tt?(this._fogVisible=Tt.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Tt.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(pt),this.opaquePassCutoff=0,Y=H(),Me=Y.map(Qt=>O[Qt]));const $t=this._shadowRenderer;if($t){$t.updateShadowParameters(this.transform,this.style.directionalLight);for(const Qt in qe)for(const Ht of nt[Qt]){let us={min:0,max:0};this.terrain&&(us=this.terrain.getMinMaxForTile(Ht)||us),$t.addShadowReceiver(Ht.toUnwrapped(),us.min,us.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 Oz(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const _t=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),St=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(_t&&!this._snow&&(this._snow=new Vz(this)),!_t&&this._snow&&(this._snow.destroy(),delete this._snow),St&&!this._rain&&(this._rain=new K2(this)),!St&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),pe){this.buildingTileBorderManager||(this.buildingTileBorderManager=new Fg);const Qt=this.style.getLayerSourceCache(pe);this.buildingTileBorderManager.updateBorders(Qt,pe)}if(!Ye.has(this.context.gl))return;this.renderPass="offscreen";for(const Qt of Me){const Ht=p.getLayerSourceCache(Qt);if(!Qt.hasOffscreenPass()||Qt.isHidden(this.transform.zoom))continue;const us=Ht?rt[Ht.id]:void 0;(Qt.type==="custom"||Qt.type==="raster"||Qt.type==="raster-particle"||Qt.isSky()||us&&us.length)&&this.renderLayer(this,Ht,Qt,us)}this.depthRangeFor3D=[0,1-(Me.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,vt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Rt=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Zt=(()=>{if(j.showOverdrawInspector)return o.aq.black;const Qt=this.style.fog;if(Qt&&this.transform.projection.supportsFog){const Ht=this.style.getLut(Qt.scope);if(!Rt){const us=Qt.properties.get("color-use-theme")==="none",vs=Qt.properties.get("color").toNonPremultipliedRenderColor(us?null:Ht).toArray01();return new o.aq(...vs)}if(Rt){const us=Qt.properties.get("space-color-use-theme")==="none",vs=Qt.properties.get("space-color").toNonPremultipliedRenderColor(us?null:Ht).toArray01();return new o.aq(...vs)}}return o.aq.transparent})();if(this.context.clear({color:Zt,depth:1}),this.clearStencil(),this._showOverdrawInspector=j.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Rt&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=Y.length-1;this.currentLayer>=0;this.currentLayer--){const Qt=Me[this.currentLayer],Ht=p.getLayerSourceCache(Qt);if(Qt.isSky())continue;const us=Ht?(Qt.is3D(q)?ot:rt)[Ht.id]:void 0;this._renderTileClippingMasks(Qt,Ht,us),this.renderLayer(this,Ht,Qt,us)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Rt&&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 us=this.currentLayer;this.depthOcclusion=!0;for(const vs of this.layersWithOcclusionOpacity){this.currentLayer=vs;const ks=Me[this.currentLayer],cr=p.getLayerSourceCache(ks),Js=cr?rt[cr.id]:void 0;this.terrain||this._renderTileClippingMasks(ks,cr,cr?nt[cr.id]:void 0),this.renderLayer(this,cr,ks,Js)}this.depthOcclusion=!1,this.currentLayer=us,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 Qt=null;Me.forEach(Ht=>{const us=p.getLayerSourceCache(Ht);us&&!Ht.isHidden(this.transform.zoom)&&us.getVisibleCoordinates().length&&(!Qt||Qt.getSource().maxzoom0?j.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(p,j,L){const O=L===void 0?this.terrain&&this.terrain.renderingToTexture:L,q=[];return this.style&&this.style.enable3dLights()&&(p==="globeRaster"||p==="terrainRaster"?(q.push("LIGHTING_3D_MODE"),q.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):O||q.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(q.push("TERRAIN"),this.linearFloatFilteringSupported()&&q.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&q.push("GLOBE"),!this._fogVisible||O||j!==void 0&&!j||q.push("FOG"),O&&q.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&q.push("OVERDRAW_INSPECTOR"),q}getOrCreateProgram(p,j){this.cache=this.cache||{};const L=j&&j.defines||[],O=j&&j.config,q=this.currentGlobalDefines(p,j&&j.overrideFog,j&&j.overrideRtt).concat(L),H=i1.cacheKey(tz[p],p,q,O);return this.cache[H]||(this.cache[H]=new i1(this.context,p,tz[p],O,q5[p],q)),this.cache[H]}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 p=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(p.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(p,j){if(this.style.enable3dLights()){const L=this.style.directionalLight,O=this.style.ambientLight;if(L&&O){const q=((H,Y,te)=>{const de=H.properties.get("direction"),pe=H.properties.get("color-use-theme")==="none",Ce=H.properties.get("color").toNonPremultipliedRenderColor(pe?null:te.getLut(H.scope)).toArray01(),je=H.properties.get("intensity"),Me=Y.properties.get("color-use-theme")==="none",qe=Y.properties.get("color").toNonPremultipliedRenderColor(Me?null:te.getLut(Y.scope)).toArray01(),$e=Y.properties.get("intensity"),nt=[de.x,de.y,de.z],rt=o.dD(qe,$e),pt=o.dD(Ce,je);return{u_lighting_ambient_color:rt,u_lighting_directional_dir:nt,u_lighting_directional_color:pt,u_ground_radiance:sP(nt,pt,rt)}})(L,O,this.style);j.setLightsUniformValues(p,q)}}}uploadCommonUniforms(p,j,L,O,q){if(this.uploadCommonLightUniforms(p,j),this.terrain&&this.terrain.renderingToTexture)return;const H=this.style.fog;if(H){const Y=H.getOpacity(this.transform.pitch),te=((de,pe,Ce,je,Me,qe,$e,nt,rt,pt,vt,ot)=>{const Ut=de.transform,Tt=pe.properties.get("color-use-theme")==="none",$t=pe.properties.get("color").toNonPremultipliedRenderColor(Tt?null:de.style.getLut(pe.scope)).toArray01();$t[3]=je;const _t=de.frameCounter/1e3%1,[St,Rt]=pe.properties.get("vertical-range");return{u_fog_matrix:Ce?Ut.calculateFogTileMatrix(Ce):ot||de.identityMat,u_fog_range:pe.getFovAdjustedRange(Ut._fov),u_fog_color:$t,u_fog_horizon_blend:pe.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(St,Rt),Rt],u_fog_temporal_offset:_t,u_frustum_tl:Me,u_frustum_tr:qe,u_frustum_br:$e,u_frustum_bl:nt,u_globe_pos:rt,u_globe_radius:pt,u_viewport:vt,u_globe_transition:o.al(Ut.zoom),u_is_globe:+(Ut.projection.name==="globe")}})(this,H,L,Y,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],O);j.setFogUniformValues(p,te)}q&&j.setCutoffUniformValues(p,q.uniformValues)}setTileLoadedFlag(p){this.tileLoaded=p}saveCanvasCopy(){const p=this.canvasCopy();p&&(this.frameCopies.push(p),this.tileLoaded=!1)}canvasCopy(){const p=this.context.gl,j=p.createTexture();return p.bindTexture(p.TEXTURE_2D,j),p.copyTexImage2D(p.TEXTURE_2D,0,p.RGBA,0,0,p.drawingBufferWidth,p.drawingBufferHeight,0),j}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const p=this.style&&this.style.fog;return!!p&&p.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const p=this._backgroundTiles,j=this._backgroundTiles={},L=this.transform.coveringTiles({tileSize:512});for(const O of L)j[O.key]=p[O.key]||new o.b0(O,512,this.transform.tileZoom,this,void 0,this.worldview);return j}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(p,j){return!(!p.is3D(!(!this.terrain||!this.terrain.enabled))||p.type!=="clip"&&p.type!=="building"&&(p.minzoom&&p.minzoom>this.transform.zoom||(this.style._clipLayerPresent||p.sourceLayer!=="building"&&p.sourceLayer!=="procedural_buildings")&&(!j||j.type!=="batched-model")))}isTileAffectedByFog(p){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let j=this._cachedTileFogOpacities[p.key];return j||(this._cachedTileFogOpacities[p.key]=j=this.style.fog.getOpacityForTile(p)),j[0]>=un||j[1]>=un}setupDepthForOcclusion(p,j,L){const O=this.context,q=O.gl,H=!!L;var Y;L||(L={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}),O.activeTexture.set(q.TEXTURE3),p&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(q.NEAREST,q.CLAMP_TO_EDGE),L.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],L.u_depth_range_unpack=[2/((Y=this.depthRangeFor3D)[1]-Y[0]),-1-2*Y[0]/(Y[1]-Y[0])],L.u_occluder_half_size=.5*this.occlusionParams.occluderSize,L.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(q.NEAREST,q.CLAMP_TO_EDGE),O.activeTexture.set(q.TEXTURE0),H||j.setTerrainUniformValues(O,L)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const p=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=p?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function EP(E,p){let j=!1,L=null;const O=()=>{L=null,j&&(E(),L=setTimeout(O,p),j=!1)};return()=>(j=!0,L||O(),L)}class Sge{constructor(p){this._hashName=p&&encodeURIComponent(p),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=EP(this._updateHashUnthrottled.bind(this),300)}addTo(p){return this._map=p,window.addEventListener("hashchange",this._onHashChange,!1),p.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 p=this._map;if(!p)return"";const j=Tu(p);if(this._hashName){const L=this._hashName;let O=!1;const q=location.hash.slice(1).split("&").map(H=>{const Y=H.split("=")[0];return Y===L?(O=!0,`${Y}=${j}`):H}).filter(H=>H);return O||q.push(`${L}=${j}`),`#${q.join("&")}`}return`#${j}`}_getCurrentHash(){const p=location.hash.replace("#","");if(this._hashName){let j;return p.split("&").map(L=>L.split("=")).forEach(L=>{L[0]===this._hashName&&(j=L)}),(j&&j[1]||"").split("/")}return p.split("/")}_onHashChange(){const p=this._map;if(!p)return!1;const j=this._getCurrentHash();if(j.length>=3&&!j.some(L=>isNaN(Number(L)))){const L=p.dragRotate.isEnabled()&&p.touchZoomRotate.isEnabled()?+(j[3]||0):p.getBearing();return p.jumpTo({center:[+j[2],+j[1]],zoom:+j[0],bearing:L,pitch:+(j[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function Tu(E,p){const j=E.getCenter(),L=Math.round(100*E.getZoom())/100,O=Math.ceil((L*Math.LN2+Math.log(512/360/.5))/Math.LN10),q=Math.pow(10,O),H=Math.round(j.lng*q)/q,Y=Math.round(j.lat*q)/q,te=E.getBearing(),de=E.getPitch();let pe=p?`/${H}/${Y}/${L}`:`${L}/${Y}/${H}`;return(te||de)&&(pe+="/"+Math.round(10*te)/10),de&&(pe+=`/${Math.round(de)}`),pe}const rT={linearity:.3,easing:o.eN(0,0,.3,1)},Y2=Object.assign({deceleration:2500,maxSpeed:1400},rT),Cge=Object.assign({deceleration:20,maxSpeed:1400},rT),to=Object.assign({deceleration:1e3,maxSpeed:360},rT),Ta=Object.assign({deceleration:1e3,maxSpeed:90},rT);class Gz{constructor(p){this._map=p,this.clear()}clear(){this._inertiaBuffer=[]}record(p){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:p})}_drainInertiaBuffer(){const p=this._inertiaBuffer,j=o.o.now();for(;p.length>0&&j-p[0].time>160;)p.shift()}_onMoveEnd(p){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const j={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:q}of this._inertiaBuffer)j.zoom+=q.zoomDelta||0,j.bearing+=q.bearingDelta||0,j.pitch+=q.pitchDelta||0,q.panDelta&&j.pan._add(q.panDelta),q.around&&(j.around=q.around),q.pinchAround&&(j.pinchAround=q.pinchAround);const L=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,O={};if(j.pan.mag()){const q=jx(j.pan.mag(),L,Object.assign({},Y2,p||{}));O.offset=j.pan.mult(q.amount/j.pan.mag()),O.center=this._map.transform.center,om(O,q)}if(j.zoom){const q=jx(j.zoom,L,Cge);O.zoom=this._map.transform.zoom+q.amount,om(O,q)}if(j.bearing){const q=jx(j.bearing,L,to);O.bearing=this._map.transform.bearing+o.aC(q.amount,-179,179),om(O,q)}if(j.pitch){const q=jx(j.pitch,L,Ta);O.pitch=this._map.transform.pitch+q.amount,om(O,q)}if(O.zoom||O.bearing){const q=j.pinchAround===void 0?j.around:j.pinchAround;O.around=q?this._map.unproject(q):this._map.getCenter()}return this.clear(),O.noMoveStart=!0,O}}function om(E,p){(!E.duration||E.durationj.unproject(te)),Y=q.reduce((te,de,pe,Ce)=>te.add(de.div(Ce.length)),new o.P(0,0));super(p,{points:q,point:Y,lngLats:H,lngLat:j.unproject(Y),originalEvent:L}),this._defaultPrevented=!1}}class AP extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(p,j){super("wheel",{originalEvent:j}),this._defaultPrevented=!1}}class MP{constructor(p,j){this._map=p,this._clickTolerance=j.clickTolerance}reset(){this._mousedownPos=void 0}wheel(p){return this._firePreventable(new AP(this._map,p))}mousedown(p,j){return this._mousedownPos=j,this._firePreventable(new $d(p.type,this._map,p))}mouseup(p){this._map.fire(new $d(p.type,this._map,p))}preclick(p){const j=new MouseEvent("preclick",p);this._map.fire(new $d(j.type,this._map,j))}click(p,j){this._mousedownPos&&this._mousedownPos.dist(j)>=this._clickTolerance||(this.preclick(p),this._map.fire(new $d(p.type,this._map,p)))}dblclick(p){return this._firePreventable(new $d(p.type,this._map,p))}mouseover(p){this._map.fire(new $d(p.type,this._map,p))}mouseout(p){this._map.fire(new $d(p.type,this._map,p))}touchstart(p){return this._firePreventable(new Bm(p.type,this._map,p))}touchmove(p){this._map.fire(new Bm(p.type,this._map,p))}touchend(p){this._map.fire(new Bm(p.type,this._map,p))}touchcancel(p){this._map.fire(new Bm(p.type,this._map,p))}_firePreventable(p){if(this._map.fire(p),p.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class IP{constructor(p){this._map=p}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(p){this._map.fire(new $d(p.type,this._map,p))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new $d("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(p){this._delayContextMenu?this._contextMenuEvent=p:this._map.fire(new $d(p.type,this._map,p)),this._map.listens("contextmenu")&&p.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class LP{constructor(p,j){this._map=p,this._el=p.getCanvasContainer(),this._container=p.getContainer(),this._clickTolerance=j.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(p,j){this.isEnabled()&&p.shiftKey&&p.button===0&&(A(),this._startPos=this._lastPos=j,this._active=!0)}mousemoveWindow(p,j){if(!this._active)return;const L=j,O=this._startPos,q=this._lastPos;if(!O||!q||q.equals(L)||!this._box&&L.dist(O){this._box&&(this._box.style.transform=`translate(${H}px,${te}px)`,this._box.style.width=Y-H+"px",this._box.style.height=de-te+"px")})}mouseupWindow(p,j){if(!this._active)return;const L=this._startPos,O=j;if(L&&p.button===0){if(this.reset(),R(),L.x!==O.x||L.y!==O.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:p})),{cameraAnimation:q=>q.fitScreenCoordinates(L,O,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",p)}}keydown(p){this._active&&p.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",p))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),I(),delete this._startPos,delete this._lastPos}_fireEvent(p,j){return this._map.fire(new o.C(p,{originalEvent:j}))}}function Z2(E,p){const j={};for(let L=0;Lthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=p.timeStamp),L.length===this.numTouches&&(this.centroid=function(O){const q=new o.P(0,0);for(const H of O)q._add(H);return q.div(O.length)}(j),this.touches=Z2(L,j)))}touchmove(p,j,L){if(this.aborted||!this.centroid)return;const O=Z2(L,j);for(const q in this.touches){const H=O[q];(!H||H.dist(this.touches[q])>30)&&(this.aborted=!0)}}touchend(p,j,L){if((!this.centroid||p.timeStamp-this.startTime>500)&&(this.aborted=!0),L.length===0){const O=!this.aborted&&this.centroid;if(this.reset(),O)return O}}}class Nx{constructor(p){this.singleTap=new Tf(p),this.numTaps=p.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(p,j,L){this.singleTap.touchstart(p,j,L)}touchmove(p,j,L){this.singleTap.touchmove(p,j,L)}touchend(p,j,L){const O=this.singleTap.touchend(p,j,L);if(O){const q=p.timeStamp-this.lastTime<500,H=!this.lastTap||this.lastTap.dist(O)<30;if(q&&H||this.reset(),this.count++,this.lastTime=p.timeStamp,this.lastTap=O,this.count===this.numTaps)return this.reset(),O}}}class v_{constructor(){this._zoomIn=new Nx({numTouches:1,numTaps:2}),this._zoomOut=new Nx({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(p,j,L){this._zoomIn.touchstart(p,j,L),this._zoomOut.touchstart(p,j,L)}touchmove(p,j,L){this._zoomIn.touchmove(p,j,L),this._zoomOut.touchmove(p,j,L)}touchend(p,j,L){const O=this._zoomIn.touchend(p,j,L),q=this._zoomOut.touchend(p,j,L);return O?(this._active=!0,p.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:H=>H.easeTo({duration:300,zoom:H.getZoom()+1,around:H.unproject(O)},{originalEvent:p})}):q?(this._active=!0,p.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:H=>H.easeTo({duration:300,zoom:H.getZoom()-1,around:H.unproject(q)},{originalEvent:p})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const nT=0,PP=2,DP={[nT]:1,[PP]:2},$g={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class X2{constructor(p){this.reset(),this._clickTolerance=p.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(p,j){return!1}_move(p,j){return{}}mousedown(p,j){if(this._lastPoint)return;const L=z(p);this._correctButton(p,L)&&(this._lastPoint=j,this._eventButton=L)}mousemoveWindow(p,j){const L=this._lastPoint;if(L){if(p.preventDefault(),this._eventButton!=null&&function(O,q){const H=DP[q];return O.buttons===void 0||(O.buttons&H)!==H}(p,this._eventButton))this.reset();else if(this._moved||!(j.dist(L)0&&(this._active=!0);const O=Z2(L,j),q=new o.P(0,0),H=new o.P(0,0);let Y=0;for(const de in O){const pe=O[de],Ce=this._touches[de];Ce&&(q._add(pe),H._add(pe.sub(Ce)),Y++,O[de]=pe)}if(this._touches=O,Y{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class J2{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(p){}_move(p,j,L){return{}}touchstart(p,j,L){this._firstTwoTouches||L.length<2||(this._firstTwoTouches=[L[0].identifier,L[1].identifier],this._start([j[0],j[1]]))}touchmove(p,j,L){const O=this._firstTwoTouches;if(!O)return;p.preventDefault();const[q,H]=O,Y=ll(L,j,q),te=ll(L,j,H);if(!Y||!te)return;const de=this._aroundCenter?null:Y.add(te).div(2);return this._move([Y,te],de,p)}touchend(p,j,L){if(!this._firstTwoTouches)return;const[O,q]=this._firstTwoTouches,H=ll(L,j,O),Y=ll(L,j,q);H&&Y||(this._active&&R(),this.reset())}touchcancel(){this.reset()}enable(p){this._enabled=!0,this._aroundCenter=!!p&&p.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function ll(E,p,j){for(let L=0;LMath.abs(E.x)}class FP extends J2{constructor(p){super(),this._map=p}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(p){this._lastPoints=p,eN(p[0].sub(p[1]))&&(this._valid=!1)}_move(p,j,L){const O=this._lastPoints;if(!O)return;const q=p[0].sub(O[0]),H=p[1].sub(O[1]);return this._map._cooperativeGestures&&!o.eO()&&L.touches.length<3||(this._valid=this.gestureBeginsVertically(q,H,L.timeStamp),!this._valid)?void 0:(this._lastPoints=p,this._active=!0,{pitchDelta:(q.y+H.y)/2*-.5})}gestureBeginsVertically(p,j,L){if(this._valid!==void 0)return this._valid;const O=p.mag()>=2,q=j.mag()>=2;if(!O&&!q)return;if(!O||!q)return this._firstMove==null&&(this._firstMove=L),L-this._firstMove<100&&void 0;const H=p.y>0==j.y>0;return eN(p)&&eN(j)&&H}}const BP={panStep:100,bearingStep:15,pitchStep:10};class f1{constructor(){const p=BP;this._panStep=p.panStep,this._bearingStep=p.bearingStep,this._pitchStep=p.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(p){if(p.altKey||p.ctrlKey||p.metaKey)return;let j=0,L=0,O=0,q=0,H=0;switch(p.keyCode){case 61:case 107:case 171:case 187:j=1;break;case 189:case 109:case 173:j=-1;break;case 37:p.shiftKey?L=-1:(p.preventDefault(),q=-1);break;case 39:p.shiftKey?L=1:(p.preventDefault(),q=1);break;case 38:p.shiftKey?O=1:(p.preventDefault(),H=-1);break;case 40:p.shiftKey?O=-1:(p.preventDefault(),H=1);break;default:return}return this._rotationDisabled&&(L=0,O=0),{cameraAnimation:Y=>{const te=Y.getZoom();Y.easeTo({duration:300,easeId:"keyboardHandler",easing:zP,zoom:j?Math.round(te)+j*(p.shiftKey?2:1):te,bearing:Y.getBearing()+L*this._bearingStep,pitch:Y.getPitch()+O*this._pitchStep,offset:[-q*this._panStep,-H*this._panStep],center:Y.getCenter()},{originalEvent:p})}}}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 zP(E){return E*(2-E)}const p1=4.000244140625,$P=1/450;class lT{constructor(p,j){this._map=p,this._el=p.getCanvasContainer(),this._handler=j,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=$P,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(p){this._defaultZoomRate=p}setWheelZoomRate(p){this._wheelZoomRate=p}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(p){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!p&&p.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(p){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(p.ctrlKey||p.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let j=p.deltaMode===WheelEvent.DOM_DELTA_LINE?40*p.deltaY:p.deltaY;const L=o.o.now(),O=L-(this._lastWheelEventTime||0);this._lastWheelEventTime=L,j!==0&&j%p1===0?this._type="wheel":j!==0&&Math.abs(j)<4?this._type="trackpad":O>400?(this._type=null,this._lastValue=j,this._timeout=window.setTimeout(this._onTimeout,40,p)):this._type||(this._type=Math.abs(O*j)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,j+=this._lastValue)),p.shiftKey&&j&&(j/=4),this._type&&(this._lastWheelEvent=p,this._delta-=j,this._active||this._start(p)),p.preventDefault()}_onTimeout(p){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(p)}_start(p){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 j=$(this._el,p);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:j,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 p=this._map.transform;this._type==="wheel"&&p.projection.wrap&&(p._center.lng>=180||p._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const j=()=>p._terrainEnabled()&&this._aroundCoord?p.computeZoomRelativeTo(this._aroundCoord):p.zoom;if(this._delta!==0){const de=this._type==="wheel"&&Math.abs(this._delta)>p1?this._wheelZoomRate:this._defaultZoomRate;let pe=2/(1+Math.exp(-Math.abs(this._delta*de)));this._delta<0&&pe!==0&&(pe=1/pe);const Ce=j(),je=Math.pow(2,Ce),Me=typeof this._targetZoom=="number"?p.zoomScale(this._targetZoom):je;this._targetZoom=Math.min(p.maxZoom,Math.max(p.minZoom,p.scaleZoom(Me*pe))),this._type==="wheel"&&(this._startZoom=Ce,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const L=typeof this._targetZoom=="number"?this._targetZoom:j(),O=this._startZoom,q=this._easing;let H,Y=!1;if(this._type==="wheel"&&O&&q){const de=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),pe=q(de);H=o.am(O,L,pe),de<1?this._frameId||(this._frameId=!0):Y=!0}else H=L,Y=!0;this._active=!0,Y&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let te=H-j();return te*this._lastDelta<0&&(te=0),{noInertia:!0,needsRenderFrame:!Y,zoomDelta:te,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(p){let j=o.eP;if(this._prevEase){const L=this._prevEase,O=(o.o.now()-L.start)/L.duration,q=L.easing(O+.01)-L.easing(O),H=.27/Math.sqrt(q*q+1e-4)*.01,Y=Math.sqrt(.0729-H*H);j=o.eN(H,Y,.25,1)}return this._prevEase={start:o.o.now(),duration:p,easing:j},j}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=w("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 cT{constructor(p,j){this._clickZoom=p,this._tapZoom=j}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 dT{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(p,j){return p.preventDefault(),{cameraAnimation:L=>{L.easeTo({duration:300,zoom:L.getZoom()+(p.shiftKey?-1:1),around:L.unproject(j)},{originalEvent:p})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Wz{constructor(){this._tap=new Nx({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(p,j,L){this._swipePoint||(this._tapTime&&p.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?L.length>0&&(this._swipePoint=j[0],this._swipeTouch=L[0].identifier):this._tap.touchstart(p,j,L))}touchmove(p,j,L){if(this._tapTime){if(this._swipePoint){if(L[0].identifier!==this._swipeTouch)return;const O=j[0],q=O.y-this._swipePoint.y;return this._swipePoint=O,p.preventDefault(),this._active=!0,{zoomDelta:q/128}}}else this._tap.touchmove(p,j,L)}touchend(p,j,L){this._tapTime?this._swipePoint&&L.length===0&&this.reset():this._tap.touchend(p,j,L)&&(this._tapTime=p.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class UP{constructor(p,j,L){this._el=p,this._mousePan=j,this._touchPan=L}enable(p){this._inertiaOptions=p||{},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 Kz{constructor(p,j,L){this._pitchWithRotate=p.pitchWithRotate,this._mouseRotate=j,this._mousePitch=L}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 Yz{constructor(p,j,L,O){this._el=p,this._touchZoom=j,this._touchRotate=L,this._tapDragZoom=O,this._rotationDisabled=!1,this._enabled=!0}enable(p){this._touchZoom.enable(p),this._rotationDisabled||this._touchRotate.enable(p),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 tN=E=>E.zoom||E.drag||E.pitch||E.rotate;class Zz extends o.C{}class Xz{constructor(){this.constants=[1,1,.01],this.radius=0}setup(p,j){const L=o.ax([],j,p);this.radius=o.ai(L[2]<0?o.eR([],L,this.constants):[L[0],L[1],0])}projectRay(p){o.eR(p,p,this.constants),o.ay(p,p),o.eS(p,p,this.constants);const j=o.bJ([],p,this.radius);if(j[2]>0){const L=o.bJ([],[0,0,1],o.bi(j,[0,0,1])),O=o.bJ([],o.ay([],[j[0],j[1],0]),this.radius),q=o.cT([],j,o.bJ([],o.ax([],o.cT([],O,L),j),2));j[0]=q[0],j[1]=q[1]}return j}}function sN(E){return E.panDelta&&E.panDelta.mag()||E.zoomDelta||E.bearingDelta||E.pitchDelta}class Qz{constructor(p,j){this._map=p,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Gz(p),this._bearingSnap=j.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Xz,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(j),o.aZ(["handleEvent","handleWindowEvent"],this);const L=this._el;this._listeners=[[L,"touchstart",{passive:!0}],[L,"touchmove",{passive:!1}],[L,"touchend",void 0],[L,"touchcancel",void 0],[L,"mousedown",void 0],[L,"mousemove",void 0],[L,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[L,"mouseover",void 0],[L,"mouseout",void 0],[L,"dblclick",void 0],[L,"click",void 0],[L,"keydown",{capture:!1}],[L,"keyup",void 0],[L,"wheel",{passive:!1}],[L,"contextmenu",void 0],[window,"blur",void 0]];for(const[O,q,H]of this._listeners){const Y=O===document?this.handleWindowEvent:this.handleEvent;O.addEventListener(q,Y,H)}}destroy(){for(const[p,j,L]of this._listeners){const O=p===document?this.handleWindowEvent:this.handleEvent;p.removeEventListener(j,O,L)}}_addDefaultHandlers(p){const j=this._map,L=j.getCanvasContainer();this._add("mapEvent",new MP(j,p));const O=j.boxZoom=new LP(j,p);this._add("boxZoom",O);const q=new v_,H=new dT;j.doubleClickZoom=new cT(H,q),this._add("tapZoom",q),this._add("clickZoom",H);const Y=new Wz;this._add("tapDragZoom",Y);const te=j.touchPitch=new FP(j);this._add("touchPitch",te);const de=new aT(p),pe=new Q2(p);j.dragRotate=new Kz(p,de,pe),this._add("mouseRotate",de,["mousePitch"]),this._add("mousePitch",pe,["mouseRotate"]);const Ce=new Ef(p),je=new RP(j,p);j.dragPan=new UP(L,Ce,je),this._add("mousePan",Ce),this._add("touchPan",je,["touchZoom","touchRotate"]);const Me=new m1,qe=new OP;j.touchZoomRotate=new Yz(L,qe,Me,Y),this._add("touchRotate",Me,["touchPan","touchZoom"]),this._add("touchZoom",qe,["touchPan","touchRotate"]),this._add("blockableMapEvent",new IP(j));const $e=j.scrollZoom=new lT(j,this);this._add("scrollZoom",$e,["mousePan"]);const nt=j.keyboard=new f1;this._add("keyboard",nt);for(const rt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])p.interactive&&p[rt]&&j[rt].enable(p[rt])}_add(p,j,L){this._handlers.push({handlerName:p,handler:j,allowed:L}),this._handlersById[p]=j}stop(p){if(!this._updatingCamera){for(const{handler:j}of this._handlers)j.reset();this._inertia.clear(),this._fireEvents({},{},p),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:p}of this._handlers)if(p.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!tN(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(p,j,L){for(const O in p)if(O!==L&&(!j||j.indexOf(O)<0))return!0;return!1}handleWindowEvent(p){this.handleEvent(p,`${p.type}Window`)}_getMapTouches(p){const j=[];for(const L of p)this._el.contains(L.target)&&j.push(L);return j}handleEvent(p,j){this._updatingCamera=!0;const L=p.type==="renderFrame",O=L?void 0:p,q={needsRenderFrame:!1},H={},Y={},te=p.touches?this._getMapTouches(p.touches):void 0,de=te?F(this._el,te):L?void 0:$(this._el,p);for(const{handlerName:je,handler:Me,allowed:qe}of this._handlers){if(!Me.isEnabled())continue;let $e;this._blockedByActive(Y,qe,je)?Me.reset():Me[j||p.type]&&($e=Me[j||p.type](p,de,te),this.mergeHandlerResult(q,H,$e,je,O),$e&&$e.needsRenderFrame&&this._triggerRenderFrame()),($e||Me.isActive())&&(Y[je]=Me)}const pe={};for(const je in this._previousActiveHandlers)Y[je]||(pe[je]=O);this._previousActiveHandlers=Y,(Object.keys(pe).length||sN(q))&&(this._changes.push([q,H,pe]),this._triggerRenderFrame()),(Object.keys(Y).length||sN(q))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Ce}=q;Ce&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Ce(this._map))}mergeHandlerResult(p,j,L,O,q){if(!L)return;Object.assign(p,L);const H={handlerName:O,originalEvent:L.originalEvent||q};L.zoomDelta!==void 0&&(j.zoom=H),L.panDelta!==void 0&&(j.drag=H),L.pitchDelta!==void 0&&(j.pitch=H),L.bearingDelta!==void 0&&(j.rotate=H)}_applyChanges(){const p={},j={},L={};for(const[O,q,H]of this._changes)O.panDelta&&(p.panDelta=(p.panDelta||new o.P(0,0))._add(O.panDelta)),O.zoomDelta&&(p.zoomDelta=(p.zoomDelta||0)+O.zoomDelta),O.bearingDelta&&(p.bearingDelta=(p.bearingDelta||0)+O.bearingDelta),O.pitchDelta&&(p.pitchDelta=(p.pitchDelta||0)+O.pitchDelta),O.around!==void 0&&(p.around=O.around),O.aroundCoord!==void 0&&(p.aroundCoord=O.aroundCoord),O.pinchAround!==void 0&&(p.pinchAround=O.pinchAround),O.noInertia&&(p.noInertia=O.noInertia),Object.assign(j,q),Object.assign(L,H);this._updateMapTransform(p,j,L),this._changes=[]}_updateMapTransform(p,j,L){const O=this._map,q=O.transform,H=pt=>[pt.x,pt.y,pt.z];if((()=>{const pt=this._eventsInProgress.drag;return pt&&!this._handlersById[pt.handlerName].isActive()})()&&!sN(p)){const pt=q.zoom;q.cameraElevationReference="sea",this._originalZoom!=null&&q._orthographicProjectionAtLowPitch&&q.projection.name!=="globe"&&q.pitch===0?(q.cameraElevationReference="ground",q.zoom=this._originalZoom):(q.recenterOnTerrain(),q.cameraElevationReference="ground"),pt!==q.zoom&&this._map._update(!0)}if(q._isCameraConstrained&&O._stop(!0),!sN(p))return void this._fireEvents(j,L,!0);let{panDelta:Y,zoomDelta:te,bearingDelta:de,pitchDelta:pe,around:Ce,aroundCoord:je,pinchAround:Me}=p;q._isCameraConstrained&&(te>0&&(te=0),q._isCameraConstrained=!1),Me!==void 0&&(Ce=Me),(te||(pt=>j[pt]&&!this._eventsInProgress[pt])("drag"))&&Ce&&(this._dragOrigin=H(q.pointCoordinate3D(Ce)),this._originalZoom=q.zoom,this._trackingEllipsoid.setup(q._camera.position,this._dragOrigin)),q.cameraElevationReference="sea",O._stop(!0),Ce=Ce||O.transform.centerPoint,de&&(q.bearing+=de),pe&&(q.pitch+=pe),q._updateCameraState();const qe=[0,0,0];if(Y)if(q.projection.name==="mercator"){const pt=this._trackingEllipsoid.projectRay(q.screenPointToMercatorRay(Ce).dir),vt=this._trackingEllipsoid.projectRay(q.screenPointToMercatorRay(Ce.sub(Y)).dir);qe[0]=vt[0]-pt[0],qe[1]=vt[1]-pt[1]}else{const pt=q.pointCoordinate(Ce);if(q.projection.name==="globe"){Y=Y.rotate(-q.angle);const vt=q._pixelsPerMercatorPixel/q.worldSize;qe[0]=-Y.x*o.eQ(o.bV(pt.y))*vt,qe[1]=-Y.y*o.eQ(q.center.lat)*vt}else{const vt=q.pointCoordinate(Ce.sub(Y));pt&&vt&&(qe[0]=vt.x-pt.x,qe[1]=vt.y-pt.y)}}const $e=q.zoom,nt=[0,0,0];if(te){const pt=H(je||q.pointCoordinate3D(Ce)),vt={dir:o.ay([],o.ax([],pt,q._camera.position))};if(vt.dir[2]<0){const ot=q.zoomDeltaToMovement(pt,te);o.bJ(nt,vt.dir,ot)}}const rt=o.cT(qe,qe,nt);q._translateCameraConstrained(rt),te&&Math.abs(q.zoom-$e)>1e-4&&q.recenterOnTerrain(),q.cameraElevationReference="ground",this._map._update(),p.noInertia||this._inertia.record(p),this._fireEvents(j,L,!0)}_fireEvents(p,j,L){const O=tN(this._eventsInProgress),q=tN(p),H={};for(const pe in p){const{originalEvent:Ce}=p[pe];this._eventsInProgress[pe]||(H[`${pe}start`]=Ce),this._eventsInProgress[pe]=p[pe]}!O&&q&&this._fireEvent("movestart",q.originalEvent);for(const pe in H)this._fireEvent(pe,H[pe]);q&&this._fireEvent("move",q.originalEvent);for(const pe in p){const{originalEvent:Ce}=p[pe];this._fireEvent(pe,Ce)}const Y={};let te;for(const pe in this._eventsInProgress){const{handlerName:Ce,originalEvent:je}=this._eventsInProgress[pe];this._handlersById[Ce].isActive()||(delete this._eventsInProgress[pe],te=j[Ce]||je,Y[`${pe}end`]=te)}for(const pe in Y)this._fireEvent(pe,Y[pe]);const de=tN(this._eventsInProgress);if(L&&(O||q)&&!de){this._updatingCamera=!0;const pe=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ce=je=>je!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new Zz("renderFrame",{timeStamp:p})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const qP="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Jz extends o.E{constructor(p,j){super(),this._moving=!1,this._zooming=!1,this.transform=p,this._bearingSnap=j.bearingSnap,this._respectPrefersReducedMotion=j.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(p,j){return this.jumpTo({center:p},j)}panBy(p,j,L){return p=o.P.convert(p).mult(-1),this.panTo(this.transform.center,Object.assign({offset:p},j),L)}panTo(p,j,L){return this.easeTo(Object.assign({center:p},j),L)}getZoom(){return this.transform.zoom}setZoom(p,j){return this.jumpTo({zoom:p},j),this}zoomTo(p,j,L){return this.easeTo(Object.assign({zoom:p},j),L)}zoomIn(p,j){return this.zoomTo(this.getZoom()+1,p,j),this}zoomOut(p,j){return this.zoomTo(this.getZoom()-1,p,j),this}getBearing(){return this.transform.bearing}setBearing(p,j){return this.jumpTo({bearing:p},j),this}getPadding(){return this.transform.padding}setPadding(p,j){return this.jumpTo({padding:p},j),this}rotateTo(p,j,L){return this.easeTo(Object.assign({bearing:p},j),L)}resetNorth(p,j){return this.rotateTo(0,Object.assign({duration:1e3},p),j),this}resetNorthPitch(p,j){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},p),j),this}snapToNorth(p,j){return Math.abs(this.getBearing())p.aspect?L/(2*Math.tan(.5*p.fovX)*p.aspect):O/(2*Math.tan(.5*p.fovY)*p.aspect)}_cameraForBoundsOnGlobe(p,j,L,O,q,H){const Y=p.clone(),te=this._extendCameraOptions(H);Y.bearing=O,Y.pitch=q;const de=o.aU.convert(j),pe=o.aU.convert(L),Ce=.5*(de.lat+pe.lat),je=.5*(de.lng+pe.lng),Me=o.eT(Ce,je),qe=o.ay([],Me),$e=o.ay([],o.bh([],qe,[0,1,0])),nt=o.bh([],$e,qe),rt=[$e[0],$e[1],$e[2],0,nt[0],nt[1],nt[2],0,qe[0],qe[1],qe[2],0,0,0,0,1],pt=[Me,o.eT(de.lat,de.lng),o.eT(pe.lat,de.lng),o.eT(pe.lat,pe.lng),o.eT(de.lat,pe.lng),o.eT(Ce,de.lng),o.eT(Ce,pe.lng),o.eT(de.lat,je),o.eT(pe.lat,je)];let vt=o.cU.fromPoints(pt.map(vs=>[o.bi($e,vs),o.bi(nt,vs),o.bi(qe,vs)]));const ot=o.ah([],vt.center,rt);o.eU(ot)===0&&o.eV(ot,0,0,1),o.ay(ot,ot),o.bJ(ot,ot,o.aF),Y.center=o.eW(ot);const Ut=Y.getWorldToCameraMatrix(),Tt=o.b7(new Float64Array(16),Ut);vt=o.cU.applyTransform(vt,o.aD([],Ut,rt));const $t=this._extendAABB(vt,Y,te,O);if(!$t)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");vt=$t,o.ah(ot,ot,Ut);const _t=.5*(vt.max[2]-vt.min[2]),St=this._minimumAABBFrustumDistance(Y,vt),Rt=o.bJ([],[0,0,1],_t),Zt=o.cT(Rt,ot,Rt),qt=St+(Y.pitch===0?0:o.bf(ot,Zt)),xs=Y.globeCenterInViewSpace,as=o.ax([],ot,[xs[0],xs[1],xs[2]]);o.ay(as,as),o.bJ(as,as,qt);const Os=o.cT([],ot,as);o.ah(Os,Os,Tt);const Hs=o.eD/o.aF,Qt=o.ai(Os),Ht=o.bU(Math.max(Qt*Hs-o.eD,Number.EPSILON),0),us=Math.min(Y.zoomFromMercatorZAdjusted(Ht),te.maxZoom);return us>.5*(o.cJ+o.cv)?(Y.setProjection({name:"mercator"}),Y.zoom=us,this._cameraForBounds(Y,j,L,O,q,H)):{center:Y.center,zoom:us,bearing:O,pitch:q}}_extendAABB(p,j,L,O){const q=.5*((L.padding.left||0)+(L.padding.right||0)),H=.5*((L.padding.top||0)+(L.padding.bottom||0)),Y=H,te=q,de=q,pe=H,Ce=j.width-(te+de),je=j.height-(Y+pe),Me=o.ax([],p.max,p.min),qe=Math.min(Ce/Me[0],je/Me[1]),$e=Math.min(j.scaleZoom(j.scale*qe),L.maxZoom);if(isNaN($e))return null;const nt=j.scale/j.zoomScale($e),rt=new o.cU([p.min[0]-te*nt,p.min[1]-pe*nt,p.min[2]],[p.max[0]+de*nt,p.max[1]+Y*nt,p.max[2]]),pt=(typeof L.offset.x=="number"&&typeof L.offset.y=="number"?new o.P(L.offset.x,L.offset.y):o.P.convert(L.offset)).rotate(-o.ap(O));return rt.center[0]-=pt.x*nt,rt.center[1]+=pt.y*nt,rt}queryTerrainElevation(p,j){const L=this.transform.elevation;return L?(j=Object.assign({},{exaggerated:!0},j),L.getAtPoint(o.ag.fromLngLat(p),null,j.exaggerated)):null}_cameraForBounds(p,j,L,O,q,H){if(p.projection.name==="globe")return this._cameraForBoundsOnGlobe(p,j,L,O,q,H);const Y=p.clone(),te=this._extendCameraOptions(H);Y.bearing=O,Y.pitch=q;const de=o.aU.convert(j),pe=o.aU.convert(L),Ce=new o.aU(de.lng,pe.lat),je=new o.aU(pe.lng,de.lat),Me=Y.project(de),qe=Y.project(pe),$e=this.queryTerrainElevation(de),nt=this.queryTerrainElevation(pe),rt=this.queryTerrainElevation(Ce),pt=this.queryTerrainElevation(je),vt=[[Me.x,Me.y,Math.min($e||0,nt||0,rt||0,pt||0)],[qe.x,qe.y,Math.max($e||0,nt||0,rt||0,pt||0)]];let ot=o.cU.fromPoints(vt);const Ut=Y.getWorldToCameraMatrix(),Tt=o.b7(new Float64Array(16),Ut);ot=o.cU.applyTransform(ot,Ut);const $t=this._extendAABB(ot,Y,te,O);if(!$t)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ot=$t;const _t=.5*o.ax([],ot.max,ot.min)[2],St=this._minimumAABBFrustumDistance(Y,ot),Rt=[0,0,1,0];o.aE(Rt,Rt,Ut),o.eX(Rt,Rt);const Zt=o.bJ([],Rt,St+_t),qt=o.cT([],ot.center,Zt);o.ah(ot.center,ot.center,Tt),o.ah(qt,qt,Tt);const xs=Y.unproject(new o.P(ot.center[0],ot.center[1])),as=o.eY(Y.projection,xs),Os=Math.pow(2,as),Hs=Math.min(Y._zoomFromMercatorZ(qt[2]*Y.pixelsPerMeter*Os/Y.worldSize),te.maxZoom);return Y.mercatorFromTransition&&Hs<.5*(o.cJ+o.cv)?(Y.setProjection({name:"globe"}),Y.zoom=Hs,this._cameraForBounds(Y,j,L,O,q,H)):{center:xs,zoom:Hs,bearing:O,pitch:q}}fitBounds(p,j,L){const O=this.cameraForBounds(p,j);return this._fitInternal(O,j,L)}fitScreenCoordinates(p,j,L,O,q){const H=o.P.convert(p),Y=o.P.convert(j),te=new o.P(Math.min(H.x,Y.x),Math.min(H.y,Y.y)),de=new o.P(Math.max(H.x,Y.x),Math.max(H.y,Y.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(H,Y))return this;const pe=this.transform.pointLocation3D(te),Ce=this.transform.pointLocation3D(de),je=this.transform.pointLocation3D(new o.P(te.x,de.y)),Me=this.transform.pointLocation3D(new o.P(de.x,te.y)),qe=[Math.min(pe.lng,Ce.lng,je.lng,Me.lng),Math.min(pe.lat,Ce.lat,je.lat,Me.lat)],$e=[Math.max(pe.lng,Ce.lng,je.lng,Me.lng),Math.max(pe.lat,Ce.lat,je.lat,Me.lat)],nt=O&&O.pitch?O.pitch:this.getPitch(),rt=this._cameraForBounds(this.transform,qe,$e,L,nt,O);return this._fitInternal(rt,O,q)}_fitInternal(p,j,L){return p?(j=Object.assign(p,j)).linear?this.easeTo(j,L):this.flyTo(j,L):this}jumpTo(p,j){this.stop();const L=p.preloadOnly?this.transform.clone():this.transform;let O=!1,q=!1,H=!1;"zoom"in p&&L.zoom!==+p.zoom&&(O=!0,L.zoom=+p.zoom),p.center!==void 0&&(L.center=o.aU.convert(p.center)),"bearing"in p&&L.bearing!==+p.bearing&&(q=!0,L.bearing=+p.bearing),"pitch"in p&&L.pitch!==+p.pitch&&(H=!0,L.pitch=+p.pitch);const Y=typeof p.padding=="number"?this._extendPadding(p.padding):p.padding;if(p.padding!=null&&!L.isPaddingEqual(Y))if(p.retainPadding===!1){const te=L.clone();te.padding=Y,L.setLocationAtPoint(L.center,te.centerPoint)}else L.padding=Y;return p.preloadOnly?(this._preloadTiles(L),this):(this.fire(new o.C("movestart",j)).fire(new o.C("move",j)),O&&this.fire(new o.C("zoomstart",j)).fire(new o.C("zoom",j)).fire(new o.C("zoomend",j)),q&&this.fire(new o.C("rotatestart",j)).fire(new o.C("rotate",j)).fire(new o.C("rotateend",j)),H&&this.fire(new o.C("pitchstart",j)).fire(new o.C("pitch",j)).fire(new o.C("pitchend",j)),this.fire(new o.C("moveend",j)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(qP),this.transform.getFreeCameraOptions()}setFreeCameraOptions(p,j){const L=this.transform;if(!L.projection.supportsFreeCamera)return o.w(qP),this;this.stop();const O=L.zoom,q=L.pitch,H=L.bearing;L.setFreeCameraOptions(p);const Y=O!==L.zoom,te=q!==L.pitch,de=H!==L.bearing;return this.fire(new o.C("movestart",j)).fire(new o.C("move",j)),Y&&this.fire(new o.C("zoomstart",j)).fire(new o.C("zoom",j)).fire(new o.C("zoomend",j)),de&&this.fire(new o.C("rotatestart",j)).fire(new o.C("rotate",j)).fire(new o.C("rotateend",j)),te&&this.fire(new o.C("pitchstart",j)).fire(new o.C("pitch",j)).fire(new o.C("pitchend",j)),this.fire(new o.C("moveend",j)),this}easeTo(p,j){this._stop(!1,p.easeId),((p=Object.assign({offset:[0,0],duration:500,easing:o.eP},p)).animate===!1||this._prefersReducedMotion(p))&&(p.duration=0);const L=this.transform,O=this.getZoom(),q=this.getBearing(),H=this.getPitch(),Y=this.getPadding(),te="zoom"in p?+p.zoom:O,de="bearing"in p?this._normalizeBearing(p.bearing,q):q,pe="pitch"in p?+p.pitch:H,Ce=this._extendPadding(p.padding),je=o.P.convert(p.offset);let Me,qe,$e;if(L.projection.name==="globe"){const Rt=o.ag.fromLngLat(L.center),Zt=je.rotate(-L.angle);Rt.x+=Zt.x/L.worldSize,Rt.y+=Zt.y/L.worldSize;const qt=Rt.toLngLat(),xs=o.aU.convert(p.center||qt);this._normalizeCenter(xs),Me=L.centerPoint.add(Zt),qe=new o.P(Rt.x,Rt.y).mult(L.worldSize),$e=new o.P(o.aH(xs.lng),o.aL(xs.lat)).mult(L.worldSize).sub(qe)}else{Me=L.centerPoint.add(je);const Rt=L.pointLocation(Me),Zt=o.aU.convert(p.center||Rt);this._normalizeCenter(Zt),qe=L.project(Rt),$e=L.project(Zt).sub(qe)}const nt=L.zoomScale(te-O);let rt,pt;p.around&&(rt=o.aU.convert(p.around),pt=L.locationPoint(rt));const vt=this._zooming||te!==O,ot=this._rotating||q!==de,Ut=this._pitching||pe!==H,Tt=!L.isPaddingEqual(Ce),$t=p.retainPadding===!1?L.clone():L,_t=Rt=>Zt=>{if(vt&&(Rt.zoom=o.am(O,te,Zt)),ot&&(Rt.bearing=o.am(q,de,Zt)),Ut&&(Rt.pitch=o.am(H,pe,Zt)),Tt&&($t.interpolatePadding(Y,Ce,Zt),Me=$t.centerPoint.add(je)),rt)Rt.setLocationAtPoint(rt,pt);else{const qt=Rt.zoomScale(Rt.zoom-O),xs=te>O?Math.min(2,nt):Math.max(.5,nt),as=Math.pow(xs,1-Zt),Os=Rt.unproject(qe.add($e.mult(Zt*as)).mult(qt));Rt.setLocationAtPoint(Rt.renderWorldCopies?Os.wrap():Os,Me)}return p.preloadOnly||this._fireMoveEvents(j),Rt};if(p.preloadOnly){const Rt=this._emulate(_t,p.duration,L);return this._preloadTiles(Rt),this}const St={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=vt,this._rotating=ot,this._pitching=Ut,this._padding=Tt,this._easeId=p.easeId,this._prepareEase(j,p.noMoveStart,St),this._ease(_t(L),Rt=>{L.cameraElevationReference==="sea"&&L.recenterOnTerrain(),this._afterEase(j,Rt)},p),this}_prepareEase(p,j,L={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),j||L.moving||this.fire(new o.C("movestart",p)),this._zooming&&!L.zooming&&this.fire(new o.C("zoomstart",p)),this._rotating&&!L.rotating&&this.fire(new o.C("rotatestart",p)),this._pitching&&!L.pitching&&this.fire(new o.C("pitchstart",p))}_fireMoveEvents(p){this.fire(new o.C("move",p)),this._zooming&&this.fire(new o.C("zoom",p)),this._rotating&&this.fire(new o.C("rotate",p)),this._pitching&&this.fire(new o.C("pitch",p))}_afterEase(p,j){if(this._easeId&&j&&this._easeId===j)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const L=this._zooming,O=this._rotating,q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,L&&this.fire(new o.C("zoomend",p)),O&&this.fire(new o.C("rotateend",p)),q&&this.fire(new o.C("pitchend",p)),this.fire(new o.C("moveend",p))}flyTo(p,j){if(this._prefersReducedMotion(p)){const vs=o.aJ(p,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(vs,j)}this.stop(),p=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},p);const L=this.transform,O=this.getZoom(),q=this.getBearing(),H=this.getPitch(),Y=this.getPadding(),te="zoom"in p?o.aC(+p.zoom,L.minZoom,L.maxZoom):O,de="bearing"in p?this._normalizeBearing(p.bearing,q):q,pe="pitch"in p?+p.pitch:H,Ce=this._extendPadding(p.padding),je=L.zoomScale(te-O),Me=o.P.convert(p.offset);let qe=L.centerPoint.add(Me);const $e=L.pointLocation(qe),nt=o.aU.convert(p.center||$e);this._normalizeCenter(nt);const rt=L.project($e),pt=L.project(nt).sub(rt);let vt=p.curve;const ot=Math.max(L.width,L.height),Ut=ot/je,Tt=pt.mag();if("minZoom"in p){const vs=o.aC(Math.min(p.minZoom,O,te),L.minZoom,L.maxZoom),ks=ot/L.zoomScale(vs-O);vt=Math.sqrt(ks/Tt*2)}const $t=vt*vt;function _t(vs){const ks=(Ut*Ut-ot*ot+(vs?-1:1)*$t*$t*Tt*Tt)/(2*(vs?Ut:ot)*$t*Tt);return Math.log(Math.sqrt(ks*ks+1)-ks)}function St(vs){return(Math.exp(vs)-Math.exp(-vs))/2}function Rt(vs){return(Math.exp(vs)+Math.exp(-vs))/2}const Zt=_t(0);let qt=function(vs){return Rt(Zt)/Rt(Zt+vt*vs)},xs=function(vs){return ot*((Rt(Zt)*(St(ks=Zt+vt*vs)/Rt(ks))-St(Zt))/$t)/Tt;var ks},as=(_t(1)-Zt)/vt;if(Math.abs(Tt)<1e-6||!isFinite(as)){if(Math.abs(ot-Ut)<1e-6)return this.easeTo(p,j);const vs=Utp.maxDuration&&(p.duration=0);const Os=q!==de,Hs=pe!==H,Qt=!L.isPaddingEqual(Ce),Ht=p.retainPadding===!1?L.clone():L,us=vs=>ks=>{const cr=ks*as,Js=1/qt(cr);vs.zoom=ks===1?te:O+vs.scaleZoom(Js),Os&&(vs.bearing=o.am(q,de,ks)),Hs&&(vs.pitch=o.am(H,pe,ks)),Qt&&(Ht.interpolatePadding(Y,Ce,ks),qe=Ht.centerPoint.add(Me));const er=ks===1?nt:vs.unproject(rt.add(pt.mult(xs(cr))).mult(Js));return vs.setLocationAtPoint(vs.renderWorldCopies?er.wrap():er,qe),vs._updateCameraOnTerrain(),p.preloadOnly||this._fireMoveEvents(j),vs};if(p.preloadOnly){const vs=this._emulate(us,p.duration,L);return this._preloadTiles(vs),this}return this._zooming=!0,this._rotating=Os,this._pitching=Hs,this._padding=Qt,this._prepareEase(j,!1),this._ease(us(L),()=>this._afterEase(j),p),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(p){}_cancelRenderFrame(p){}_stop(p,j){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const L=this._onEaseEnd;this._onEaseEnd=void 0,L.call(this,j)}if(!p){const L=this.handlers;L&&L.stop(!1)}return this}_ease(p,j,L){L.animate===!1||L.duration===0?(p(1),j()):(this._easeStart=o.o.now(),this._easeOptions=L,this._onEaseFrame=p,this._onEaseEnd=j,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const p=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),j=this._onEaseFrame;j&&j(this._easeOptions.easing(p)),p<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(p,j){p=o.bs(p,-180,180);const L=Math.abs(p-j);return Math.abs(p-360-j)180?-360:L<-180?360:0}_prefersReducedMotion(p){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(p&&p.essential)}_emulate(p,j,L){const O=Math.ceil(15*j/1e3),q=[],H=p(L.clone());for(let Y=0;Y<=O;Y++){const te=H(Y/O);q.push(te.clone())}return q}_preloadTiles(p,j){}}class VP{constructor(p={}){this.options=p,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(p){const j=this.options&&this.options.compact,L=p._getUIString("AttributionControl.ToggleAttribution");this._map=p,this._container=w("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=w("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",L);const O=w("span","mapboxgl-ctrl-icon",this._compactButton);return O.setAttribute("aria-hidden","true"),O.setAttribute("title",L),this._innerContainer=w("div","mapboxgl-ctrl-attrib-inner",this._container),j&&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),j===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 p=this._editLink;p||(p=this._editLink=this._container.querySelector(".mapbox-improve-map"));const j=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(p){const L=j.reduce((O,q,H)=>(q.value&&(O+=`${q.key}=${q.value}${HO.length-q.length),p=p.filter((O,q)=>{for(let H=q+1;H=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?p=[...this.options.customAttribution,...p]:p.unshift(this.options.customAttribution));const L=p.map(O=>function(q){const H=new DOMParser().parseFromString(q,"text/html");return Array.from(H.body.querySelectorAll("*")).reverse().forEach(Y=>{const te=Y.textContent||"";if(Y.tagName!=="A")return void Y.replaceWith(...Y.childNodes);const de=Y.getAttribute("href");if(!de||!/^(https?:|mailto:)/i.test(de))return void Y.replaceWith(H.createTextNode(te));const pe=H.createElement("a");pe.href=de,pe.textContent=te,pe.rel="noopener nofollow";const Ce=Y.getAttribute("class");Ce&&(pe.className=Ce),Y.replaceWith(pe)}),H.body.innerHTML}(O)).join(" | ");L!==this._attribHTML&&(this._attribHTML=L,p.length?(this._innerContainer.innerHTML=L,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 HP{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(p){this._map=p,this._container=w("div","mapboxgl-ctrl");const j=w("a","mapboxgl-ctrl-logo");return j.target="_blank",j.rel="noopener nofollow",j.href="https://www.mapbox.com/",j.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),j.setAttribute("rel","noopener nofollow"),this._container.appendChild(j),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(p){p&&p.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const p=this._map.style._sourceCaches;if(Object.entries(p).length===0)return!0;for(const j in p){const L=p[j].getSource();if(L.hasOwnProperty("mapbox_logo")&&!L.mapbox_logo)return!1}return!0}_updateCompact(){const p=this._container.children;if(p.length){const j=p[0];this._map.getCanvasContainer().offsetWidth<250?j.classList.add("mapboxgl-compact"):j.classList.remove("mapboxgl-compact")}}}class e7{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(p){const j=++this._id;return this._queue.push({callback:p,id:j,cancelled:!1}),j}remove(p){const j=this._currentlyRunning,L=j?this._queue.concat(j):this._queue;for(const O of L)if(O.id===p)return void(O.cancelled=!0)}run(p=0){const j=this._currentlyRunning=this._queue;this._queue=[];for(const L of j)if(!L.cancelled&&(L.callback(p),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class Tge{constructor(p){this.jumpTo(p)}getValue(p){if(p<=this._startTime)return this._start;if(p>=this._endTime)return this._end;const j=o.dn((p-this._startTime)/(this._endTime-this._startTime));return this._start*(1-j)+this._end*j}isEasing(p){return p>=this._startTime&&p<=this._endTime}jumpTo(p){this._startTime=-1/0,this._endTime=-1/0,this._start=p,this._end=p}easeTo(p,j,L){this._start=this.getValue(j),this._end=p,this._startTime=j,this._endTime=j+L}}const Ege={"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 Bi extends o.C{constructor(p,j,L,O){const{point:q,lngLat:H,originalEvent:Y,target:te}=p;super(p.type,{point:q,lngLat:H,originalEvent:Y,target:te}),this.preventDefault=()=>{p.preventDefault()},this.id=j,this.interaction=L,this.feature=O}}class uT{constructor(p){this.map=p,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(p,j){if(this.typeById.has(p))throw new Error(`Interaction id "${p}" already exists.`);const L=j.filter;let O=j.type;L&&this.filters.set(p,o.dg(L)),O==="mouseover"&&(O="mouseenter"),O==="mouseout"&&(O="mouseleave");const q=this.interactionsByType.get(O)||new Map;O==="mouseenter"||O==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(p,j)):q.size===0&&this.map.on(O,this.handleType),q.size===0&&this.interactionsByType.set(O,q),q.set(p,j),this.typeById.set(p,O)}get(p){const j=this.typeById.get(p);if(!j)return;const L=this.interactionsByType.get(j);return L?L.get(p):void 0}remove(p){const j=this.typeById.get(p);if(!j)return;this.typeById.delete(p),this.filters.delete(p);const L=this.interactionsByType.get(j);L&&(L.delete(p),j==="mouseenter"||j==="mouseleave"?(this.delegatedInteractions.delete(p),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):L.size===0&&this.map.off(j,this.handleType))}queryTargets(p,j){const L=[];for(const[O,q]of j)q.target&&L.push({targetId:O,target:q.target,filter:this.filters.get(O)});return this.map.style.queryRenderedTargets(p,L,this.map.transform)}handleMove(p){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const j=this.queryTargets(p.point,Array.from(this.delegatedInteractions).reverse());j.length&&(p.type="mouseenter",this.handleType(p,j));const L=new Map;for(const[O,{feature:q}]of this.prevHoveredFeatures)this.hoveredFeatures.has(O)||L.set(q.id,q);L.size&&(p.type="mouseleave",this.handleType(p,Array.from(L.values())))}handleOut(p){const j=Array.from(this.hoveredFeatures.values()).map(({feature:L})=>L);j.length&&(p.type="mouseleave",this.handleType(p,j)),this.hoveredFeatures.clear()}handleType(p,j){const L=p.type==="mouseenter";if(L&&!this.interactionsByType.has(p.type))return void o.w("mouseenter interaction required for mouseleave to work.");const O=Array.from(this.interactionsByType.get(p.type)).reverse(),q=!!j;j=j||this.queryTargets(p.point,O);let H=!1;const Y=new Set;for(const te of j){for(const[de,pe]of O){if(!pe.target)continue;const Ce=te.variants?te.variants[de]:null;if(Ce){for(const je of Ce){if(Nu(je,te,Y,de))continue;const Me=new o.di(te,je),qe=Wy(je,te,de);q&&Me.id!==void 0&&(Me.state=this.map.getFeatureState(Me));const $e=L?this.prevHoveredFeatures.get(qe):null,nt=new Bi(p,de,pe,Me),rt=$e?$e.stop:pe.handler(nt);if(L&&this.hoveredFeatures.set(qe,{feature:te,stop:rt}),rt!==!1){H=!0;break}}if(H)break}}if(H)break}if(!H)for(const[te,de]of O){const{handler:pe,target:Ce}=de;if(!Ce&&pe(new Bi(p,te,de,null))!==!1)break}}}function Age(E,p){if(Array.isArray(E)&&Array.isArray(p)){const j=new Set(E),L=new Set(p);return j.size===L.size&&E.every(O=>L.has(O))}return o.b6(E,p)}const Mge={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},Ige={showCompass:!0,showZoom:!0,visualizePitch:!1};class rN{constructor(p,j,L=!1){this._clickTolerance=10,this.element=j,this.mouseRotate=new aT({clickTolerance:p.dragRotate._mouseRotate._clickTolerance}),this.map=p,L&&(this.mousePitch=new Q2({clickTolerance:p.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),j.addEventListener("mousedown",this.mousedown),j.addEventListener("touchstart",this.touchstart,{passive:!1}),j.addEventListener("touchmove",this.touchmove),j.addEventListener("touchend",this.touchend),j.addEventListener("touchcancel",this.reset)}down(p,j){this.mouseRotate.mousedown(p,j),this.mousePitch&&this.mousePitch.mousedown(p,j),A()}move(p,j){const L=this.map,O=this.mouseRotate.mousemoveWindow(p,j),q=O&&O.bearingDelta;if(q&&L.setBearing(L.getBearing()+q),this.mousePitch){const H=this.mousePitch.mousemoveWindow(p,j),Y=H&&H.pitchDelta;Y&&L.setPitch(L.getPitch()+Y)}}off(){const p=this.element;p.removeEventListener("mousedown",this.mousedown),p.removeEventListener("touchstart",this.touchstart),p.removeEventListener("touchmove",this.touchmove),p.removeEventListener("touchend",this.touchend),p.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){I(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(p){this.down(Object.assign({},p,{button:p.button,type:p.type,ctrlKey:!0,preventDefault:()=>p.preventDefault()}),$(this.element,p)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(p){this.move(p,$(this.element,p))}mouseup(p){this.mouseRotate.mouseupWindow(p),this.mousePitch&&this.mousePitch.mouseupWindow(p),this.offTemp()}touchstart(p){p.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=F(this.element,p.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>p.preventDefault()},this._startPos))}touchmove(p){p.targetTouches.length!==1?this.reset():(this._lastPos=F(this.element,p.targetTouches)[0],this.move({buttons:1,preventDefault:()=>p.preventDefault()},this._lastPos))}touchend(p){p.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)j.width||p.y>j.height;j.locationPoint3D(L).distSqr(p)180;){const L=j.locationPoint3D(E);if(L.x>=0&&L.y>=0&&L.x<=j.width&&L.y<=j.height)break;E.lng>j.center.lng?E.lng-=360:E.lng+=360}return E}const nN={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%)"},zm={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Af extends o.E{constructor(p,j){super(),(p instanceof HTMLElement||j)&&(p=Object.assign({element:p},j)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:L="center",color:O="#3FB1CE",scale:q=1,draggable:H=!1,clickTolerance:Y=0,rotation:te=zm.rotation,rotationAlignment:de=zm.rotationAlignment,pitchAlignment:pe=zm.pitchAlignment,occludedOpacity:Ce=zm.occludedOpacity,altitude:je=zm.altitude}=p||{};this._anchor=L,this._color=O,this._scale=q,this._draggable=H,this._clickTolerance=Y,this._rotation=te,this._rotationAlignment=de,this._pitchAlignment=pe,this._occludedOpacity=Ce,this._altitude=je,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),p&&p.element?(this._element=p.element,this._offset=o.P.convert(p&&p.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(p&&p.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",$e=>{$e.preventDefault()}),this._element.addEventListener("mousedown",$e=>{$e.preventDefault()});const Me=this._element.classList;for(const $e in nN)Me.remove(`mapboxgl-marker-anchor-${$e}`);Me.add(`mapboxgl-marker-anchor-${this._anchor}`);const qe=p&&p.className?p.className.trim().split(/\s+/):[];Me.add(...qe),this._popup=null}_createDefaultMarker(){const p=w("div"),j=b("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},p);if(this._altitude===0){const L=b("radialGradient",{id:"shadowGradient"},b("defs",{},j));b("stop",{offset:"10%","stop-opacity":.4},L),b("stop",{offset:"100%","stop-opacity":.05},L),b("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},j)}return b("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"},j),b("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"},j),b("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},j),p}addTo(p){return p===this._map||(this.remove(),this._map=p,p.getCanvasContainer().appendChild(this._element),p.on("move",this._updateMoving),p.on("moveend",this._update),p.on("remove",this._clearFadeTimer),p._addMarker(this),this.setDraggable(this._draggable),this._update(),p.on("click",this._onMapClick)),this}remove(){const p=this._map;return p&&(p.off("click",this._onMapClick),p.off("move",this._updateMoving),p.off("moveend",this._update),p.off("mousedown",this._addDragHandler),p.off("touchstart",this._addDragHandler),p.off("mouseup",this._onUp),p.off("touchend",this._onUp),p.off("mousemove",this._onMove),p.off("touchmove",this._onMove),p.off("remove",this._clearFadeTimer),p._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(p){return this._lngLat=o.aU.convert(p),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(p){return p===this._altitude||(this._defaultMarker&&(this._altitude===0&&p!==0||this._altitude!==0&&p===0)&&(this._element=this._createDefaultMarker()),this._altitude=p||zm.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(p){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")),p){if(!("offset"in p.options)){const O=Math.sqrt(Math.pow(13.5,2)/2);p.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[O,-1*(38.1-13.5+O)],"bottom-right":[-O,-1*(38.1-13.5+O)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=p,p._marker=this,p._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(p){const j=p.code,L=p.charCode||p.keyCode;j!=="Space"&&j!=="Enter"&&L!==32&&L!==13||this.togglePopup()}_onMapClick(p){const j=p.originalEvent.target,L=this._element;this._popup&&(j===L||L.contains(j))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const p=this._popup;return p?(p.isOpen()?(p.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(p.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const p=this._map,j=this._pos;if(!p||!j)return!1;const L=p.unproject(j,this._altitude),O=p.getFreeCameraOptions();if(!O.position)return!1;const q=O.position.toLngLat();return q.distanceTo(L)<.9*q.distanceTo(this._lngLat)}_evaluateOpacity(){const p=this._map;if(!p)return;const j=this._pos;if(!j||j.x<0||j.x>p.transform.width||j.y<0||j.y>p.transform.height)return void this._clearFadeTimer();const L=p.unproject(j,this._altitude);let O;p._showingGlobe()&&o.e$(p.transform,this._lngLat)?O=0:(O=1-p._queryFogOpacity(L),p.transform._terrainEnabled()&&p.getTerrain()&&this._behindTerrain()&&(O*=this._occludedOpacity)),this._element.style.opacity=`${O}`,this._element.style.pointerEvents=O>0?"auto":"none",this._popup&&this._popup._setOpacity(O),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const p=this._pos;if(!p||!this._map)return;const j=this._offset.mult(this._scale);this._element.style.transform=` translate(${p.x}px,${p.y}px) ${nN[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${j.x}px,${j.y}px) `}_calculateXYTransform(){const p=this._pos,j=this._map,L=this.getPitchAlignment();if(!j||!p||L!=="map")return"";if(!j._showingGlobe()){const te=j.getPitch();return te?`rotateX(${te}deg)`:""}const O=o.cH(o.f0(j.transform,this._lngLat)),q=p.sub(o.f1(j.transform)),H=Math.abs(q.x)+Math.abs(q.y);if(H===0)return"";const Y=O/H;return`rotateX(${-q.y*Y}deg) rotateY(${q.x*Y}deg)`}_calculateZTransform(){const p=this._pos,j=this._map;if(!j||!p)return"";let L=0;const O=this.getRotationAlignment();if(O==="map")if(j._showingGlobe()){const q=j.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),H=j.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(q);L=o.cH(Math.atan2(H.y,H.x))-90}else L=-j.getBearing();else if(O==="horizon"){const q=o.aj(4,6,j.getZoom()),H=o.f1(j.transform);H.y+=q*j.transform.height;const Y=p.sub(H),te=o.cH(Math.atan2(Y.y,Y.x));L=(te>90?te-270:te+90)*(1-q)}return L+=this._rotation,L?`rotateZ(${L}deg)`:""}_update(p){cancelAnimationFrame(this._updateFrameId);const j=this._map;j&&(j.transform.renderWorldCopies&&(this._lngLat=GP(this._lngLat,this._pos,j.transform)),this._pos=j.project(this._lngLat,this._altitude),p===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),j._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(j._showingGlobe()||j.getTerrain()||j.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(p){return this._offset=o.P.convert(p),this._update(),this}addClassName(p){return this._element.classList.add(p),this}removeClassName(p){return this._element.classList.remove(p),this}toggleClassName(p){return this._element.classList.toggle(p)}_onMove(p){const j=this._map;if(!j)return;const L=this._pointerdownPos,O=this._positionDelta;if(L&&O){if(!this._isDragging){const q=this._clickTolerance||j._clickTolerance;if(p.point.dist(L)E.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(E.minPitch!=null&&E.maxPitch!=null&&E.minPitch>E.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(E.minPitch!=null&&E.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(E.maxPitch!=null&&E.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");E.antialias&&o.eZ(window)&&(E.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 N2(E.minZoom,E.maxZoom,E.minPitch,E.maxPitch,E.renderWorldCopies,null,null),E),this._repaint=!!E.repaint,this._interactive=E.interactive,this._minTileCacheSize=E.minTileCacheSize,this._maxTileCacheSize=E.maxTileCacheSize,this._failIfMajorPerformanceCaveat=E.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=E.preserveDrawingBuffer,this._antialias=E.antialias,this._trackResize=E.trackResize,this._bearingSnap=E.bearingSnap,this._refreshExpiredTiles=E.refreshExpiredTiles,this._fadeDuration=E.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=E.crossSourceCollisions,this._collectResourceTiming=E.collectResourceTiming,this._language=this._parseLanguage(E.language),this._worldview=E.worldview,this._renderTaskQueue=new e7,this._domRenderTaskQueue=new e7,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},Ege,E.locale),this._clickTolerance=E.clickTolerance,this._cooperativeGestures=E.cooperativeGestures,this._performanceMetricsCollection=E.performanceMetricsCollection,this._tessellationStep=E.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=E.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new Tge(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=E.scaleFactor,this._requestManager=new Z(E.transformRequest,E.accessToken,E.testMode);const j=ie(E.accessToken||o.g.ACCESS_TOKEN);if(j&&"atlas"in j&&typeof j.atlas=="number"&&(this._tokenExpiration=j.atlas),this._silenceAuthErrors=!!E.testMode,this._contextCreateOptions=E.contextCreateOptions?Object.assign({},E.contextCreateOptions):{},typeof E.container=="string"){const L=document.getElementById(E.container);if(!L)throw new Error(`Container '${E.container.toString()}' not found.`);this._container=L}else{if(!(E.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=E.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."),E.maxBounds&&this.setMaxBounds(E.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 Qz(this,E),this._localFontFamily=E.localFontFamily,this._localIdeographFontFamily=E.localIdeographFontFamily,this._useServerFontComposition=E.useServerFontComposition,(E.style||!E.testMode)&&this.setStyle(E.style||o.g.DEFAULT_STYLE,{config:E.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),E.projection&&this.setProjection(E.projection),E.hash&&(this._hash=new Sge(typeof E.hash=="string"&&E.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){p.center==null&&p.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:E.center,zoom:E.zoom,bearing:E.bearing,pitch:E.pitch});const L=E.bounds;L&&(this.resize(),this.fitBounds(L,Object.assign({},E.fitBoundsOptions,{duration:0})))}this.resize(),E.attributionControl&&this.addControl(new VP({customAttribution:E.customAttribution})),this._logoControl=new HP,this.addControl(this._logoControl,E.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",L=>{this._update(L.dataType==="style"),this.fire(new o.C(`${L.dataType}data`,L))}),this.on("dataloading",L=>{this.fire(new o.C(`${L.dataType}dataloading`,L))}),this._interactions=new uT(this)}_getMapId(){return this._mapId}addControl(E,p){if(p===void 0&&(p=E.getDefaultPosition?E.getDefaultPosition():"top-right"),!E||!E.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 j=E.onAdd(this);this._controls.push(E);const L=this._controlPositions[p];return p.indexOf("bottom")!==-1?L.insertBefore(j,L.firstChild):L.appendChild(j),this}removeControl(E){if(!E||!E.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 p=this._controls.indexOf(E);return p>-1&&this._controls.splice(p,1),E.onRemove(this),this}hasControl(E){return this._controls.indexOf(E)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(E){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 p=!this._moving;return p&&this.fire(new o.C("movestart",E)).fire(new o.C("move",E)),this.fire(new o.C("resize",E)),p&&this.fire(new o.C("moveend",E)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(E){return this.transform.setMaxBounds(o.aK.convert(E)),this._update()}setMinZoom(E){if((E=E??-2)>=-2&&E<=this.transform.maxZoom)return this.transform.minZoom=E,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=E,this._update(),this.getZoom()>E?this.setZoom(E):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(E){if((E=E??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(E>=0&&E<=this.transform.maxPitch)return this.transform.minPitch=E,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(E>=this.transform.minPitch)return this.transform.maxPitch=E,this._update(),this.getPitch()>E?this.setPitch(E):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(E){return this._scaleFactor=E,this.painter.scaleFactor=E,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(p=>p.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(E){return this.transform.renderWorldCopies=E,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(E){return E==="auto"?navigator.language:Array.isArray(E)?E.length===0?void 0:E.map(p=>p==="auto"?navigator.language:p):E}setLanguage(E){const p=this._parseLanguage(E);if(!this.style||p===this._language)return this;this._language=p,this.style.reloadSources();for(const j of this._controls)j._setLanguage&&j._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(E){return this.style&&E!==this._worldview?(this._worldview=E,this._styleDirty=!0,this.style.setWorldview(E),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(E){return this._lazyInitEmptyStyle(),E?typeof E=="string"&&(E={name:E}):E=null,this._useExplicitProjection=!!E,this._prioritizeAndUpdateProjection(E,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const E=this.transform,p=E.projection.name;let j;p==="globe"&&E.zoom>=o.cv?(E.setMercatorFromTransition(),j=!0):p==="mercator"&&E.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(E),this.style.applyProjectionUpdate();const L=this.transform.getProjection().name==="mercator"&&j!==this.transform.mercatorFromTransition;return(p||L)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(E,p){return this.transform.locationPoint3D(o.aU.convert(E),p)}unproject(E,p){return this.transform.pointLocation3D(o.P.convert(E),p)}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(E,p,j){const L=O=>{let q=[];if(Array.isArray(p)){const H=p.filter(Y=>this.getLayer(Y));q=H.length?this.queryRenderedFeatures(O,{layers:H}):[]}else q=this.queryRenderedFeatures(O,{target:p});return q};if(E==="mouseenter"||E==="mouseover"){let O=!1;return{listener:j,targets:p,delegates:{mousemove:H=>{const Y=L(H.point);Y.length?O||(O=!0,j.call(this,new $d(E,this,H.originalEvent,{features:Y}))):O=!1},mouseout:()=>{O=!1}}}}if(E==="mouseleave"||E==="mouseout"){let O=!1;return{listener:j,targets:p,delegates:{mousemove:Y=>{L(Y.point).length?O=!0:O&&(O=!1,j.call(this,new $d(E,this,Y.originalEvent)))},mouseout:Y=>{O&&(O=!1,j.call(this,new $d(E,this,Y.originalEvent)))}}}}{const O=q=>{const H=L(q.point);H.length&&(q.features=H,j.call(this,q),delete q.features)};return{listener:j,targets:p,delegates:{[E]:O}}}}on(E,p,j){if(typeof p=="function"||j===void 0)return super.on(E,p);if(typeof p=="string"&&(p=[p]),!this._areTargetsValid(p))return this;const L=this._createDelegatedListener(E,p,j);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[E]=this._delegatedListeners[E]||[],this._delegatedListeners[E].push(L);for(const O in L.delegates)this.on(O,L.delegates[O]);return this}once(E,p,j){if(typeof p=="function"||j===void 0)return super.once(E,p);if(typeof p=="string"&&(p=[p]),!this._areTargetsValid(p))return this;const L=this._createDelegatedListener(E,p,j);for(const O in L.delegates)this.once(O,L.delegates[O]);return this}off(E,p,j){if(typeof p=="function"||j===void 0)return super.off(E,p);if(typeof p=="string"&&(p=[p]),!this._areTargetsValid(p))return this;const L=this._delegatedListeners?this._delegatedListeners[E]:void 0;return L&&(O=>{for(let q=0;q{if(j){const O=typeof j=="string"?j:j instanceof Error?j.message:j.error;o.w(`Unable to perform style diff: ${O}. Rebuilding the style from scratch.`),this._updateStyle(E,p)}else L&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=p.localIdeographFontFamily,this._localFontFamily=p.localFontFamily,this._updateStyle(E,p))}_getUIString(E){const p=this._locale[E];if(p==null)throw new Error(`Missing UI string '${E}'`);return p}_updateStyle(E,p){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),E){const j=Object.assign({},p);p&&p.config&&(j.initialConfig=p.config,delete j.config),this.style=new Cf(this,j).load(E),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Cf(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(E){return E==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(E)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${E}".`))),!1)}_isTargetValid(E){return"featuresetId"in E?this._isValidId("importId"in E?E.importId:E.featuresetId):"layerId"in E&&this._isValidId(E.layerId)}_areTargetsValid(E){if(Array.isArray(E)){for(const p of E)if(!this._isValidId(p))return!1;return!0}return this._isTargetValid(E)}addSource(E,p){return this._isValidId(E)?(this._lazyInitEmptyStyle(),this.style.addSource(E,p),this._update(!0)):this}isSourceLoaded(E){return!!this._isValidId(E)&&!!this.style&&this.style._isSourceCacheLoaded(E)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(E,p,j){this._lazyInitEmptyStyle(),this.style.addSourceType(E,p,j)}removeSource(E){return this._isValidId(E)?(this.style.removeSource(E),this._updateTerrain(),this._update(!0)):this}getSource(E){return this._isValidId(E)?this.style.getOwnSource(E):null}addImage(E,p,{pixelRatio:j=1,sdf:L=!1,stretchX:O,stretchY:q,content:H}={}){this._lazyInitEmptyStyle();const Y=o.I.from(E);if(p instanceof HTMLImageElement||ImageBitmap&&p instanceof ImageBitmap){const{width:te,height:de,data:pe}=o.o.getImageData(p);this.style.addImage(Y,{data:new o.q({width:te,height:de},pe),pixelRatio:j,stretchX:O,stretchY:q,content:H,sdf:L,version:0,usvg:!1})}else if(p.width===void 0||p.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:te,height:de}=p,pe=p;this.style.addImage(Y,{data:new o.q({width:te,height:de},new Uint8Array(pe.data)),pixelRatio:j,stretchX:O,stretchY:q,content:H,sdf:L,usvg:!1,version:0,userImage:pe}),pe.onAdd&&pe.onAdd(this,E)}}updateImage(E,p){this._lazyInitEmptyStyle();const j=o.I.from(E),L=this.style.getImage(j);if(!L)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 O=p instanceof HTMLImageElement||ImageBitmap&&p instanceof ImageBitmap?o.o.getImageData(p):p,{width:q,height:H,data:Y}=O;if(q===void 0||H===void 0)return void this.fire(new o.B(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(q!==(L.usvg?L.icon.usvg_tree.width:L.data.width)||H!==(L.usvg?L.icon.usvg_tree.height:L.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${q}, ${H}) must be that same as the previous version of the image (${L.data.width}, ${L.data.height})`)));const te=!(p instanceof HTMLImageElement||ImageBitmap&&p instanceof ImageBitmap);let de=!1;L.usvg?(L.data=new o.q({width:q,height:H},new Uint8Array(Y)),L.usvg=!1,L.icon=void 0,de=!0):L.data.replace(Y,te),this.style.updateImage(j,L,de)}hasImage(E){return E?!!this.style&&!!this.style.getImage(o.I.from(E)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(E){this.style.removeImage(o.I.from(E))}loadImage(E,p){o.n(this._requestManager.transformRequest(E,o.R.Image),(j,L)=>{p(j,L)})}listImages(){return this.style.listImages().map(E=>E.name)}addModel(E,p){this._lazyInitEmptyStyle(),this.style.addModel(E,p)}hasModel(E){return E?this.style.hasModel(E):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(E){this.style.removeModel(E)}listModels(){return this.style.listModels()}addLayer(E,p){return this._isValidId(E.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(E,p),this._update(!0)):this}getSlot(E){const p=this.getLayer(E);return p&&p.slot||null}setSlot(E,p){return this.style.setSlot(E,p),this.style.mergeLayers(),this._update(!0)}addImport(E,p){return this.style.addImport(E,p).catch(j=>this.fire(new o.B(new Error("Failed to add import",j)))),this}updateImport(E,p){return typeof p!="string"&&p.id!==E?(this.removeImport(E),this.addImport(p)):(this.style.updateImport(E,p),this._update(!0))}removeImport(E){return this.style.removeImport(E),this}moveImport(E,p){return this.style.moveImport(E,p),this._update(!0)}moveLayer(E,p){return this._isValidId(E)?(this.style.moveLayer(E,p),this._update(!0)):this}removeLayer(E){return this._isValidId(E)?(this.style.removeLayer(E),this._update(!0)):this}getLayer(E){if(!this._isValidId(E))return null;const p=this.style.getOwnLayer(E);return p?p.type==="custom"?p.implementation:p.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(E,p,j){return this._isValidId(E)?(this.style.setLayerZoomRange(E,p,j),this._update(!0)):this}setFilter(E,p,j={}){return this._isValidId(E)?(this.style.setFilter(E,p,j),this._update(!0)):this}getFilter(E){return this._isValidId(E)?this.style.getFilter(E):null}setPaintProperty(E,p,j,L={}){return this._isValidId(E)?(this.style.setPaintProperty(E,p,j,L),this._update(!0)):this}getPaintProperty(E,p){return this._isValidId(E)?this.style.getPaintProperty(E,p):null}setLayoutProperty(E,p,j,L={}){return this._isValidId(E)?(this.style.setLayoutProperty(E,p,j,L),this._update(!0)):this}getLayoutProperty(E,p){return this._isValidId(E)?this.style.getLayoutProperty(E,p):null}setLayerProperty(E,p,j,L={}){return this._isValidId(E)?(p==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(E,p,j,L),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(E){return this.style.setGlyphsUrl(E),this._update(!0)}getSchema(E){return this.style.getSchema(E)}setSchema(E,p){return this.style.setSchema(E,p),this._update(!0)}getConfig(E){return this.style.getConfig(E)}setConfig(E,p){return this.style.setConfig(E,p),this._update(!0)}getConfigProperty(E,p){return this.style.getConfigProperty(E,p)}setConfigProperty(E,p,j){return this.style.setConfigProperty(E,p,j),this._update(!0)}getFeaturesetDescriptors(E){return this.style.getFeaturesetDescriptors(E)}setLights(E){if(this._lazyInitEmptyStyle(),E&&E.length===1&&E[0].type==="flat"){const p=E[0];p.properties?this.style.setFlatLight(p.properties,p.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(E),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const E=this.style.getLights()||[];return E.length===0&&E.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),E}setLight(E,p={}){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:E}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(E){return this._lazyInitEmptyStyle(),!E&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(E),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(E){return this._lazyInitEmptyStyle(),this.style.setFog(E),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(E){return this._lazyInitEmptyStyle(),this.style.setSnow(E),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(E){return this._lazyInitEmptyStyle(),this.style.setRain(E),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(E){return this._lazyInitEmptyStyle(),this.style.setColorTheme(E),this._update(!0)}setImportColorTheme(E,p){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(E,p),this._update(!0)}setCamera(E){return this.style.setCamera(E),this._triggerCameraUpdate(E)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(E){const p=this.transform.nearClipOffset!==E;return this.transform.nearClipOffset=E,this._update(p)}_triggerCameraUpdate(E){return this._update(this.transform.setOrthographicProjectionAtLowPitch(E["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(E){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(E),this.transform):0}setFeatureState(E,p){return E.source&&!this._isValidId(E.source)?this:(this.style.setFeatureState(E,p),this._update())}removeFeatureState(E,p){return E.source&&!this._isValidId(E.source)?this:(this.style.removeFeatureState(E,p),this._update())}getFeatureState(E){return E.source&&!this._isValidId(E.source)?null:this.style.getFeatureState(E)}_selectIndoorFloor(E){this.style.indoorManager.selectFloor(E)}_setIndoorActiveFloorsVisibility(E){this.style.indoorManager.setActiveFloorsVisibility(E)}getIndoorTileOptions(E,p){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(E,p):null}_updateContainerDimensions(){if(!this._container)return;const E=this._container.getBoundingClientRect().width||400,p=this._container.getBoundingClientRect().height||300;let j,L,O,q=this._container;for(;q&&(!L||!O);){const H=window.getComputedStyle(q).transform;H&&H!=="none"&&(j=H.match(/matrix.*\((.+)\)/)[1].split(", "),j[0]&&j[0]!=="0"&&j[0]!=="1"&&(L=j[0]),j[3]&&j[3]!=="0"&&j[3]!=="1"&&(O=j[3])),q=q.parentElement}this._containerWidth=L?Math.abs(E/L):E,this._containerHeight=O?Math.abs(p/O):p}_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 E=this._container;E.classList.add("mapboxgl-map"),(this._missingCSSCanary=w("div","mapboxgl-canary",E)).style.visibility="hidden",this._detectMissingCSS();const p=this._canvasContainer=w("div","mapboxgl-canvas-container",E);this._canvas=w("canvas","mapboxgl-canvas",p),this._interactive&&(p.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 j=this._controlContainer=w("div","mapboxgl-control-container",E),L=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(O=>{L[O]=w("div",`mapboxgl-ctrl-${O}`,j)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(E,p){const j=o.o.devicePixelRatio||1;this._canvas.width=j*Math.ceil(E),this._canvas.height=j*Math.ceil(p),this._canvas.style.width=`${E}px`,this._canvas.style.height=`${p}px`}_addMarker(E){this._markers.push(E)}_removeMarker(E){const p=this._markers.indexOf(E);p!==-1&&this._markers.splice(p,1)}_addPopup(E){this._popups.push(E)}_removePopup(E){const p=this._popups.indexOf(E);p!==-1&&this._popups.splice(p,1)}_setupPainter(){const E=Object.assign({},v.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),p=this._canvas.getContext("webgl2",E);p?(We(p,!0),this.painter=new kge(p,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",j=>{if(j.dataType==="source"){const L=this.transform.elevation?this.transform.elevation._source():null;L&&j.sourceCacheId===L.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(p)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(E){E.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:E}))}_contextRestored(E){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:E}))}_onMapScroll(E){if(E.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(E){return this.style?(this._styleDirty=this._styleDirty||E,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(E){return this._update(),this._renderTaskQueue.add(E)}_cancelRenderFrame(E){this._renderTaskQueue.remove(E)}_requestDomTask(E){!this.loaded()||this.loaded()&&!this.isMoving()?E():this._domRenderTaskQueue.add(E)}_render(E){let p;this.fire(new o.C("renderstart")),++this._frameId;const j=this.painter.context.extTimerQuery,L=o.o.now(),O=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(p=O.createQuery(),O.beginQuery(j.TIME_ELAPSED_EXT,p)),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(E),this._domRenderTaskQueue.run(E),this._removed)return;this._updateProjectionTransition();const q=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const te=this.transform.zoom,de=this.transform.pitch,pe=o.o.now(),Ce=new o.ae(te,{now:pe,fadeDuration:q,pitch:de,transition:this.style.transition,worldview:this._worldview});this.style.update(Ce)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let H=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),H=this._updateAverageElevation(L),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):H=this._updateAverageElevation(L),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,q,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:q,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,h.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(),p){const te=o.o.now()-L;O.endQuery(j.TIME_ELAPSED_EXT),setTimeout(()=>{const de=O.getQueryParameter(p,O.QUERY_RESULT)/1e6;O.deleteQuery(p),this.fire(new o.C("gpu-timing-frame",{cpuTime:te,gpuTime:de}))},50)}if(this.listens("gpu-timing-layer")){const te=this.painter.collectGpuTimers();setTimeout(()=>{const de=this.painter.queryGpuTimers(te);this.fire(new o.C("gpu-timing-layer",{layerTimes:de}))},50)}if(this.listens("gpu-timing-deferred-render")){const te=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const de=this.painter.queryGpuTimeDeferredRender(te);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:de}))},50)}const Y=this._sourcesDirty||this._styleDirty||this._placementDirty||H;if(Y||this._repaint)this.triggerRepaint();else{const te=this.idle();if(te&&(H=this._updateAverageElevation(L,!0)),H)this.triggerRepaint();else if(this._triggerFrame(!1),te&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const de=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:de})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||Y||(this._fullyLoaded=!0,h.mark(d.fullLoad),this._performanceMetricsCollection&&fe(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(E){for(const p of this._markers)E&&!this.getRenderWorldCopies()&&(p._lngLat=p._lngLat.wrap()),p._update();for(const p of this._popups)!E||this.getRenderWorldCopies()||p._trackPointer||(p._lngLat=p._lngLat.wrap()),p._update()}_updateAverageElevation(E,p=!1){const j=O=>(this.transform.averageElevation=O,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&j(0);const L=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(L||(p||E-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(E)){const O=this.transform.averageElevation;let q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(q)?q=0:this._averageElevationLastSampledAt=E;const H=Math.abs(O-q);if(H>1){if(this._isInitialLoad||L)return this._averageElevation.jumpTo(q),j(q);this._averageElevation.easeTo(q,E,300)}else if(H>1e-4)return this._averageElevation.jumpTo(q),j(q)}return!!this._averageElevation.isEasing(E)&&j(this._averageElevation.getValue(E))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const E=this.painter.context.gl;We(E,!1),this._logoControl instanceof HP&&this._logoControl._updateLogo(),E&&E.clear(E.DEPTH_BUFFER_BIT|E.COLOR_BUFFER_BIT|E.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(){Oe(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,E=>{E&&(E.message!==X&&E.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),De(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&He(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Ie(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){xe(this._requestManager._customAccessToken)}_updateTerrain(){const E=this._isDragging();this.painter.updateTerrain(this.style,E)}_calculateSpeedIndex(){const E=this.painter.canvasCopy(),p=this.painter.getCanvasCopiesAndTimestamps();p.timeStamps.push(performance.now());const j=this.painter.context.gl,L=j.createFramebuffer();function O(q){j.framebufferTexture2D(j.FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_2D,q,0);const H=new Uint8Array(j.drawingBufferWidth*j.drawingBufferHeight*4);return j.readPixels(0,0,j.drawingBufferWidth,j.drawingBufferHeight,j.RGBA,j.UNSIGNED_BYTE,H),H}return j.bindFramebuffer(j.FRAMEBUFFER,L),this._canvasPixelComparison(O(E),p.canvasCopies.map(O),p.timeStamps)}_canvasPixelComparison(E,p,j){let L=j[1]-j[0];const O=E.length/4;for(let q=0;q{const j=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,j&&this._render(p)}))}_preloadTiles(E){const p=this.style?this.style.getSourceCaches():[];return o.t(p,(j,L)=>j._preloadTiles(E,L),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(E){this._trackResize&&this.resize({originalEvent:E})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(E){this._showTileBoundaries!==E&&(this._showTileBoundaries=E,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(E){this._showParseStatus!==E&&(this._showParseStatus=E,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(E){this._showTerrainWireframe!==E&&(this._showTerrainWireframe=E,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(E){this._showLayers2DWireframe!==E&&(this._showLayers2DWireframe=E,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(E){this._showLayers3DWireframe!==E&&(this._showLayers3DWireframe=E,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(E){this._speedIndexTiming!==E&&(this._speedIndexTiming=E,this._update())}get showPadding(){return!!this._showPadding}set showPadding(E){this._showPadding!==E&&(this._showPadding=E,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(E){this._showCollisionBoxes!==E&&(this._showCollisionBoxes=E,this.style&&E?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(E){this._showOverdrawInspector!==E&&(this._showOverdrawInspector=E,this._update())}get repaint(){return!!this._repaint}set repaint(E){this._repaint!==E&&(this._repaint=E,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(E){this._vertices=E,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(E){this._showTileAABBs!==E&&(this._showTileAABBs=E,E&&this._update())}_setCacheLimits(E,p){o.e_(E,p)}get version(){return c}},NavigationControl:class{constructor(E={}){this.options=Object.assign({},Ige,E),this._container=w("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",p=>p.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",p=>{this._map&&this._map.zoomIn({},{originalEvent:p})}),w("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",p=>{this._map&&this._map.zoomOut({},{originalEvent:p})}),w("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",p=>{const j=this._map;j&&(this.options.visualizePitch?j.resetNorthPitch({},{originalEvent:p}):j.resetNorth({},{originalEvent:p}))}),this._compassIcon=w("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const E=this._map;if(!E)return;const p=E.getZoom(),j=p===E.getMaxZoom(),L=p===E.getMinZoom();this._zoomInButton.disabled=j,this._zoomOutButton.disabled=L,this._zoomInButton.setAttribute("aria-disabled",j.toString()),this._zoomOutButton.setAttribute("aria-disabled",L.toString())}_rotateCompassArrow(){const E=this._map;if(!E)return;const p=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(E.transform.pitch*(Math.PI/180)),.5)}) rotateX(${E.transform.pitch}deg) rotateZ(${E.transform.angle*(180/Math.PI)}deg)`:`rotate(${E.transform.angle*(180/Math.PI)}deg)`;E._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=p)})}onAdd(E){return this._map=E,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),E.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&E.on("pitch",this._rotateCompassArrow),E.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new rN(E,this._compass,this.options.visualizePitch)),this._container}onRemove(){const E=this._map;E&&(this._container.remove(),this.options.showZoom&&E.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&E.off("pitch",this._rotateCompassArrow),E.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(E,p){const j=w("button",E,this._container);return j.type="button",j.addEventListener("click",p),j}_setButtonTitle(E,p){if(!this._map)return;const j=this._map._getUIString(`NavigationControl.${p}`);E.setAttribute("aria-label",j),E.firstElementChild&&E.firstElementChild.setAttribute("title",j)}},GeolocateControl:class extends o.E{constructor(E={}){super();const p=navigator.geolocation;this.options=Object.assign({geolocation:p},aN,E),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=EP(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(E){return this._map=E,this._container=w("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(E){const p=(j=!!this.options.geolocation)=>{this._supportsGeolocation=j,E(j)};this._supportsGeolocation!==void 0?E(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(j=>p(j.state!=="denied")).catch(()=>p()):p()}_isOutOfMapMaxBounds(E){const p=this._map.getMaxBounds(),j=E.coords;return!!p&&(j.longitudep.getEast()||j.latitudep.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(E){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(E))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",E)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=E,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(E),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(E),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:E.coords,timestamp:E.timestamp},E.toJSON?{toJSON:E.toJSON.bind(E)}:{}))),this._finish()}}_updateCamera(E){const p=new o.aU(E.coords.longitude,E.coords.latitude),j=E.coords.accuracy,L=this._map.getBearing(),O=Object.assign({bearing:L},this.options.fitBoundsOptions);this._map.fitBounds(p.toBounds(j),O,{geolocateSource:!0})}_updateMarker(E){if(E){const p=new o.aU(E.coords.longitude,E.coords.latitude);this._accuracyCircleMarker.setLngLat(p).addTo(this._map),this._userLocationDotMarker.setLngLat(p).addTo(this._map),this._accuracy=E.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const E=this._map.transform,p=o.bU(1,E._center.lat)*E.worldSize,j=Math.ceil(2*this._accuracy*p);this._circleElement.style.width=`${j}px`,this._circleElement.style.height=`${j}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(E){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(E.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 p=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",p),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",p),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(E.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:E.code,message:E.message,PERMISSION_DENIED:E.PERMISSION_DENIED,POSITION_UNAVAILABLE:E.POSITION_UNAVAILABLE,TIMEOUT:E.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const E=this.options.positionOptions.timeout;E&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},E))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(E){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",p=>p.preventDefault()),this._geolocateButton=w("button","mapboxgl-ctrl-geolocate",this._container),w("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",E===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const p=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",p),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",p)}else{const p=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",p),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",p)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=w("div","mapboxgl-user-location"),this._dotElement.appendChild(w("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(w("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Af({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=w("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Af({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",p=>{p.geolocateSource||this._watchState!=="ACTIVE_LOCK"||p.originalEvent&&p.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(E){this._userLocationDotMarker&&(E.webkitCompassHeading?this._heading=E.webkitCompassHeading:E.absolute===!0&&(this._heading=-1*E.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 E;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(E={maximumAge:6e5,timeout:0},this._noTimeout=!0):(E=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,E),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(E){return this.options.followUserLocation=E??aN.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 E=()=>{const p="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(p,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(p=>{p==="granted"&&E()}).catch(console.error):E()}_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:VP,ScaleControl:class{constructor(E={}){this.options=Object.assign({},sc,E),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const E=this.options.maxWidth||100,p=this._map,j=p._containerHeight/2,L=p._containerWidth/2-E/2,O=p.unproject([L,j]),q=p.unproject([L+E,j]),H=O.distanceTo(q);if(this.options.unit==="imperial"){const Y=3.2808*H;Y>5280?this._setScale(E,Y/5280,"mile"):this._setScale(E,Y,"foot")}else this.options.unit==="nautical"?this._setScale(E,H/1852,"nautical-mile"):H>=1e3?this._setScale(E,H/1e3,"kilometer"):this._setScale(E,H,"meter")}_setScale(E,p,j){this._map._requestDomTask(()=>{const L=function(q){const H=Math.pow(10,`${Math.floor(q)}`.length-1);let Y=q/H;return Y=Y>=10?10:Y>=5?5:Y>=3?3:Y>=2?2:Y>=1?1:function(te){const de=Math.pow(10,Math.ceil(-Math.log(te)/Math.LN10));return Math.round(te*de)/de}(Y),H*Y}(p),O=L/p;this._container.innerHTML=j!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:j}).format(L):`${L} ${Mf[j]}`,this._container.style.width=E*O+"px"})}onAdd(E){return this._map=E,this._language=E.getLanguage(),this._container=w("div","mapboxgl-ctrl mapboxgl-ctrl-scale",E.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(E){this._language=E,this._update()}setUnit(E){this.options.unit=E,this._update()}},FullscreenControl:class{constructor(E={}){this._fullscreen=!1,E&&E.container&&(E.container instanceof HTMLElement?this._container=E.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(E){return this._map=E,this._container||(this._container=this._map.getContainer()),this._controlContainer=w("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 E=this._fullscreenButton=w("button","mapboxgl-ctrl-fullscreen",this._controlContainer);w("span","mapboxgl-ctrl-icon",E).setAttribute("aria-hidden","true"),E.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const E=this._getTitle();this._fullscreenButton.setAttribute("aria-label",E),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",E)}_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(E){return this._map=E,this._container=w("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 E=this._map.style.indoorManager;E.off("selector-update",this._onIndoorUpdate),E.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(E.getControlState())}}_createButton(E,p){const j=w("button",E,this._container);return j.type="button",j.addEventListener("click",p),j}_setButtonTitle(E,p){E.setAttribute("aria-label",p),E.textContent=p}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(E){if(!E||!E.floors||E.floors.length===0)return this._model=E,void(this._container.style.display="none");const p=this._model;this._model=E,this._container.style.display="inline-block";const j=!p||p.floors.length!==E.floors.length||p.floors.some((L,O)=>L.id!==E.floors[O].id);if(j&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),E.selectedFloorId){if(E.selectedFloorId!==this._lastSelectedFloorId||j){const L=E.floors.findIndex(O=>O.id===E.selectedFloorId);if(L!==-1){const O=E.floors.length;let q,H;O<=5?(q=0,H=O-1):this._visibleFloorStart===0?(q=0,H=3):this._visibleFloorStart>=O-3?(q=O-3-1,H=O-1):(q=this._visibleFloorStart,H=this._visibleFloorStart+3-1),LH&&(this._visibleFloorStart=L-2)}}this._lastSelectedFloorId=E.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const E=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);w("span","mapboxgl-ctrl-icon",E).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||E.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(E);const p=this._model.floors,j=p.length;if(j<=5)return void p.forEach(H=>this._createFloorButton(H));const L=this._visibleFloorStart===0,O=this._visibleFloorStart>=j-3;if(L)this._createFloorButton(p[0]);else{const H=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);w("span","mapboxgl-ctrl-icon",H).setAttribute("aria-hidden","true"),this._container.appendChild(H)}let q=[];if(q=L?p.slice(1,4):O?p.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):p.slice(this._visibleFloorStart,this._visibleFloorStart+3),q.forEach(H=>this._createFloorButton(H)),O)this._createFloorButton(p[j-1]);else{const H=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);w("span","mapboxgl-ctrl-icon",H).setAttribute("aria-hidden","true"),this._container.appendChild(H)}}_createFloorButton(E){const p=this._createButton("mapboxgl-ctrl-level-button",()=>{const q=E.id;this._model&&this._model.selectedFloorId===q&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(q))}),j=(E.name||"").trim(),L=E.zIndex.toString(),O=j?Array.from(j).slice(0,3).join(""):L;this._setButtonTitle(p,O),this._model&&this._model.activeFloorsVisible&&E.id===this._model.selectedFloorId&&p.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(p)}_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 E=this._model&&this._model.floors||[];if(E.length>3){const p=E.length-3;this._visibleFloorStart===p-1&&(this._visibleFloorStart=p-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const E=this._model.floors.length-3;this._visibleFloorStartE&&(this._visibleFloorStart=E),this._render())}}},Popup:class extends o.E{constructor(E){super(),this.options=Object.assign(Object.create(iN),E),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(E&&E.className?E.className.trim().split(/\s+/):[])}addTo(E){return this._map&&this.remove(),this._map=E,this.options.closeOnClick&&E.on("preclick",this._onClose),this.options.closeOnMove&&E.on("move",this._onClose),E.on("remove",this.remove),this._update(),E._addPopup(this),this._focusFirstElement(),this._trackPointer?(E.on("mousemove",this._onMouseEvent),E.on("mouseup",this._onMouseEvent),E._canvasContainer.classList.add("mapboxgl-track-pointer")):E.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 E=this._map;return E&&(E.off("move",this._update),E.off("move",this._onClose),E.off("preclick",this._onClose),E.off("click",this._onClose),E.off("remove",this.remove),E.off("mousemove",this._onMouseEvent),E.off("mouseup",this._onMouseEvent),E.off("drag",this._onMouseEvent),E._canvasContainer&&E._canvasContainer.classList.remove("mapboxgl-track-pointer"),E._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(E){this._lngLat=o.aU.convert(E),this._pos=null,this._trackPointer=!1,this._update();const p=this._map;return p&&(p.on("move",this._update),p.off("mousemove",this._onMouseEvent),p._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(E){return this._altitude=E,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const E=this._map;return E&&(E.off("move",this._update),E.on("mousemove",this._onMouseEvent),E.on("drag",this._onMouseEvent),E._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(E){return this.setDOMContent(document.createTextNode(E))}setHTML(E){const p=document.createDocumentFragment(),j=document.createElement("body");let L;for(j.innerHTML=E;L=j.firstChild,L;)p.appendChild(L);return this.setDOMContent(p)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(E){return this.options.maxWidth=E,this._update(),this}setDOMContent(E){let p=this._content;if(p)for(;p.hasChildNodes();)p.firstChild&&p.removeChild(p.firstChild);else p=this._content=w("div","mapboxgl-popup-content",this._container||void 0);if(p.appendChild(E),this.options.closeButton){const j=this._closeButton=w("button","mapboxgl-popup-close-button",p);j.type="button",j.setAttribute("aria-label","Close popup"),j.innerHTML='',j.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(E){return this._classList.add(E),this._updateClassList(),this}removeClassName(E){return this._classList.delete(E),this._updateClassList(),this}setOffset(E){return this.options.offset=E,this._update(),this}toggleClassName(E){let p;return this._classList.delete(E)?p=!1:(this._classList.add(E),p=!0),this._updateClassList(),p}_onMouseEvent(E){this._update(E.point)}_getAnchor(E){if(this.options.anchor)return this.options.anchor;const p=this._map,j=this._container,L=this._pos;if(!p||!j||!L)return"bottom";const O=j.offsetWidth,q=j.offsetHeight,H=L.xp.transform.width-O/2;if(L.y+Ep.transform.height-q){if(H)return"bottom-left";if(Y)return"bottom-right"}return H?"left":Y?"right":"bottom"}_updateClassList(){const E=this._container;if(!E)return;const p=[...this._classList];p.push("mapboxgl-popup"),this._anchor&&p.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&p.push("mapboxgl-popup-track-pointer"),E.className=p.join(" ")}_update(E){const p=this._map,j=this._content;if(!p||!this._lngLat&&!this._trackPointer||!j)return;let L=this._container;if(L||(L=this._container=w("div","mapboxgl-popup",p.getContainer()),this._tip=w("div","mapboxgl-popup-tip",L),L.appendChild(j)),this.options.maxWidth&&L.style.maxWidth!==this.options.maxWidth&&(L.style.maxWidth=this.options.maxWidth),p.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=GP(this._lngLat,this._pos,p.transform)),!this._trackPointer||E){const O=this._pos=this._trackPointer&&E instanceof o.P?E:p.project(this._lngLat,this._altitude),q=hT(this.options.offset),H=this._anchor=this._getAnchor(q.y),Y=hT(this.options.offset,H),te=O.add(Y).round();p._requestDomTask(()=>{this._container&&H&&(this._container.style.transform=`${nN[H]} translate(${te.x}px,${te.y}px)`)})}if(!this._marker&&p._showingGlobe()){const O=o.e$(p.transform,this._lngLat)?0:1;this._setOpacity(O)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const E=this._container.querySelector(Lge);E&&E.focus()}_onClose(){this.remove()}_setOpacity(E){this._container&&(this._container.style.opacity=`${E}`),this._content&&(this._content.style.pointerEvents=E?"auto":"none")}},Marker:Af,Style:Cf,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:w2,Evented:o.E,config:o.g,prewarm:function(){jt().acquire(Ze)},clearPrewarmedResources:function(){const E=Xe;E&&(E.isPreloaded()&&E.numActive()===1?(E.release(Ze),Xe=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(E){o.g.ACCESS_TOKEN=E},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(E){o.g.API_URL=E},get workerCount(){return lt.workerCount},set workerCount(E){lt.workerCount=E},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(E){o.g.MAX_PARALLEL_IMAGE_REQUESTS=E},clearStorage(E){o.f7(E)},get workerUrl(){return tt.workerUrl},set workerUrl(E){tt.workerUrl=E},get workerClass(){return tt.workerClass},set workerClass(E){tt.workerClass=E},get workerParams(){return tt.workerParams},set workerParams(E){tt.workerParams=E},get dracoUrl(){return o.f6()},set dracoUrl(E){o.g.DRACO_URL=o.o.resolveURL(E)},get meshoptUrl(){return o.f5()},set meshoptUrl(E){const p=o.o.resolveURL(E);o.g.MESHOPT_URL=p,o.g.MESHOPT_SIMD_URL=p},get buildingGenUrl(){return o.f4()},set buildingGenUrl(E){o.g.BUILDING_GEN_URL=o.o.resolveURL(E)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})($Qe);var oAt=$Qe.exports;const Tl=Ao(oAt);function Fs({className:s,...t}){return e.jsx("div",{className:It("animate-pulse rounded-md bg-muted",s),...t})}const mRe={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},fRe={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 lAt(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function cAt({listings:s,isLoading:t}){const r=br(),n=k.useRef(null),a=k.useRef(null),i=k.useRef([]),[l,o]=k.useState(""),[c,d]=k.useState(!0);return k.useEffect(()=>{(async()=>{d(!0);try{const{data:x}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();x!=null&&x.value&&o(x.value)}catch(x){console.error("Error fetching mapbox token:",x)}d(!1)})()},[]),k.useEffect(()=>{if(!n.current||!l||a.current)return;Tl.accessToken=l;const m=s.filter(v=>v.latitude!=null&&v.longitude!=null);let x=[-98.5795,39.8283],y=4;if(m.length>0){const v=m.reduce((b,N)=>b+N.longitude,0)/m.length,w=m.reduce((b,N)=>b+N.latitude,0)/m.length;x=[v,w],y=m.length===1?12:10}return a.current=new Tl.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:y,center:x}),a.current.addControl(new Tl.NavigationControl,"top-right"),()=>{var v;(v=a.current)==null||v.remove(),a.current=null}},[l]),k.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(x=>x.remove()),i.current=[];const m=s.filter(x=>x.latitude!=null&&x.longitude!=null);if(m.forEach(x=>{var A,I,D;const y=mRe[x.status]||"#10B981",v=((A=x.photos)==null?void 0:A.find(R=>R.is_primary))||((I=x.photos)==null?void 0:I[0]),b=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${x.slug||x.id}`:`/public/listing/${x.slug||x.id}`,N=document.createElement("div");N.className="cursor-pointer",N.innerHTML=`
`;const S=new Tl.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${v!=null&&v.photo_url?``:""}
${lAt(x.price)}
${x.property_address||""}
${x.city}, ${x.state}
${fRe[x.status]||x.status} ${x.bedrooms?`${x.bedrooms} bed`:""} ${x.bathrooms?`${x.bathrooms} bath`:""}
${(D=x.agent)!=null&&D.name?`
Listed by ${x.agent.name}
`:""}
Click to view details →
`),T=new Tl.Marker(N).setLngLat([x.longitude,x.latitude]).setPopup(S).addTo(a.current);i.current.push(T)}),m.length>1){const x=new Tl.LngLatBounds;m.forEach(y=>x.extend([y.longitude,y.latitude])),a.current.fitBounds(x,{padding:60,maxZoom:13})}else m.length===1&&a.current.flyTo({center:[m[0].longitude,m[0].latitude],zoom:12})},[s,l]),k.useEffect(()=>(window.__navigateToPublicListing__=m=>{r(m)},()=>{delete window.__navigateToPublicListing__}),[r]),c||t?e.jsx(Fs,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(m=>m.latitude!=null&&m.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(mRe).map(([m,x])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:x}}),e.jsx("span",{className:"text-xs text-gray-600",children:fRe[m]})]},m))}),e.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}function f8(s,[t,r]){return Math.min(r,Math.max(t,s))}function sB(s){const t=k.useRef({value:s,previous:s});return k.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var dAt=[" ","Enter","ArrowUp","ArrowDown"],uAt=[" ","Enter"],E3="Select",[ofe,lfe,hAt]=BF(E3),[UI,NUs]=pd(E3,[hAt,Pv]),cfe=Pv(),[mAt,Zj]=UI(E3),[fAt,pAt]=UI(E3),qQe=s=>{const{__scopeSelect:t,children:r,open:n,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:h,autoComplete:m,disabled:x,required:y,form:v}=s,w=cfe(t),[b,N]=k.useState(null),[S,T]=k.useState(null),[A,I]=k.useState(!1),D=Kj(d),[R,$]=Sh({prop:n,defaultProp:a??!1,onChange:i,caller:E3}),[F,z]=Sh({prop:l,defaultProp:o,onChange:c,caller:E3}),Q=k.useRef(null),K=b?v||!!b.closest("form"):!0,[X,Z]=k.useState(new Set),re=Array.from(X).map(le=>le.props.value).join(";");return e.jsx(qF,{...w,children:e.jsxs(mAt,{required:y,scope:t,trigger:b,onTriggerChange:N,valueNode:S,onValueNodeChange:T,valueNodeHasChildren:A,onValueNodeHasChildrenChange:I,contentId:Yu(),value:F,onValueChange:z,open:R,onOpenChange:$,dir:D,triggerPointerDownPosRef:Q,disabled:x,children:[e.jsx(ofe.Provider,{scope:t,children:e.jsx(fAt,{scope:s.__scopeSelect,onNativeOptionAdd:k.useCallback(le=>{Z(oe=>new Set(oe).add(le))},[]),onNativeOptionRemove:k.useCallback(le=>{Z(oe=>{const ne=new Set(oe);return ne.delete(le),ne})},[]),children:r})}),K?e.jsxs(mJe,{"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:F,onChange:le=>z(le.target.value),disabled:x,form:v,children:[F===void 0?e.jsx("option",{value:""}):null,Array.from(X)]},re):null]})})};qQe.displayName=E3;var VQe="SelectTrigger",HQe=k.forwardRef((s,t)=>{const{__scopeSelect:r,disabled:n=!1,...a}=s,i=cfe(r),l=Zj(VQe,r),o=l.disabled||n,c=Ga(t,l.onTriggerChange),d=lfe(r),h=k.useRef("touch"),[m,x,y]=pJe(w=>{const b=d().filter(T=>!T.disabled),N=b.find(T=>T.value===l.value),S=xJe(b,w,N);S!==void 0&&l.onValueChange(S.value)}),v=w=>{o||(l.onOpenChange(!0),y()),w&&(l.triggerPointerDownPosRef.current={x:Math.round(w.pageX),y:Math.round(w.pageY)})};return e.jsx(PI,{asChild:!0,...i,children:e.jsx(wn.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":fJe(l.value)?"":void 0,...a,ref:c,onClick:Vr(a.onClick,w=>{w.currentTarget.focus(),h.current!=="mouse"&&v(w)}),onPointerDown:Vr(a.onPointerDown,w=>{h.current=w.pointerType;const b=w.target;b.hasPointerCapture(w.pointerId)&&b.releasePointerCapture(w.pointerId),w.button===0&&w.ctrlKey===!1&&w.pointerType==="mouse"&&(v(w),w.preventDefault())}),onKeyDown:Vr(a.onKeyDown,w=>{const b=m.current!=="";!(w.ctrlKey||w.altKey||w.metaKey)&&w.key.length===1&&x(w.key),!(b&&w.key===" ")&&dAt.includes(w.key)&&(v(),w.preventDefault())})})})});HQe.displayName=VQe;var GQe="SelectValue",WQe=k.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,children:i,placeholder:l="",...o}=s,c=Zj(GQe,r),{onValueNodeHasChildrenChange:d}=c,h=i!==void 0,m=Ga(t,c.onValueNodeChange);return Dd(()=>{d(h)},[d,h]),e.jsx(wn.span,{...o,ref:m,style:{pointerEvents:"none"},children:fJe(c.value)?e.jsx(e.Fragment,{children:l}):i})});WQe.displayName=GQe;var xAt="SelectIcon",KQe=k.forwardRef((s,t)=>{const{__scopeSelect:r,children:n,...a}=s;return e.jsx(wn.span,{"aria-hidden":!0,...a,ref:t,children:n||"▼"})});KQe.displayName=xAt;var gAt="SelectPortal",YQe=s=>e.jsx(AI,{asChild:!0,...s});YQe.displayName=gAt;var A3="SelectContent",ZQe=k.forwardRef((s,t)=>{const r=Zj(A3,s.__scopeSelect),[n,a]=k.useState();if(Dd(()=>{a(new DocumentFragment)},[]),!r.open){const i=n;return i?Vf.createPortal(e.jsx(XQe,{scope:s.__scopeSelect,children:e.jsx(ofe.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(QQe,{...s,ref:t})});ZQe.displayName=A3;var sy=10,[XQe,Xj]=UI(A3),yAt="SelectContentImpl",vAt=kj("SelectContent.RemoveScroll"),QQe=k.forwardRef((s,t)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:x,collisionPadding:y,sticky:v,hideWhenDetached:w,avoidCollisions:b,...N}=s,S=Zj(A3,r),[T,A]=k.useState(null),[I,D]=k.useState(null),R=Ga(t,Ae=>A(Ae)),[$,F]=k.useState(null),[z,Q]=k.useState(null),K=lfe(r),[X,Z]=k.useState(!1),re=k.useRef(!1);k.useEffect(()=>{if(T)return Jme(T)},[T]),Zme();const le=k.useCallback(Ae=>{const[He,...Le]=K().map(xe=>xe.ref.current),[Ie]=Le.slice(-1),Te=document.activeElement;for(const xe of Ae)if(xe===Te||(xe==null||xe.scrollIntoView({block:"nearest"}),xe===He&&I&&(I.scrollTop=0),xe===Ie&&I&&(I.scrollTop=I.scrollHeight),xe==null||xe.focus(),document.activeElement!==Te))return},[K,I]),oe=k.useCallback(()=>le([$,T]),[le,$,T]);k.useEffect(()=>{X&&oe()},[X,oe]);const{onOpenChange:ne,triggerPointerDownPosRef:ie}=S;k.useEffect(()=>{if(T){let Ae={x:0,y:0};const He=Ie=>{var Te,xe;Ae={x:Math.abs(Math.round(Ie.pageX)-(((Te=ie.current)==null?void 0:Te.x)??0)),y:Math.abs(Math.round(Ie.pageY)-(((xe=ie.current)==null?void 0:xe.y)??0))}},Le=Ie=>{Ae.x<=10&&Ae.y<=10?Ie.preventDefault():T.contains(Ie.target)||ne(!1),document.removeEventListener("pointermove",He),ie.current=null};return ie.current!==null&&(document.addEventListener("pointermove",He),document.addEventListener("pointerup",Le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",He),document.removeEventListener("pointerup",Le,{capture:!0})}}},[T,ne,ie]),k.useEffect(()=>{const Ae=()=>ne(!1);return window.addEventListener("blur",Ae),window.addEventListener("resize",Ae),()=>{window.removeEventListener("blur",Ae),window.removeEventListener("resize",Ae)}},[ne]);const[ye,ce]=pJe(Ae=>{const He=K().filter(Te=>!Te.disabled),Le=He.find(Te=>Te.ref.current===document.activeElement),Ie=xJe(He,Ae,Le);Ie&&setTimeout(()=>Ie.ref.current.focus())}),ve=k.useCallback((Ae,He,Le)=>{const Ie=!re.current&&!Le;(S.value!==void 0&&S.value===He||Ie)&&(F(Ae),Ie&&(re.current=!0))},[S.value]),be=k.useCallback(()=>T==null?void 0:T.focus(),[T]),Ue=k.useCallback((Ae,He,Le)=>{const Ie=!re.current&&!Le;(S.value!==void 0&&S.value===He||Ie)&&Q(Ae)},[S.value]),Be=n==="popper"?Ywe:JQe,De=Be===Ywe?{side:o,sideOffset:c,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:x,collisionPadding:y,sticky:v,hideWhenDetached:w,avoidCollisions:b}:{};return e.jsx(XQe,{scope:r,content:T,viewport:I,onViewportChange:D,itemRefCallback:ve,selectedItem:$,onItemLeave:be,itemTextRefCallback:Ue,focusSelectedItem:oe,selectedItemText:z,position:n,isPositioned:X,searchRef:ye,children:e.jsx(ZF,{as:vAt,allowPinchZoom:!0,children:e.jsx(KF,{asChild:!0,trapped:S.open,onMountAutoFocus:Ae=>{Ae.preventDefault()},onUnmountAutoFocus:Vr(a,Ae=>{var He;(He=S.trigger)==null||He.focus({preventScroll:!0}),Ae.preventDefault()}),children:e.jsx(Hj,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Ae=>Ae.preventDefault(),onDismiss:()=>S.onOpenChange(!1),children:e.jsx(Be,{role:"listbox",id:S.contentId,"data-state":S.open?"open":"closed",dir:S.dir,onContextMenu:Ae=>Ae.preventDefault(),...N,...De,onPlaced:()=>Z(!0),ref:R,style:{display:"flex",flexDirection:"column",outline:"none",...N.style},onKeyDown:Vr(N.onKeyDown,Ae=>{const He=Ae.ctrlKey||Ae.altKey||Ae.metaKey;if(Ae.key==="Tab"&&Ae.preventDefault(),!He&&Ae.key.length===1&&ce(Ae.key),["ArrowUp","ArrowDown","Home","End"].includes(Ae.key)){let Ie=K().filter(Te=>!Te.disabled).map(Te=>Te.ref.current);if(["ArrowUp","End"].includes(Ae.key)&&(Ie=Ie.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ae.key)){const Te=Ae.target,xe=Ie.indexOf(Te);Ie=Ie.slice(xe+1)}setTimeout(()=>le(Ie)),Ae.preventDefault()}})})})})})})});QQe.displayName=yAt;var bAt="SelectItemAlignedPosition",JQe=k.forwardRef((s,t)=>{const{__scopeSelect:r,onPlaced:n,...a}=s,i=Zj(A3,r),l=Xj(A3,r),[o,c]=k.useState(null),[d,h]=k.useState(null),m=Ga(t,R=>h(R)),x=lfe(r),y=k.useRef(!1),v=k.useRef(!0),{viewport:w,selectedItem:b,selectedItemText:N,focusSelectedItem:S}=l,T=k.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&w&&b&&N){const R=i.trigger.getBoundingClientRect(),$=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),z=N.getBoundingClientRect();if(i.dir!=="rtl"){const Te=z.left-$.left,xe=F.left-Te,et=R.left-xe,fe=R.width+et,it=Math.max(fe,$.width),Oe=window.innerWidth-sy,Ye=f8(xe,[sy,Math.max(sy,Oe-it)]);o.style.minWidth=fe+"px",o.style.left=Ye+"px"}else{const Te=$.right-z.right,xe=window.innerWidth-F.right-Te,et=window.innerWidth-R.right-xe,fe=R.width+et,it=Math.max(fe,$.width),Oe=window.innerWidth-sy,Ye=f8(xe,[sy,Math.max(sy,Oe-it)]);o.style.minWidth=fe+"px",o.style.right=Ye+"px"}const Q=x(),K=window.innerHeight-sy*2,X=w.scrollHeight,Z=window.getComputedStyle(d),re=parseInt(Z.borderTopWidth,10),le=parseInt(Z.paddingTop,10),oe=parseInt(Z.borderBottomWidth,10),ne=parseInt(Z.paddingBottom,10),ie=re+le+X+ne+oe,ye=Math.min(b.offsetHeight*5,ie),ce=window.getComputedStyle(w),ve=parseInt(ce.paddingTop,10),be=parseInt(ce.paddingBottom,10),Ue=R.top+R.height/2-sy,Be=K-Ue,De=b.offsetHeight/2,Ae=b.offsetTop+De,He=re+le+Ae,Le=ie-He;if(He<=Ue){const Te=Q.length>0&&b===Q[Q.length-1].ref.current;o.style.bottom="0px";const xe=d.clientHeight-w.offsetTop-w.offsetHeight,et=Math.max(Be,De+(Te?be:0)+xe+oe),fe=He+et;o.style.height=fe+"px"}else{const Te=Q.length>0&&b===Q[0].ref.current;o.style.top="0px";const et=Math.max(Ue,re+w.offsetTop+(Te?ve:0)+De)+Le;o.style.height=et+"px",w.scrollTop=He-Ue+w.offsetTop}o.style.margin=`${sy}px 0`,o.style.minHeight=ye+"px",o.style.maxHeight=K+"px",n==null||n(),requestAnimationFrame(()=>y.current=!0)}},[x,i.trigger,i.valueNode,o,d,w,b,N,i.dir,n]);Dd(()=>T(),[T]);const[A,I]=k.useState();Dd(()=>{d&&I(window.getComputedStyle(d).zIndex)},[d]);const D=k.useCallback(R=>{R&&v.current===!0&&(T(),S==null||S(),v.current=!1)},[T,S]);return e.jsx(wAt,{scope:r,contentWrapper:o,shouldExpandOnScrollRef:y,onScrollButtonChange:D,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(wn.div,{...a,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});JQe.displayName=bAt;var _At="SelectPopperPosition",Ywe=k.forwardRef((s,t)=>{const{__scopeSelect:r,align:n="start",collisionPadding:a=sy,...i}=s,l=cfe(r);return e.jsx(VF,{...l,...i,ref:t,align:n,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)"}})});Ywe.displayName=_At;var[wAt,WCe]=UI(A3,{}),Zwe="SelectViewport",eJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,nonce:n,...a}=s,i=Xj(Zwe,r),l=WCe(Zwe,r),o=Ga(t,i.onViewportChange),c=k.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:n}),e.jsx(ofe.Slot,{scope:r,children:e.jsx(wn.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Vr(a.onScroll,d=>{const h=d.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:x}=l;if(x!=null&&x.current&&m){const y=Math.abs(c.current-h.scrollTop);if(y>0){const v=window.innerHeight-sy*2,w=parseFloat(m.style.minHeight),b=parseFloat(m.style.height),N=Math.max(w,b);if(N0?A:0,m.style.justifyContent="flex-end")}}}c.current=h.scrollTop})})})]})});eJe.displayName=Zwe;var tJe="SelectGroup",[jAt,NAt]=UI(tJe),kAt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=Yu();return e.jsx(jAt,{scope:r,id:a,children:e.jsx(wn.div,{role:"group","aria-labelledby":a,...n,ref:t})})});kAt.displayName=tJe;var sJe="SelectLabel",rJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=NAt(sJe,r);return e.jsx(wn.div,{id:a.id,...n,ref:t})});rJe.displayName=sJe;var _de="SelectItem",[SAt,nJe]=UI(_de),aJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,value:n,disabled:a=!1,textValue:i,...l}=s,o=Zj(_de,r),c=Xj(_de,r),d=o.value===n,[h,m]=k.useState(i??""),[x,y]=k.useState(!1),v=Ga(t,S=>{var T;return(T=c.itemRefCallback)==null?void 0:T.call(c,S,n,a)}),w=Yu(),b=k.useRef("touch"),N=()=>{a||(o.onValueChange(n),o.onOpenChange(!1))};if(n==="")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(SAt,{scope:r,value:n,disabled:a,textId:w,isSelected:d,onItemTextChange:k.useCallback(S=>{m(T=>T||((S==null?void 0:S.textContent)??"").trim())},[]),children:e.jsx(ofe.ItemSlot,{scope:r,value:n,disabled:a,textValue:h,children:e.jsx(wn.div,{role:"option","aria-labelledby":w,"data-highlighted":x?"":void 0,"aria-selected":d&&x,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:v,onFocus:Vr(l.onFocus,()=>y(!0)),onBlur:Vr(l.onBlur,()=>y(!1)),onClick:Vr(l.onClick,()=>{b.current!=="mouse"&&N()}),onPointerUp:Vr(l.onPointerUp,()=>{b.current==="mouse"&&N()}),onPointerDown:Vr(l.onPointerDown,S=>{b.current=S.pointerType}),onPointerMove:Vr(l.onPointerMove,S=>{var T;b.current=S.pointerType,a?(T=c.onItemLeave)==null||T.call(c):b.current==="mouse"&&S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Vr(l.onPointerLeave,S=>{var T;S.currentTarget===document.activeElement&&((T=c.onItemLeave)==null||T.call(c))}),onKeyDown:Vr(l.onKeyDown,S=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&S.key===" "||(uAt.includes(S.key)&&N(),S.key===" "&&S.preventDefault())})})})})});aJe.displayName=_de;var MD="SelectItemText",iJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,className:n,style:a,...i}=s,l=Zj(MD,r),o=Xj(MD,r),c=nJe(MD,r),d=pAt(MD,r),[h,m]=k.useState(null),x=Ga(t,N=>m(N),c.onItemTextChange,N=>{var S;return(S=o.itemTextRefCallback)==null?void 0:S.call(o,N,c.value,c.disabled)}),y=h==null?void 0:h.textContent,v=k.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:y},c.value),[c.disabled,c.value,y]),{onNativeOptionAdd:w,onNativeOptionRemove:b}=d;return Dd(()=>(w(v),()=>b(v)),[w,b,v]),e.jsxs(e.Fragment,{children:[e.jsx(wn.span,{id:c.textId,...i,ref:x}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?Vf.createPortal(i.children,l.valueNode):null]})});iJe.displayName=MD;var oJe="SelectItemIndicator",lJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return nJe(oJe,r).isSelected?e.jsx(wn.span,{"aria-hidden":!0,...n,ref:t}):null});lJe.displayName=oJe;var Xwe="SelectScrollUpButton",cJe=k.forwardRef((s,t)=>{const r=Xj(Xwe,s.__scopeSelect),n=WCe(Xwe,s.__scopeSelect),[a,i]=k.useState(!1),l=Ga(t,n.onScrollButtonChange);return Dd(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollTop>0;i(d)};const c=r.viewport;return o(),c.addEventListener("scroll",o),()=>c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(uJe,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});cJe.displayName=Xwe;var Qwe="SelectScrollDownButton",dJe=k.forwardRef((s,t)=>{const r=Xj(Qwe,s.__scopeSelect),n=WCe(Qwe,s.__scopeSelect),[a,i]=k.useState(!1),l=Ga(t,n.onScrollButtonChange);return Dd(()=>{if(r.viewport&&r.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,h=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[r.viewport,r.isPositioned]),a?e.jsx(uJe,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=r;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});dJe.displayName=Qwe;var uJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,onAutoScroll:n,...a}=s,i=Xj("SelectScrollButton",r),l=k.useRef(null),o=lfe(r),c=k.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return k.useEffect(()=>()=>c(),[c]),Dd(()=>{var h;const d=o().find(m=>m.ref.current===document.activeElement);(h=d==null?void 0:d.ref.current)==null||h.scrollIntoView({block:"nearest"})},[o]),e.jsx(wn.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:Vr(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(n,50))}),onPointerMove:Vr(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(n,50))}),onPointerLeave:Vr(a.onPointerLeave,()=>{c()})})}),CAt="SelectSeparator",hJe=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s;return e.jsx(wn.div,{"aria-hidden":!0,...n,ref:t})});hJe.displayName=CAt;var Jwe="SelectArrow",TAt=k.forwardRef((s,t)=>{const{__scopeSelect:r,...n}=s,a=cfe(r),i=Zj(Jwe,r),l=Xj(Jwe,r);return i.open&&l.position==="popper"?e.jsx(HF,{...a,...n,ref:t}):null});TAt.displayName=Jwe;var EAt="SelectBubbleInput",mJe=k.forwardRef(({__scopeSelect:s,value:t,...r},n)=>{const a=k.useRef(null),i=Ga(n,a),l=sB(t);return k.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&h){const m=new Event("change",{bubbles:!0});h.call(o,t),o.dispatchEvent(m)}},[l,t]),e.jsx(wn.select,{...r,style:{...WKe,...r.style},ref:i,defaultValue:t})});mJe.displayName=EAt;function fJe(s){return s===""||s===void 0}function pJe(s){const t=Ed(s),r=k.useRef(""),n=k.useRef(0),a=k.useCallback(l=>{const o=r.current+l;t(o),function c(d){r.current=d,window.clearTimeout(n.current),d!==""&&(n.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=k.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return k.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,a,i]}function xJe(s,t,r){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=r?s.indexOf(r):-1;let l=AAt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==r));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==r?c:void 0}function AAt(s,t){return s.map((r,n)=>s[(t+n)%s.length])}var MAt=qQe,gJe=HQe,IAt=WQe,LAt=KQe,PAt=YQe,yJe=ZQe,DAt=eJe,vJe=rJe,bJe=aJe,RAt=iJe,OAt=lJe,_Je=cJe,wJe=dJe,jJe=hJe;const Is=MAt,Ls=IAt,As=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(gJe,{ref:n,className:It("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),...r,children:[t,e.jsx(LAt,{asChild:!0,children:e.jsx(Wi,{className:"h-4 w-4 opacity-50"})})]}));As.displayName=gJe.displayName;const NJe=k.forwardRef(({className:s,...t},r)=>e.jsx(_Je,{ref:r,className:It("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Jf,{className:"h-4 w-4"})}));NJe.displayName=_Je.displayName;const kJe=k.forwardRef(({className:s,...t},r)=>e.jsx(wJe,{ref:r,className:It("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Wi,{className:"h-4 w-4"})}));kJe.displayName=wJe.displayName;const Ms=k.forwardRef(({className:s,children:t,position:r="popper",...n},a)=>e.jsx(PAt,{children:e.jsxs(yJe,{ref:a,className:It("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",r==="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:r,...n,children:[e.jsx(NJe,{}),e.jsx(DAt,{className:It("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(kJe,{})]})}));Ms.displayName=yJe.displayName;const FAt=k.forwardRef(({className:s,...t},r)=>e.jsx(vJe,{ref:r,className:It("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));FAt.displayName=vJe.displayName;const ct=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(bJe,{ref:n,className:It("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),...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(OAt,{children:e.jsx(Kn,{className:"h-4 w-4"})})}),e.jsx(RAt,{children:t})]}));ct.displayName=bJe.displayName;const BAt=k.forwardRef(({className:s,...t},r)=>e.jsx(jJe,{ref:r,className:It("-mx-1 my-1 h-px bg-muted",s),...t}));BAt.displayName=jJe.displayName;const zAt=s=>mt({queryKey:["public-listings",s],queryFn:async()=>{let t=V.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, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});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&&(t=t.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:r,error:n}=await t;if(n)throw n;return r}}),SJe=s=>mt({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let r=V.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, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, 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?r=r.eq("id",s):r=r.eq("slug",s);const{data:n,error:a}=await r.single();if(a)throw a;return n},enabled:!!s}),CJe=()=>Ct({mutationFn:async({listingId:s,agentId:t,firstName:r,lastName:n,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:h,message:m})=>{let x=null,y=null;if(l){const{data:N}=await V.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();N&&(x=N.id,y=N.sharing_agent_id)}const{data:v,error:w}=await V.from("listing_leads").insert({listing_id:s,agent_id:y||t,first_name:r,last_name:n,email:a,phone:i,share_id:x,referred_by_agent_id:y,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:h||null,message:m||null}).select().single();if(w)throw w;const{error:b}=await V.functions.invoke("process-listing-lead",{body:{leadId:v.id}});return b&&console.error("Error processing lead:",b),v}}),$At=()=>Ct({mutationFn:async s=>{const{error:t}=await V.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),UAt={active:"bg-emerald-500",coming_soon:"bg-blue-600",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},pRe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},qAt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function TJe(){const[s,t]=k.useState(""),[r,n]=k.useState(!1),[a,i]=k.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:l,isLoading:o}=zAt({city:s||void 0,status:a.status||void 0,propertyType:a.propertyType||void 0,minPrice:a.minPrice?Number(a.minPrice):void 0,maxPrice:a.maxPrice?Number(a.maxPrice):void 0}),c=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(m),d=()=>{i({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},h=s||a.status||a.propertyType||a.minPrice||a.maxPrice;return e.jsxs(e.Fragment,{children:[e.jsxs(nl,{children:[e.jsx("title",{children:"LevelUp Listings - Find Your Dream Home | Real Estate for Sale"}),e.jsx("meta",{name:"description",content:"Browse exclusive property listings from LevelUp real estate agents. Find homes for sale, condos, townhouses, and luxury properties. View photos, prices, and connect with agents."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings - Find Your Dream Home"}),e.jsx("meta",{property:"og:description",content:"Browse exclusive property listings from LevelUp real estate agents. Find homes for sale, view photos, and connect with agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{property:"og:locale",content:"en_US"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:"LevelUp Listings - Find Your Dream Home"}),e.jsx("meta",{name:"twitter:description",content:"Browse exclusive property listings from LevelUp real estate agents."}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("meta",{name:"keywords",content:"homes for sale, real estate, property listings, houses, condos, townhouses, luxury homes, LevelUp"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com",description:"Browse exclusive property listings from LevelUp real estate agents",potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:"https://listings.relevelup.com?q={search_term_string}"},"query-input":"required name=search_term_string"}})}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateAgent",name:"LevelUp",url:"https://relevelup.com",logo:"https://listings.relevelup.com/assets/levelup-logo-color.png"})})]}),e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("header",{className:"bg-white border-b border-gray-200 sticky top-0 z-50",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Yn,{to:"/public/listings",className:"flex items-center",children:e.jsx("img",{src:HCe,alt:"LevelUp",className:"h-8"})}),e.jsx("nav",{className:"hidden md:flex items-center gap-6",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors",children:"About LevelUp"})})]})})}),e.jsxs("section",{className:"relative bg-cover bg-center py-20 md:py-32",style:{backgroundImage:`url(${iAt})`},children:[e.jsx("div",{className:"absolute inset-0 bg-black/40"}),e.jsxs("div",{className:"relative max-w-7xl mx-auto px-4",children:[e.jsx("h1",{className:"text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-3 text-center drop-shadow-lg",children:"Find Your Perfect Home"}),e.jsx("p",{className:"text-white/90 text-center mb-10 text-lg md:text-xl drop-shadow",children:"Exclusive listings from LevelUp agents"}),e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex gap-0 shadow-2xl rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"relative flex-1 bg-white",children:[e.jsx(yn,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400"}),e.jsx(Ne,{placeholder:"Enter an address, neighborhood, city, or ZIP code",value:s,onChange:m=>t(m.target.value),className:"pl-12 h-14 md:h-16 text-base md:text-lg border-0 focus-visible:ring-0 rounded-none bg-white"})]}),e.jsx(G,{className:"h-14 md:h-16 px-6 md:px-8 rounded-none bg-blue-600 hover:bg-blue-700",children:e.jsx(yn,{className:"h-5 w-5 md:h-6 md:w-6"})})]}),e.jsx("div",{className:"flex justify-center mt-6",children:e.jsxs(G,{variant:"secondary",size:"sm",onClick:()=>n(!r),className:"gap-2 bg-white/90 hover:bg-white text-gray-700 shadow-lg",children:[e.jsx(s3,{className:"h-4 w-4"}),r?"Hide Filters":"More Filters"]})}),r&&e.jsxs("div",{className:"mt-4 p-6 bg-white rounded-lg shadow-xl",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Status"}),e.jsxs(Is,{value:a.status||"all",onValueChange:m=>i({...a,status:m==="all"?"":m}),children:[e.jsx(As,{className:"bg-white",children:e.jsx(Ls,{placeholder:"Any status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"Any status"}),Object.entries(pRe).map(([m,x])=>e.jsx(ct,{value:m,children:x},m))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Property Type"}),e.jsxs(Is,{value:a.propertyType||"all",onValueChange:m=>i({...a,propertyType:m==="all"?"":m}),children:[e.jsx(As,{className:"bg-white",children:e.jsx(Ls,{placeholder:"Any type"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"Any type"}),Object.entries(qAt).map(([m,x])=>e.jsx(ct,{value:m,children:x},m))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Min Price"}),e.jsx(Ne,{type:"number",placeholder:"No min",value:a.minPrice,onChange:m=>i({...a,minPrice:m.target.value}),className:"bg-white"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-gray-700 mb-1.5 block",children:"Max Price"}),e.jsx(Ne,{type:"number",placeholder:"No max",value:a.maxPrice,onChange:m=>i({...a,maxPrice:m.target.value}),className:"bg-white"})]})]}),h&&e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:d,className:"gap-1 text-gray-500",children:[e.jsx(vr,{className:"h-4 w-4"}),"Clear all"]})})]})]})]})]}),l&&l.length>0&&e.jsx("section",{className:"py-8 bg-white border-b border-gray-200",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Explore on Map"}),e.jsx(cAt,{listings:l,isLoading:o})]})}),e.jsx("section",{className:"py-8",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4",children:o?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5",children:[...Array(8)].map((m,x)=>e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden shadow-sm",children:[e.jsx(Fs,{className:"aspect-[4/3]"}),e.jsxs("div",{className:"p-4 space-y-3",children:[e.jsx(Fs,{className:"h-7 w-28"}),e.jsx(Fs,{className:"h-4 w-full"}),e.jsx(Fs,{className:"h-4 w-3/4"})]})]},x))}):l&&l.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center justify-between mb-6",children:e.jsxs("h2",{className:"text-xl font-semibold text-gray-900",children:[l.length," ",l.length===1?"Home":"Homes"," Available"]})}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5",children:l.map(m=>{var w,b,N;const x=((w=m.photos)==null?void 0:w.find(S=>S.is_primary))||((b=m.photos)==null?void 0:b[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`;return e.jsx(Yn,{to:v,children:e.jsxs("div",{className:"bg-white rounded-lg overflow-hidden shadow-sm hover:shadow-lg transition-shadow cursor-pointer group border border-gray-100",children:[e.jsxs("div",{className:"aspect-[4/3] relative overflow-hidden bg-gray-100",children:[x?e.jsx("img",{src:x.photo_url,alt:m.property_address||m.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",children:e.jsx(En,{className:"h-12 w-12 text-gray-300"})}),e.jsx(Ge,{className:`absolute top-2 left-2 ${UAt[m.status]} text-white border-0 text-xs font-medium px-2 py-0.5`,children:pRe[m.status]}),e.jsx("button",{className:"absolute top-2 right-2 p-2 rounded-full bg-white/80 hover:bg-white transition-colors",onClick:S=>S.preventDefault(),children:e.jsx(ci,{className:"h-5 w-5 text-gray-600"})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"text-xl font-bold text-gray-900 mb-1",children:c(m.price)}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-gray-700 mb-2",children:[m.bedrooms&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.bedrooms}),e.jsx("span",{className:"text-gray-500",children:"bds"}),e.jsx("span",{className:"text-gray-300 mx-1",children:"|"})]}),m.bathrooms&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.bathrooms}),e.jsx("span",{className:"text-gray-500",children:"ba"}),e.jsx("span",{className:"text-gray-300 mx-1",children:"|"})]}),m.square_footage&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-semibold",children:m.square_footage.toLocaleString()}),e.jsx("span",{className:"text-gray-500",children:"sqft"})]})]}),m.property_address&&e.jsx("p",{className:"text-sm text-gray-700 truncate",children:m.property_address}),e.jsxs("p",{className:"text-sm text-gray-500 truncate",children:[m.city,", ",m.state]}),m.agent&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-gray-100",children:[e.jsx("p",{className:"text-xs text-gray-500 truncate",children:m.agent.name}),((N=m.agent.brokerage)==null?void 0:N.name)&&e.jsx("p",{className:"text-xs text-gray-400 truncate",children:m.agent.brokerage.name})]})]})]})},m.id)})})]}):e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center",children:e.jsx(En,{className:"h-10 w-10 text-gray-400"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No listings found"}),e.jsx("p",{className:"text-gray-500 mb-6",children:h?"Try adjusting your search or filters":"Check back soon for new listings"}),h&&e.jsx(G,{variant:"outline",onClick:d,children:"Clear filters"})]})})}),e.jsx("footer",{className:"bg-gray-900 text-white py-10 mt-auto",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("img",{src:GCe,alt:"LevelUp",className:"h-6"})}),e.jsxs("p",{className:"text-gray-400 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-white text-sm transition-colors",children:"relevelup.com"})]})})})]})]})}const ke=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:It("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));ke.displayName="Card";const Mt=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:It("flex flex-col space-y-1.5 p-6",s),...t}));Mt.displayName="CardHeader";const Dt=k.forwardRef(({className:s,...t},r)=>e.jsx("h3",{ref:r,className:It("text-2xl font-semibold leading-none tracking-tight",s),...t}));Dt.displayName="CardTitle";const Nr=k.forwardRef(({className:s,...t},r)=>e.jsx("p",{ref:r,className:It("text-sm text-muted-foreground",s),...t}));Nr.displayName="CardDescription";const Pe=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:It("p-6 pt-0",s),...t}));Pe.displayName="CardContent";const sO=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:It("flex items-center p-6 pt-0",s),...t}));sO.displayName="CardFooter";var VAt="Label",EJe=k.forwardRef((s,t)=>e.jsx(wn.label,{...s,ref:t,onMouseDown:r=>{var a;r.target.closest("button, input, select, textarea")||((a=s.onMouseDown)==null||a.call(s,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));EJe.displayName=VAt;var AJe=EJe;const HAt=r5("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),he=k.forwardRef(({className:s,...t},r)=>e.jsx(AJe,{ref:r,className:It(HAt(),s),...t}));he.displayName=AJe.displayName;const wde="/assets/levelup-logo-color-D3mY9gCJ.png";function GAt(){const s=ec(),t=window.location.hostname;if(!(t==="listings.relevelup.com"||t.startsWith("listings.")))return null;const n=s.pathname.slice(1);return!n||n===""?e.jsx(TJe,{}):n.startsWith("public/")?null:e.jsx(WAt,{slug:n})}function WAt({slug:s}){return e.jsx(ZAt,{slug:s})}const KAt={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"},YAt={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},xRe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function ZAt({slug:s}){var F,z;const{data:t,isLoading:r}=SJe(s),n=CJe(),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState(null),S=Q=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Q),T=async Q=>{if(Q.preventDefault(),!(!a.trim()||!c.trim()||!t)){y(!0);try{await n.mutateAsync({listingId:t.id,agentId:t.agent_id,firstName:a.trim(),lastName:l.trim(),email:c.trim(),phone:h.trim()}),w(!0),ue.success("Thanks! The agent will be in touch soon.")}catch(K){console.error("Lead submission error:",K),ue.error(`Failed to submit: ${K.message||"Please try again"}`)}finally{y(!1)}}},A=(t==null?void 0:t.photos)||[],I=A.find(Q=>Q.is_primary)||A[0],D=()=>{b!==null&&N(b===0?A.length-1:b-1)},R=()=>{b!==null&&N(b===A.length-1?0:b+1)};if(r)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(Fs,{className:"h-8 w-32"})})}),e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsx(Fs,{className:"h-10 w-48 mb-6"}),e.jsx(Fs,{className:"aspect-video mb-6"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-4",children:[e.jsx(Fs,{className:"h-12 w-48"}),e.jsx(Fs,{className:"h-6 w-full"}),e.jsx(Fs,{className:"h-6 w-3/4"})]}),e.jsx(Fs,{className:"h-64"})]})]})]});if(!t)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("a",{href:"/",className:"flex items-center gap-2",children:e.jsx("img",{src:wde,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[e.jsx(En,{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-4",children:"This listing may no longer be available."}),e.jsx(G,{asChild:!0,children:e.jsx("a",{href:"/",children:"Browse All Listings"})})]})]});const $=t.property_address?`${t.property_address} - ${t.city}, ${t.state}`:`${t.city}, ${t.state} Home for Sale`;return e.jsxs(e.Fragment,{children:[e.jsxs(nl,{children:[e.jsxs("title",{children:[$," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${S(t.price)} - ${t.bedrooms||""}BD ${t.bathrooms||""}BA ${t.square_footage?t.square_footage.toLocaleString()+" sqft":""} ${xRe[t.property_type]} in ${t.city}, ${t.state}. ${((F=t.description)==null?void 0:F.slice(0,150))||""}`}),e.jsx("meta",{property:"og:title",content:$}),e.jsx("meta",{property:"og:description",content:`${S(t.price)} - ${t.bedrooms||""}BD ${t.bathrooms||""}BA in ${t.city}, ${t.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),I&&e.jsx("meta",{property:"og:image",content:I.photo_url})]}),e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card sticky top-0 z-50",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("a",{href:"/",className:"flex items-center gap-2",children:e.jsx("img",{src:wde,alt:"LevelUp",className:"h-8"})})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-6",children:[e.jsxs("a",{href:"/",className:"inline-flex items-center text-muted-foreground hover:text-foreground mb-6",children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),A.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",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:()=>N(0),children:e.jsx("img",{src:I==null?void 0:I.photo_url,alt:"Primary",className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:A.slice(1,5).map((Q,K)=>e.jsxs("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer relative",onClick:()=>N(K+1),children:[e.jsx("img",{src:Q.photo_url,alt:`Photo ${K+2}`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"}),K===3&&A.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center text-white font-semibold",children:["+",A.length-5," more"]})]},Q.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx(Ge,{className:`${KAt[t.status]} text-white border-0`,children:YAt[t.status]})}),e.jsx("h1",{className:"text-4xl font-bold text-primary mb-2",children:S(t.price)}),t.property_address&&e.jsx("p",{className:"text-xl font-medium",children:t.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Ca,{className:"h-4 w-4"}),t.city,", ",t.state,t.neighborhood&&` • ${t.neighborhood}`]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[t.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Ny,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.bedrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Beds"})]}),t.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Xf,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.bathrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baths"})]}),t.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(og,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.square_footage.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sq Ft"})]}),t.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(on,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:t.year_built}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),xRe[t.property_type]]}),t.lot_size&&e.jsxs(Ge,{variant:"secondary",children:["Lot: ",t.lot_size]}),t.has_hoa&&e.jsx(Ge,{variant:"secondary",children:"HOA"})]}),t.description&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"About This Property"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})]}),t.agent_notes&&t.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.agent_notes})]}),t.mls_link&&e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:t.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[t.agent&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Di,{className:"h-5 w-5"}),"Listing Agent"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"font-semibold text-lg",children:t.agent.name}),((z=t.agent.brokerage)==null?void 0:z.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:t.agent.brokerage.name})]})]}),e.jsxs(ke,{className:"border-primary",children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Interested in this property?"})}),e.jsx(Pe,{children:v?e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3",children:e.jsx(Vs,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"font-medium",children:"Thanks for your interest!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The listing agent will contact you soon."})]}):e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"firstName",children:"First Name *"}),e.jsx(Ne,{id:"firstName",type:"text",placeholder:"John",value:a,onChange:Q=>i(Q.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lastName",children:"Last Name"}),e.jsx(Ne,{id:"lastName",type:"text",placeholder:"Doe",value:l,onChange:Q=>o(Q.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email *"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"you@example.com",value:c,onChange:Q=>d(Q.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone"}),e.jsx(Ne,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:h,onChange:Q=>m(Q.target.value)})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:x,children:x?"Submitting...":"Get More Info"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"The listing agent will reach out to you directly."})]})})]})]})]})]}),e.jsx(fs,{open:b!==null,onOpenChange:()=>N(null),children:e.jsxs(ms,{className:"max-w-5xl p-0 bg-black/95",children:[e.jsx(ys,{className:"sr-only",children:e.jsx(gs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>N(null),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(vr,{className:"h-5 w-5"})}),b!==null&&A[b]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:A[b].photo_url,alt:`Photo ${b+1}`,className:"w-full max-h-[80vh] object-contain"}),A.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:D,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx($o,{className:"h-6 w-6"})}),e.jsx("button",{onClick:R,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(va,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/50 px-3 py-1 rounded-full text-sm",children:[b+1," / ",A.length]})]})]})]})}),e.jsx("footer",{className:"border-t py-8 mt-16",children:e.jsxs("div",{className:"container mx-auto px-4 text-center text-sm text-muted-foreground",children:[e.jsxs("p",{children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("p",{className:"mt-2",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground",children:"relevelup.com"})})]})})]})]})}function dfe({card:s,variant:t}){const r=s.brokerage_display_name||s.brokerage_logo_url,n=s.team_name||s.team_logo_url;if(!r&&!n)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 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&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})]}),n&&e.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"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 MJe=s=>mt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:r}=await V.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(r)throw r;const{data:n}=await V.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(n!=null&&n.brokerage_id){const{data:o}=await V.from("brokerages").select("name").eq("id",n.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await V.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 V.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=V.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...n||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(n==null?void 0:n.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),XAt=()=>mt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await V.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),QAt=s=>mt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s}),IJe=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("agent_cards").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ue.success("Agent card created")},onError:t=>ue.error(t.message)})},LJe=()=>{const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("agent_cards").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ue.success("Agent card updated")},onError:t=>ue.error(t.message)})},mo=async(s,t,r,n)=>{const a=new URLSearchParams(window.location.search);await V.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:r||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:{}})},JAt=async(s,t)=>{const{error:r}=await V.from("agent_card_leads").insert({card_id:s,...t});if(r)throw r},PJe=s=>mt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(r)throw r;const{data:n,error:a}=await V.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:n||[],interactions:t||[]}},enabled:!!s});function ufe({open:s,onOpenChange:t,cardId:r,type:n,agentName:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(!1),N=async S=>{if(S.preventDefault(),!i.trim()){ue.error("Please enter your name");return}b(!0);try{await JAt(r,{lead_type:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:y.trim()||void 0,intent:m||void 0}),mo(r,"lead_submitted",n),V.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:y.trim()||void 0,intent:m||void 0}}).catch(T=>console.error("Card lead notify failed:",T)),ue.success(n==="booking"?"Request sent! They'll be in touch soon.":n==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),h(""),x(""),v("")}catch{ue.error("Something went wrong. Please try again.")}finally{b(!1)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Hr,{children:n==="booking"?`Let ${a} know you'd like to connect.`:n==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:N,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-name",children:"Name *"}),e.jsx(Ne,{id:"lead-name",value:i,onChange:S=>l(S.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(Ne,{id:"lead-phone",type:"tel",value:d,onChange:S=>h(S.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-email",children:"Email"}),e.jsx(Ne,{id:"lead-email",type:"email",value:o,onChange:S=>c(S.target.value),placeholder:"you@example.com"})]}),n==="booking"&&e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(Is,{value:m,onValueChange:x,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select one"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"buy",children:"Buy a home"}),e.jsx(ct,{value:"sell",children:"Sell my home"}),e.jsx(ct,{value:"both",children:"Buy & Sell"}),e.jsx(ct,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(Ne,{id:"lead-message",value:y,onChange:S=>v(S.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(G,{type:"submit",className:"w-full rounded-2xl",disabled:w,children:w?"Sending...":"Submit"})]})]})})}const eMt=s=>mt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),tMt=s=>mt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s}),sMt=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("card_blocks").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["card-blocks",r.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",r.card_id]}),ue.success("Block added")},onError:t=>ue.error(t.message)})},rMt=()=>{const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("card_blocks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ue.success("Block updated")},onError:t=>ue.error(t.message)})},nMt=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("card_blocks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ue.success("Block removed")},onError:t=>ue.error(t.message)})};function aMt(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 iMt(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 oMt={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 lMt({block:s,variant:t}){const r=s.config;if(!r.video_url)return null;const n=r.video_url.includes("mediadelivery.net")||r.video_url.includes("bunnycdn.com"),a=iMt(r.video_url),i=n||!!a,l=n?aMt(r.video_url):a||r.video_url;return e.jsx("div",{className:oMt[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:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const cMt={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 dMt({block:s,variant:t}){const n=s.config.testimonials||[],[a,i]=k.useState(0);if(n.length===0)return null;const l=cMt[t],o=n[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(X4,{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})]})]}),n.length>1&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[e.jsx("button",{onClick:()=>i(c=>(c-1+n.length)%n.length),className:l.nav,children:e.jsx($o,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:n.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)%n.length),className:l.nav,children:e.jsx(va,{className:"h-4 w-4"})})]})]})}const uMt={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 hMt({block:s,variant:t}){const n=s.config.tags||[];if(n.length===0)return null;const a=uMt[t];return e.jsx("div",{className:a.container,children:n.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const mMt={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 fMt({block:s,cardId:t,variant:r}){const a=s.config.links||[];if(a.length===0)return null;const i=mMt[r];return e.jsx("div",{className:i.container,children:a.map((l,o)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>mo(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Qr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const eje={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 pMt({path:s,color:t,size:r=20}){return e.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:t,children:e.jsx("path",{d:s})})}const xMt={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 gMt({block:s,cardId:t,variant:r}){const a=s.config.platforms||[],i=xMt[r];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=eje[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>mo(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(pMt,{path:c.icon,color:c.color})},o)})})]})}function hfe({cardId:s,variant:t}){const{data:r}=eMt(s);if(!r||r.length===0)return null;const n=r.filter(l=>l.block_type==="social_media"&&l.is_visible),a=r.filter(l=>l.block_type!=="social_media"),i=n.length>0?{...n[0],config:{platforms:n.flatMap(l=>l.config.platforms||[])}}:null;return r.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(lMt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(dMt,{block:l,variant:t},l.id);case"specialties":return e.jsx(hMt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(fMt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(gMt,{block:i,cardId:s,variant:t})]})}async function yMt(s){try{const t=await fetch(s);if(!t.ok)return null;const r=await t.blob(),n=r.type||"image/jpeg";return new Promise(a=>{const i=new FileReader;i.onloadend=()=>{const o=i.result.split(",")[1];a({base64:o,mimeType:n})},i.onerror=()=>a(null),i.readAsDataURL(r)})}catch{return null}}function vMt(s){const t=s.trim().split(/\s+/);if(t.length<=1)return{first:t[0]||"",last:""};const r=t.pop();return{first:t.join(" "),last:r}}async function mfe(s){const{first:t,last:r}=vMt(s.name),n=["BEGIN:VCARD","VERSION:3.0",`FN:${s.name}`,`N:${r};${t};;;`];if(s.phone&&n.push(`TEL;TYPE=CELL:${s.phone}`),s.email&&n.push(`EMAIL;TYPE=INTERNET:${s.email}`),s.brokerage&&n.push(`ORG:${s.brokerage}`),n.push(`URL:${s.cardUrl}`),s.avatarUrl){const o=await yMt(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}n.push("END:VCARD");const a=new Blob([n.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),ue.success("Contact saved!")}function bMt({card:s}){var N;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),o=(S,T)=>{mo(s.id,"button_click",S),T()},c=()=>o("call",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),d=()=>o("text",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),h=()=>o("email",()=>{var S;(S=s.profile)!=null&&S.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),mo(s.id,"button_click","book"))},x=()=>{var S,T;mo(s.id,"contact_saved"),mfe({name:i,phone:(S=s.profile)==null?void 0:S.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},y=async()=>{mo(s.id,"share_event");const S=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:S})}catch{}else await navigator.clipboard.writeText(S),ue.success("Link copied!")},v=()=>{a("referral"),r(!0),mo(s.id,"button_click","refer")},w=()=>{a("connect"),r(!0),mo(s.id,"button_click","connect")},b={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(Nn,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ya,{src:s.avatar_url||void 0,alt:i}),e.jsx(kn,{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(G,{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(Cn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(G,{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(xi,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(G,{onClick:h,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(G,{onClick:m,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(on,{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(Xn,{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(dfe,{card:s,variant:"standard"}),e.jsx(hfe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(G,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Ya,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(G,{variant:"ghost",onClick:()=>{mo(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(Xn,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(G,{variant:"ghost",onClick:v,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(pr,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(G,{variant:"ghost",onClick:w,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(sl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(G,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Ec,{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((S,T)=>e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>mo(s.id,"button_click",`social_${S.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:b[S.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(ufe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function _Mt({card:s}){var N;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),o=(S,T)=>{mo(s.id,"button_click",S),T()},c=()=>o("call",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),d=()=>o("text",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),h=()=>o("email",()=>{var S;(S=s.profile)!=null&&S.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),mo(s.id,"button_click","book"))},x=()=>{var S,T;mo(s.id,"contact_saved"),mfe({name:i,phone:(S=s.profile)==null?void 0:S.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},y=async()=>{mo(s.id,"share_event");const S=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:S})}catch{}else await navigator.clipboard.writeText(S),ue.success("Link copied!")},v=()=>{a("referral"),r(!0),mo(s.id,"button_click","refer")},w=()=>{a("connect"),r(!0),mo(s.id,"button_click","connect")},b={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(Nn,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(ya,{src:s.avatar_url||void 0,alt:i}),e.jsx(kn,{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:Cn,label:"Call",handler:c},{icon:xi,label:"Text",handler:d},{icon:Vs,label:"Email",handler:h}].map(({icon:S,label:T,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(S,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:T})]},T))}),e.jsxs("button",{onClick:m,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(on,{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(Xn,{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(dfe,{card:s,variant:"luxury"}),e.jsx(hfe,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Ya,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{mo(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(Xn,{className:"h-4 w-4 text-[#c9a84c]"})," 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-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(pr,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:w,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(sl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Ec,{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((S,T)=>e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>mo(s.id,"button_click",`social_${S.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:b[S.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(ufe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function wMt({card:s}){var T,A,I,D;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((T=s.profile)==null?void 0:T.name)||"Agent",l=i.split(" ").map(R=>R[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((I=s.bold_theme_colors)==null?void 0:I.dark)||"#1a1a2e",button:((D=s.bold_theme_colors)==null?void 0:D.button)||"#ff5722"},c=(R,$)=>{const F=parseInt(R.replace("#",""),16),z=Math.max(0,(F>>16)-$),Q=Math.max(0,(F>>8&255)-$),K=Math.max(0,(F&255)-$);return`#${(z<<16|Q<<8|K).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(R,$)=>{mo(s.id,"button_click",R),$()},h=()=>d("call",()=>{var R;(R=s.profile)!=null&&R.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),m=()=>d("text",()=>{var R;(R=s.profile)!=null&&R.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),x=()=>d("email",()=>{var R;(R=s.profile)!=null&&R.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),y=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),mo(s.id,"button_click","book"))},v=()=>{var R,$;mo(s.id,"contact_saved"),mfe({name:i,phone:(R=s.profile)==null?void 0:R.phone,email:($=s.profile)==null?void 0:$.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},w=async()=>{mo(s.id,"share_event");const R=`https://cards.relevelup.com/${s.slug}`,$="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:$,url:R})}catch{}else await navigator.clipboard.writeText(R),ue.success("Link copied!")},b=()=>{a("referral"),r(!0),mo(s.id,"button_click","refer")},N=()=>{a("connect"),r(!0),mo(s.id,"button_click","connect")},S={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(Nn,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(ya,{src:s.avatar_url||void 0,alt:i}),e.jsx(kn,{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:Cn,label:"Call",handler:h},{icon:xi,label:"Text",handler:m},{icon:Vs,label:"Email",handler:x}].map(({icon:R,label:$,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(R,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:$})]},$))}),e.jsxs("button",{onClick:y,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(on,{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(Xn,{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(dfe,{card:s,variant:"bold"}),e.jsx(hfe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&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(Ya,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{mo(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(Xn,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(pr,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:N,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(sl,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:w,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(Ec,{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((R,$)=>e.jsx("a",{href:R.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>mo(s.id,"button_click",`social_${R.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:S[R.platform.toLowerCase()]||"🔗"},$))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(ufe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function jMt({card:s}){var N;const[t,r]=k.useState(!1),[n,a]=k.useState("booking"),i=((N=s.profile)==null?void 0:N.name)||"Agent",l=i.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),o=(S,T)=>{mo(s.id,"button_click",S),T()},c=()=>o("call",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`tel:${s.profile.phone}`:ue.error("Phone number not available")}),d=()=>o("text",()=>{var S;(S=s.profile)!=null&&S.phone?window.location.href=`sms:${s.profile.phone}`:ue.error("Phone number not available")}),h=()=>o("email",()=>{var S;(S=s.profile)!=null&&S.email?window.location.href=`mailto:${s.profile.email}`:ue.error("Email not available")}),m=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),r(!0),mo(s.id,"button_click","book"))},x=()=>{var S,T;mo(s.id,"contact_saved"),mfe({name:i,phone:(S=s.profile)==null?void 0:S.phone,email:(T=s.profile)==null?void 0:T.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},y=async()=>{mo(s.id,"share_event");const S=`https://cards.relevelup.com/${s.slug}`,T="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:T,url:S})}catch{}else await navigator.clipboard.writeText(S),ue.success("Link copied!")},v=()=>{a("referral"),r(!0),mo(s.id,"button_click","refer")},w=()=>{a("connect"),r(!0),mo(s.id,"button_click","connect")},b={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(Nn,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ya,{src:s.avatar_url||void 0,alt:i}),e.jsx(kn,{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:Cn,label:"Call",handler:c},{icon:xi,label:"Text",handler:d},{icon:Vs,label:"Email",handler:h}].map(({icon:S,label:T,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(S,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:T})]},T))}),e.jsxs("button",{onClick:m,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(on,{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(Xn,{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(dfe,{card:s,variant:"classic"}),e.jsx(hfe,{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:x,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Ya,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{mo(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(Xn,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,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(pr,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:w,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(sl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Ec,{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((S,T)=>e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>mo(s.id,"button_click",`social_${S.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:b[S.platform.toLowerCase()]||"🔗"},T))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(ufe,{open:t,onOpenChange:r,cardId:s.id,type:n,agentName:i})]})}function KCe({card:s}){switch(s.theme){case"luxury":return e.jsx(_Mt,{card:s});case"bold":return e.jsx(wMt,{card:s});case"classic":return e.jsx(jMt,{card:s});case"standard":default:return e.jsx(bMt,{card:s})}}function NMt(){const s=ec();k.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(kMt,{slug:t})}function kMt({slug:s}){return e.jsx(SMt,{slug:s})}function SMt({slug:s}){var i;const{data:t,isLoading:r,error:n}=MJe(s);if(k.useEffect(()=>{t!=null&&t.id&&mo(t.id,"card_view")},[t==null?void 0:t.id]),r)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(Fs,{className:"h-28 w-28 rounded-full"}),e.jsx(Fs,{className:"h-6 w-48"}),e.jsx(Fs,{className:"h-4 w-36"})]}),e.jsx(Fs,{className:"h-12 w-full"}),e.jsx(Fs,{className:"h-12 w-full"})]})});if(n||!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(nl,{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(KCe,{card:t})]})}function DJe({presentationId:s,ctaLabel:t,agentName:r,prefillName:n,prefillEmail:a,prefillPhone:i}){const[l,o]=k.useState(n||""),[c,d]=k.useState(a||""),[h,m]=k.useState(i||""),[x,y]=k.useState(""),[v,w]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),A=async I=>{if(I.preventDefault(),!l.trim()){ue.error("Please enter your name");return}N(!0);try{const{error:D}=await V.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:h.trim()||null,intent:x||null,message:v.trim()||null});if(D)throw D;try{await V.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{}V.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:h.trim()||void 0,intent:x||void 0,message:v.trim()||void 0}}).catch(R=>console.error("Presentation lead notify failed:",R)),T(!0)}catch{ue.error("Something went wrong. Please try again.")}finally{N(!1)}};return S?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(Kn,{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:r?`${r} 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(he,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(Ne,{id:"pres-lead-name",value:l,onChange:I=>o(I.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(Ne,{id:"pres-lead-phone",type:"tel",value:h,onChange:I=>m(I.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(Ne,{id:"pres-lead-email",type:"email",value:c,onChange:I=>d(I.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(Is,{value:x,onValueChange:y,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select one"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"buy",children:"Buy a home"}),e.jsx(ct,{value:"sell",children:"Sell my home"}),e.jsx(ct,{value:"both",children:"Buy & Sell"}),e.jsx(ct,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(Ne,{id:"pres-lead-message",value:v,onChange:I=>w(I.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(G,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:b,children:b?"Sending...":t})]})}function CMt(){const s=ec();k.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(TMt,{shareToken:t})}function TMt({shareToken:s}){var v;const[t,r]=k.useState(null),[n,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>{d()},[s]);const d=async()=>{const{data:w,error:b}=await V.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(b||!w){c(!0),a(!1);return}const{data:N}=await V.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",w.owner_user_id).single();let S;if(N!=null&&N.brokerage_id){const{data:A}=await V.from("brokerages").select("name").eq("id",N.brokerage_id).single();S=(A==null?void 0:A.name)||void 0}let T=null;if(w.contact_id){const{data:A}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",w.contact_id).single();T=A}r({...w,owner_name:N==null?void 0:N.name,owner_email:N==null?void 0:N.email,owner_phone:N==null?void 0:N.phone,owner_avatar:N==null?void 0:N.avatar_url,owner_title:(N==null?void 0:N.title)||void 0,brokerage_name:S,contact_name:T?[T.first_name,T.last_name].filter(Boolean).join(" "):void 0,contact_email:(T==null?void 0:T.email)||void 0,contact_phone:(T==null?void 0:T.phone)||void 0}),a(!1);try{await V.rpc("log_presentation_view",{p_presentation_id:w.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},h=async()=>{if(t){try{await V.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")}},m=w=>{const b=w.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(b)return`https://www.youtube.com/embed/${b[1]}?rel=0`;if(w.includes("iframe.mediadelivery.net/play/")){const T=w.replace("/play/","/embed/"),A=T.includes("?")?"&":"?";return`${T}${A}responsive=true`}if(w.includes("iframe.mediadelivery.net")){const T=w.includes("?")?"&":"?";return`${w}${T}responsive=true`}const N=w.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(N)return`https://www.loom.com/embed/${N[1]}`;const S=w.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return S?`https://iframe.mediadelivery.net/embed/${S[1]}/${S[2]}?responsive=true`:w};if(n)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(Fs,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Fs,{className:"h-64 w-full"}),e.jsx(Fs,{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 x=t.sections.filter(w=>w.is_visible!==!1),y=x[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:[y!=null&&y.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:m(y.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"})}):y!=null&&y.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:y.image_url,alt:y.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:y==null?void 0:y.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:y==null?void 0:y.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:y==null?void 0:y.description})]}),(y==null?void 0:y.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:y.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:x.map((w,b)=>e.jsx("button",{onClick:()=>l(b),className:It("w-full text-left p-4 rounded-xl border transition-all",i===b?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(b+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:w.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:w.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:w.description})]})]})},b))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(v=t.cta_url)!=null&&v.trim()?e.jsxs(G,{size:"lg",onClick:h,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(Qr,{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(DJe,{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 yg=()=>{const s=sa();return mt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:r}=await V.from("team_members").select("id, team_id, role").eq("user_id",s).maybeSingle();if(console.log("[useUserTeam] membership query:",{userId:s,membership:t,error:r}),r)throw r;if(!t)return null;const{data:n,error:a}=await V.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:n}},enabled:!!s,staleTime:5*60*1e3})};function EMt(){const{user:s}=js(),t=sa(),{data:r}=yg();return mt({queryKey:["open-houses",t,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:a}=await V.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=n||[];if((r==null?void 0:r.role)==="team_leader"&&r.teamId){const{data:l,error:o}=await V.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(m=>m.agent_id))],d={};if(c.length>0){const{data:m}=await V.from("profiles").select("id, name").in("id",c);m==null||m.forEach(x=>{x.name&&(d[x.id]=x.name)})}const h=l.map(m=>({...m,agent_name:d[m.agent_id]||void 0}));i=[...i,...h]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function kUs(s){const{user:t}=js();return mt({queryKey:["open-house",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_houses").select("*").eq("id",s).single();if(n)throw n;return r},enabled:!!t&&!!s})}function RJe(s){const{user:t}=js(),r=Xt();return k.useEffect(()=>{if(!s)return;const n=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=V.channel(n).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{r.invalidateQueries({queryKey:["open-house-visitors",s]}),r.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{V.removeChannel(a)}},[s,r]),mt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:n,error:a}=await V.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return n},enabled:!!t&&!!s})}function AMt(){const s=Xt(),t=sa();return Ct({mutationFn:async r=>{const{data:n,error:a}=await V.from("open_houses").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),cn({title:"Open house created!"})},onError:r=>{cn({title:"Error",description:r.message,variant:"destructive"})}})}function OJe(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{error:n}=await V.from("open_houses").update(r).eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",r.id]})}})}function MMt(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("open_houses").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),cn({title:"Open house deleted"})}})}function IMt(s){return mt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:r}=await V.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(r)throw r;let n=null;if(t.agent_id){const{data:a}=await V.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(n=a.slug)}return{...t,agent_card_slug:n}},enabled:!!s})}function LMt(s){const{user:t}=js();return mt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;return r},enabled:!!t&&!!s})}function PMt(s){return mt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:r}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(r)throw r;return t},enabled:!!s})}function DMt(){return Ct({mutationFn:async s=>{const{error:t}=await V.from("open_house_survey_responses").insert(s);if(t)throw t}})}function RMt(s){const{user:t}=js();return mt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const a=(r||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await V.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:r,responses:i||[]}},enabled:!!t&&!!s})}function OMt(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("open_house_survey_questions").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function FMt(){const s=Xt();return Ct({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await V.from("open_house_survey_questions").update(n).eq("id",t);if(a)throw a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function BMt(){const s=Xt();return Ct({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await V.from("open_house_survey_questions").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function zMt(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.rpc("seed_default_survey_questions",{_open_house_id:t});if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["survey-questions",r]})}})}function $Mt(){return Ct({mutationFn:async s=>{const{data:t,error:r}=await V.from("open_house_visitors").insert(s).select("id").single();if(r)throw r;return t}})}function UMt(){return Ct({mutationFn:async({visitor_id:s,...t})=>{const{error:r}=await V.from("open_house_visitors").update(t).eq("id",s);if(r)throw r}})}function qMt(){return Ct({mutationFn:async s=>{await V.rpc("increment_open_house_scan",{_slug:s})}})}async function FJe(s){const{data:t,error:r}=await V.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const n=t||[];if(n.length===0)return[];const a=n.map(c=>c.id),{data:i,error:l}=await V.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var h;const d=c;(o[h=d.room_id]||(o[h]=[])).push(d)}),n.map(c=>({...c,media:o[c.id]||[]}))}function VMt(s){const{user:t}=js();return mt({queryKey:["open-house-rooms",s],queryFn:()=>FJe(s),enabled:!!t&&!!s})}function HMt(s){return mt({queryKey:["public-open-house-rooms",s],queryFn:()=>FJe(s),enabled:!!s})}function GMt(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("open_house_rooms").insert(t).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function WMt(){const s=Xt();return Ct({mutationFn:async({id:t,open_house_id:r,...n})=>{const{error:a}=await V.from("open_house_rooms").update(n).eq("id",t);if(a)throw a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function KMt(){const s=Xt();return Ct({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await V.from("open_house_rooms").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function YMt(){const s=Xt();return Ct({mutationFn:async({open_house_id:t,...r})=>{const{data:n,error:a}=await V.from("open_house_room_media").insert(r).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function ZMt(){const s=Xt();return Ct({mutationFn:async({id:t,open_house_id:r})=>{const{error:n}=await V.from("open_house_room_media").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function XMt(s){const{user:t}=js();return mt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return r||[]},enabled:!!t&&!!s})}function QMt(){const s=Xt();return Ct({mutationFn:async({id:t,status:r,open_house_id:n})=>{const{error:a}=await V.from("open_house_leads").update({status:r}).eq("id",t);if(a)throw a;return{open_house_id:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var ffe="Switch",[JMt,SUs]=pd(ffe),[eIt,tIt]=JMt(ffe),BJe=k.forwardRef((s,t)=>{const{__scopeSwitch:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:h,...m}=s,[x,y]=k.useState(null),v=Ga(t,T=>y(T)),w=k.useRef(!1),b=x?h||!!x.closest("form"):!0,[N,S]=Sh({prop:a,defaultProp:i??!1,onChange:d,caller:ffe});return e.jsxs(eIt,{scope:r,checked:N,disabled:o,children:[e.jsx(wn.button,{type:"button",role:"switch","aria-checked":N,"aria-required":l,"data-state":qJe(N),"data-disabled":o?"":void 0,disabled:o,value:c,...m,ref:v,onClick:Vr(s.onClick,T=>{S(A=>!A),b&&(w.current=T.isPropagationStopped(),w.current||T.stopPropagation())})}),b&&e.jsx(UJe,{control:x,bubbles:!w.current,name:n,value:c,checked:N,required:l,disabled:o,form:h,style:{transform:"translateX(-100%)"}})]})});BJe.displayName=ffe;var zJe="SwitchThumb",$Je=k.forwardRef((s,t)=>{const{__scopeSwitch:r,...n}=s,a=tIt(zJe,r);return e.jsx(wn.span,{"data-state":qJe(a.checked),"data-disabled":a.disabled?"":void 0,...n,ref:t})});$Je.displayName=zJe;var sIt="SwitchBubbleInput",UJe=k.forwardRef(({__scopeSwitch:s,control:t,checked:r,bubbles:n=!0,...a},i)=>{const l=k.useRef(null),o=Ga(l,i),c=sB(r),d=UF(t);return k.useEffect(()=>{const h=l.current;if(!h)return;const m=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==r&&y){const v=new Event("click",{bubbles:n});y.call(h,r),h.dispatchEvent(v)}},[c,r,n]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});UJe.displayName=sIt;function qJe(s){return s?"checked":"unchecked"}var VJe=BJe,rIt=$Je;const _r=k.forwardRef(({className:s,...t},r)=>e.jsx(VJe,{className:It("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:r,children:e.jsx(rIt,{className:It("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")})}));_r.displayName=VJe.displayName;function ma(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 Cl(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Vl(s,t){const r=ma(s);return isNaN(t)?Cl(s,NaN):(t&&r.setDate(r.getDate()+t),r)}function gf(s,t){const r=ma(s);if(isNaN(t))return Cl(s,NaN);if(!t)return r;const n=r.getDate(),a=Cl(s,r.getTime());a.setMonth(r.getMonth()+t+1,0);const i=a.getDate();return n>=i?a:(r.setFullYear(a.getFullYear(),a.getMonth(),n),r)}function HJe(s,t){const r=+ma(s);return Cl(s,r+t)}const YCe=6048e5,nIt=864e5,pfe=6e4,rB=36e5,aIt=1e3,V9=43200,gRe=1440;function yRe(s,t){return HJe(s,t*rB)}let iIt={};function Qj(){return iIt}function jm(s,t){var o,c,d,h;const r=Qj(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,a=ma(s),i=a.getDay(),l=(i=a.getTime()?r+1:t.getTime()>=l.getTime()?r:r-1}function yf(s){const t=ma(s);return t.setHours(0,0,0,0),t}function Aj(s){const t=ma(s),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+s-+r}function $p(s,t){const r=yf(s),n=yf(t),a=+r-Aj(r),i=+n-Aj(n);return Math.round((a-i)/nIt)}function oIt(s){const t=GJe(s),r=Cl(s,0);return r.setFullYear(t,0,4),r.setHours(0,0,0,0),Ib(r)}function $E(s,t){return HJe(s,t*pfe)}function e4(s,t){const r=t*7;return Vl(s,r)}function lIt(s,t){return gf(s,t*12)}function cIt(s){let t;return s.forEach(function(r){const n=ma(r);(t===void 0||t{const n=ma(r);(!t||t>n||isNaN(+n))&&(t=n)}),t||new Date(NaN)}function nce(s,t){const r=ma(s),n=ma(t),a=r.getTime()-n.getTime();return a<0?-1:a>0?1:a}function ZCe(s){return Cl(s,Date.now())}function Ol(s,t){const r=yf(s),n=yf(t);return+r==+n}function XCe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function tje(s){if(!XCe(s)&&typeof s!="number")return!1;const t=ma(s);return!isNaN(Number(t))}function kM(s,t){const r=ma(s),n=ma(t),a=r.getFullYear()-n.getFullYear(),i=r.getMonth()-n.getMonth();return a*12+i}function uIt(s,t,r){const n=jm(s,r),a=jm(t,r),i=+n-Aj(n),l=+a-Aj(a);return Math.round((i-l)/YCe)}function pg(s,t){const r=ma(s),n=ma(t),a=vRe(r,n),i=Math.abs($p(r,n));r.setDate(r.getDate()-a*i);const l=+(vRe(r,n)===-a),o=a*(i-l);return o===0?0:o}function vRe(s,t){const r=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 r<0?-1:r>0?1:r}function WJe(s){return t=>{const r=Math.trunc,n=r(t);return n===0?0:n}}function KJe(s,t){return+ma(s)-+ma(t)}function hIt(s,t,r){const n=KJe(s,t)/rB;return WJe()(n)}function mIt(s){const t=ma(s);return t.setHours(23,59,59,999),t}function qx(s){const t=ma(s),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}function fIt(s){const t=ma(s);return+mIt(t)==+qx(t)}function pIt(s,t){const r=ma(s),n=ma(t),a=nce(r,n),i=Math.abs(kM(r,n));let l;if(i<1)l=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-a*i);let o=nce(r,n)===-a;fIt(ma(s))&&i===1&&nce(s,n)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function xIt(s,t,r){const n=KJe(s,t)/1e3;return WJe()(n)}function gIt(s,t){const r=ma(s.start),n=ma(s.end);let a=+r>+n;const i=a?+r:+n,l=a?n:r;l.setHours(0,0,0,0);let o=1;const c=[];for(;+l<=i;)c.push(ma(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function $c(s){const t=ma(s);return t.setDate(1),t.setHours(0,0,0,0),t}function YJe(s){const t=ma(s),r=Cl(s,0);return r.setFullYear(t.getFullYear(),0,1),r.setHours(0,0,0,0),r}function xfe(s,t){var o,c,d,h;const r=Qj(),n=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??r.weekStartsOn??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,a=ma(s),i=a.getDay(),l=(i{let n;const a=yIt[s];return typeof a=="string"?n=a:t===1?n=a.one:n=a.other.replace("{{count}}",t.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function fve(s){return(t={})=>{const r=t.width?String(t.width):s.defaultWidth;return s.formats[r]||s.formats[s.defaultWidth]}}const bIt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},_It={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},wIt={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},jIt={date:fve({formats:bIt,defaultWidth:"full"}),time:fve({formats:_It,defaultWidth:"full"}),dateTime:fve({formats:wIt,defaultWidth:"full"})},NIt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},kIt=(s,t,r,n)=>NIt[s];function K6(s){return(t,r)=>{const n=r!=null&&r.context?String(r.context):"standalone";let a;if(n==="formatting"&&s.formattingValues){const l=s.defaultFormattingWidth||s.defaultWidth,o=r!=null&&r.width?String(r.width):l;a=s.formattingValues[o]||s.formattingValues[l]}else{const l=s.defaultWidth,o=r!=null&&r.width?String(r.width):s.defaultWidth;a=s.values[o]||s.values[l]}const i=s.argumentCallback?s.argumentCallback(t):t;return a[i]}}const SIt={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},CIt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},TIt={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"]},EIt={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"]},AIt={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"}},MIt={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"}},IIt=(s,t)=>{const r=Number(s),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},LIt={ordinalNumber:IIt,era:K6({values:SIt,defaultWidth:"wide"}),quarter:K6({values:CIt,defaultWidth:"wide",argumentCallback:s=>s-1}),month:K6({values:TIt,defaultWidth:"wide"}),day:K6({values:EIt,defaultWidth:"wide"}),dayPeriod:K6({values:AIt,defaultWidth:"wide",formattingValues:MIt,defaultFormattingWidth:"wide"})};function Y6(s){return(t,r={})=>{const n=r.width,a=n&&s.matchPatterns[n]||s.matchPatterns[s.defaultMatchWidth],i=t.match(a);if(!i)return null;const l=i[0],o=n&&s.parsePatterns[n]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(o)?DIt(o,m=>m.test(l)):PIt(o,m=>m.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=r.valueCallback?r.valueCallback(d):d;const h=t.slice(l.length);return{value:d,rest:h}}}function PIt(s,t){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)&&t(s[r]))return r}function DIt(s,t){for(let r=0;r{const n=t.match(s.matchPattern);if(!n)return null;const a=n[0],i=t.match(s.parsePattern);if(!i)return null;let l=s.valueCallback?s.valueCallback(i[0]):i[0];l=r.valueCallback?r.valueCallback(l):l;const o=t.slice(a.length);return{value:l,rest:o}}}const OIt=/^(\d+)(th|st|nd|rd)?/i,FIt=/\d+/i,BIt={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},zIt={any:[/^b/i,/^(a|c)/i]},$It={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},UIt={any:[/1/i,/2/i,/3/i,/4/i]},qIt={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},VIt={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]},HIt={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},GIt={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]},WIt={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},KIt={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}},YIt={ordinalNumber:RIt({matchPattern:OIt,parsePattern:FIt,valueCallback:s=>parseInt(s,10)}),era:Y6({matchPatterns:BIt,defaultMatchWidth:"wide",parsePatterns:zIt,defaultParseWidth:"any"}),quarter:Y6({matchPatterns:$It,defaultMatchWidth:"wide",parsePatterns:UIt,defaultParseWidth:"any",valueCallback:s=>s+1}),month:Y6({matchPatterns:qIt,defaultMatchWidth:"wide",parsePatterns:VIt,defaultParseWidth:"any"}),day:Y6({matchPatterns:HIt,defaultMatchWidth:"wide",parsePatterns:GIt,defaultParseWidth:"any"}),dayPeriod:Y6({matchPatterns:WIt,defaultMatchWidth:"any",parsePatterns:KIt,defaultParseWidth:"any"})},gfe={code:"en-US",formatDistance:vIt,formatLong:jIt,formatRelative:kIt,localize:LIt,match:YIt,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ZIt(s){const t=ma(s);return $p(t,YJe(t))+1}function QCe(s){const t=ma(s),r=+Ib(t)-+oIt(t);return Math.round(r/YCe)+1}function JCe(s,t){var h,m,x,y;const r=ma(s),n=r.getFullYear(),a=Qj(),i=(t==null?void 0:t.firstWeekContainsDate)??((m=(h=t==null?void 0:t.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??a.firstWeekContainsDate??((y=(x=a.locale)==null?void 0:x.options)==null?void 0:y.firstWeekContainsDate)??1,l=Cl(s,0);l.setFullYear(n+1,0,i),l.setHours(0,0,0,0);const o=jm(l,t),c=Cl(s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=jm(c,t);return r.getTime()>=o.getTime()?n+1:r.getTime()>=d.getTime()?n:n-1}function XIt(s,t){var o,c,d,h;const r=Qj(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??r.firstWeekContainsDate??((h=(d=r.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??1,a=JCe(s,t),i=Cl(s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),jm(i,t)}function e4e(s,t){const r=ma(s),n=+jm(r,t)-+XIt(r,t);return Math.round(n/YCe)+1}function kl(s,t){const r=s<0?"-":"",n=Math.abs(s).toString().padStart(t,"0");return r+n}const R_={y(s,t){const r=s.getFullYear(),n=r>0?r:1-r;return kl(t==="yy"?n%100:n,t.length)},M(s,t){const r=s.getMonth();return t==="M"?String(r+1):kl(r+1,2)},d(s,t){return kl(s.getDate(),t.length)},a(s,t){const r=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(s,t){return kl(s.getHours()%12||12,t.length)},H(s,t){return kl(s.getHours(),t.length)},m(s,t){return kl(s.getMinutes(),t.length)},s(s,t){return kl(s.getSeconds(),t.length)},S(s,t){const r=t.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,r-3));return kl(a,t.length)}},KT={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},bRe={G:function(s,t,r){const n=s.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});case"GGGG":default:return r.era(n,{width:"wide"})}},y:function(s,t,r){if(t==="yo"){const n=s.getFullYear(),a=n>0?n:1-n;return r.ordinalNumber(a,{unit:"year"})}return R_.y(s,t)},Y:function(s,t,r,n){const a=JCe(s,n),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return kl(l,2)}return t==="Yo"?r.ordinalNumber(i,{unit:"year"}):kl(i,t.length)},R:function(s,t){const r=GJe(s);return kl(r,t.length)},u:function(s,t){const r=s.getFullYear();return kl(r,t.length)},Q:function(s,t,r){const n=Math.ceil((s.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return kl(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(s,t,r){const n=Math.ceil((s.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return kl(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(s,t,r){const n=s.getMonth();switch(t){case"M":case"MM":return R_.M(s,t);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(s,t,r){const n=s.getMonth();switch(t){case"L":return String(n+1);case"LL":return kl(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(s,t,r,n){const a=e4e(s,n);return t==="wo"?r.ordinalNumber(a,{unit:"week"}):kl(a,t.length)},I:function(s,t,r){const n=QCe(s);return t==="Io"?r.ordinalNumber(n,{unit:"week"}):kl(n,t.length)},d:function(s,t,r){return t==="do"?r.ordinalNumber(s.getDate(),{unit:"date"}):R_.d(s,t)},D:function(s,t,r){const n=ZIt(s);return t==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):kl(n,t.length)},E:function(s,t,r){const n=s.getDay();switch(t){case"E":case"EE":case"EEE":return r.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(n,{width:"short",context:"formatting"});case"EEEE":default:return r.day(n,{width:"wide",context:"formatting"})}},e:function(s,t,r,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return kl(i,2);case"eo":return r.ordinalNumber(i,{unit:"day"});case"eee":return r.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(a,{width:"short",context:"formatting"});case"eeee":default:return r.day(a,{width:"wide",context:"formatting"})}},c:function(s,t,r,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return kl(i,t.length);case"co":return r.ordinalNumber(i,{unit:"day"});case"ccc":return r.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(a,{width:"narrow",context:"standalone"});case"cccccc":return r.day(a,{width:"short",context:"standalone"});case"cccc":default:return r.day(a,{width:"wide",context:"standalone"})}},i:function(s,t,r){const n=s.getDay(),a=n===0?7:n;switch(t){case"i":return String(a);case"ii":return kl(a,t.length);case"io":return r.ordinalNumber(a,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});case"iiii":default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(s,t,r){const a=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,t,r){const n=s.getHours();let a;switch(n===12?a=KT.noon:n===0?a=KT.midnight:a=n/12>=1?"pm":"am",t){case"b":case"bb":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,t,r){const n=s.getHours();let a;switch(n>=17?a=KT.evening:n>=12?a=KT.afternoon:n>=4?a=KT.morning:a=KT.night,t){case"B":case"BB":case"BBB":return r.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,t,r){if(t==="ho"){let n=s.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return R_.h(s,t)},H:function(s,t,r){return t==="Ho"?r.ordinalNumber(s.getHours(),{unit:"hour"}):R_.H(s,t)},K:function(s,t,r){const n=s.getHours()%12;return t==="Ko"?r.ordinalNumber(n,{unit:"hour"}):kl(n,t.length)},k:function(s,t,r){let n=s.getHours();return n===0&&(n=24),t==="ko"?r.ordinalNumber(n,{unit:"hour"}):kl(n,t.length)},m:function(s,t,r){return t==="mo"?r.ordinalNumber(s.getMinutes(),{unit:"minute"}):R_.m(s,t)},s:function(s,t,r){return t==="so"?r.ordinalNumber(s.getSeconds(),{unit:"second"}):R_.s(s,t)},S:function(s,t){return R_.S(s,t)},X:function(s,t,r){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return wRe(n);case"XXXX":case"XX":return zC(n);case"XXXXX":case"XXX":default:return zC(n,":")}},x:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"x":return wRe(n);case"xxxx":case"xx":return zC(n);case"xxxxx":case"xxx":default:return zC(n,":")}},O:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+_Re(n,":");case"OOOO":default:return"GMT"+zC(n,":")}},z:function(s,t,r){const n=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+_Re(n,":");case"zzzz":default:return"GMT"+zC(n,":")}},t:function(s,t,r){const n=Math.trunc(s.getTime()/1e3);return kl(n,t.length)},T:function(s,t,r){const n=s.getTime();return kl(n,t.length)}};function _Re(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=Math.trunc(n/60),i=n%60;return i===0?r+String(a):r+String(a)+t+kl(i,2)}function wRe(s,t){return s%60===0?(s>0?"-":"+")+kl(Math.abs(s)/60,2):zC(s,t)}function zC(s,t=""){const r=s>0?"-":"+",n=Math.abs(s),a=kl(Math.trunc(n/60),2),i=kl(n%60,2);return r+a+t+i}const jRe=(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"})}},XJe=(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"})}},QIt=(s,t)=>{const r=s.match(/(P+)(p+)?/)||[],n=r[1],a=r[2];if(!a)return jRe(s,t);let i;switch(n){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}}",jRe(n,t)).replace("{{time}}",XJe(a,t))},sje={p:XJe,P:QIt},JIt=/^D+$/,eLt=/^Y+$/,tLt=["D","DD","YY","YYYY"];function QJe(s){return JIt.test(s)}function JJe(s){return eLt.test(s)}function rje(s,t,r){const n=sLt(s,t,r);if(console.warn(n),tLt.includes(s))throw new RangeError(n)}function sLt(s,t,r){const n=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${t}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const rLt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,nLt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,aLt=/^'([^]*?)'?$/,iLt=/''/g,oLt=/[a-zA-Z]/;function _s(s,t,r){var h,m,x,y,v,w,b,N;const n=Qj(),a=(r==null?void 0:r.locale)??n.locale??gfe,i=(r==null?void 0:r.firstWeekContainsDate)??((m=(h=r==null?void 0:r.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??n.firstWeekContainsDate??((y=(x=n.locale)==null?void 0:x.options)==null?void 0:y.firstWeekContainsDate)??1,l=(r==null?void 0:r.weekStartsOn)??((w=(v=r==null?void 0:r.locale)==null?void 0:v.options)==null?void 0:w.weekStartsOn)??n.weekStartsOn??((N=(b=n.locale)==null?void 0:b.options)==null?void 0:N.weekStartsOn)??0,o=ma(s);if(!tje(o))throw new RangeError("Invalid time value");let c=t.match(nLt).map(S=>{const T=S[0];if(T==="p"||T==="P"){const A=sje[T];return A(S,a.formatLong)}return S}).join("").match(rLt).map(S=>{if(S==="''")return{isToken:!1,value:"'"};const T=S[0];if(T==="'")return{isToken:!1,value:lLt(S)};if(bRe[T])return{isToken:!0,value:S};if(T.match(oLt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+T+"`");return{isToken:!1,value:S}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(S=>{if(!S.isToken)return S.value;const T=S.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&JJe(T)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&QJe(T))&&rje(T,t,String(s));const A=bRe[T[0]];return A(o,T,a.localize,d)}).join("")}function lLt(s){const t=s.match(aLt);return t?t[1].replace(iLt,"'"):s}function cLt(s,t,r){const n=Qj(),a=(r==null?void 0:r.locale)??n.locale??gfe,i=2520,l=nce(s,t);if(isNaN(l))throw new RangeError("Invalid time value");const o=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:l});let c,d;l>0?(c=ma(t),d=ma(s)):(c=ma(s),d=ma(t));const h=xIt(d,c),m=(Aj(d)-Aj(c))/1e3,x=Math.round((h-m)/60);let y;if(x<2)return r!=null&&r.includeSeconds?h<5?a.formatDistance("lessThanXSeconds",5,o):h<10?a.formatDistance("lessThanXSeconds",10,o):h<20?a.formatDistance("lessThanXSeconds",20,o):h<40?a.formatDistance("halfAMinute",0,o):h<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):x===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",x,o);if(x<45)return a.formatDistance("xMinutes",x,o);if(x<90)return a.formatDistance("aboutXHours",1,o);if(xn.getTime()}function I3(s,t){const r=ma(s),n=ma(t);return+r<+n}function xLt(s){return+ma(s)>Date.now()}function gLt(s,t){const r=t instanceof Date?Cl(t,0):new t(0);return r.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),r.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),r}const yLt=10;class eet{constructor(){Gn(this,"subPriority",0)}validate(t,r){return!0}}class vLt extends eet{constructor(t,r,n,a,i){super(),this.value=t,this.validateValue=r,this.setValue=n,this.priority=a,i&&(this.subPriority=i)}validate(t,r){return this.validateValue(t,this.value,r)}set(t,r,n){return this.setValue(t,r,this.value,n)}}class bLt extends eet{constructor(){super(...arguments);Gn(this,"priority",yLt);Gn(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:Cl(r,gLt(r,Date))}}class pl{run(t,r,n,a){const i=this.parse(t,r,n,a);return i?{setter:new vLt(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,r,n){return!0}}class _Lt extends pl{constructor(){super(...arguments);Gn(this,"priority",140);Gn(this,"incompatibleTokens",["R","u","t","T"])}parse(r,n,a){switch(n){case"G":case"GG":case"GGG":return a.era(r,{width:"abbreviated"})||a.era(r,{width:"narrow"});case"GGGGG":return a.era(r,{width:"narrow"});case"GGGG":default:return a.era(r,{width:"wide"})||a.era(r,{width:"abbreviated"})||a.era(r,{width:"narrow"})}}set(r,n,a){return n.era=a,r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}const Xd={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}/},$0={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 Qd(s,t){return s&&{value:t(s.value),rest:s.rest}}function ld(s,t){const r=t.match(s);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function U0(s,t){const r=t.match(s);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};const n=r[1]==="+"?1:-1,a=r[2]?parseInt(r[2],10):0,i=r[3]?parseInt(r[3],10):0,l=r[5]?parseInt(r[5],10):0;return{value:n*(a*rB+i*pfe+l*aIt),rest:t.slice(r[0].length)}}function tet(s){return ld(Xd.anyDigitsSigned,s)}function Rd(s,t){switch(s){case 1:return ld(Xd.singleDigit,t);case 2:return ld(Xd.twoDigits,t);case 3:return ld(Xd.threeDigits,t);case 4:return ld(Xd.fourDigits,t);default:return ld(new RegExp("^\\d{1,"+s+"}"),t)}}function jde(s,t){switch(s){case 1:return ld(Xd.singleDigitSigned,t);case 2:return ld(Xd.twoDigitsSigned,t);case 3:return ld(Xd.threeDigitsSigned,t);case 4:return ld(Xd.fourDigitsSigned,t);default:return ld(new RegExp("^-?\\d{1,"+s+"}"),t)}}function t4e(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 set(s,t){const r=t>0,n=r?t:1-t;let a;if(n<=50)a=s||100;else{const i=n+50,l=Math.trunc(i/100)*100,o=s>=i%100;a=s+l-(o?100:0)}return r?a:1-a}function ret(s){return s%400===0||s%4===0&&s%100!==0}class wLt extends pl{constructor(){super(...arguments);Gn(this,"priority",130);Gn(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(r,n,a){const i=l=>({year:l,isTwoDigitYear:n==="yy"});switch(n){case"y":return Qd(Rd(4,r),i);case"yo":return Qd(a.ordinalNumber(r,{unit:"year"}),i);default:return Qd(Rd(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a){const i=r.getFullYear();if(a.isTwoDigitYear){const o=set(a.year,i);return r.setFullYear(o,0,1),r.setHours(0,0,0,0),r}const l=!("era"in n)||n.era===1?a.year:1-a.year;return r.setFullYear(l,0,1),r.setHours(0,0,0,0),r}}class jLt extends pl{constructor(){super(...arguments);Gn(this,"priority",130);Gn(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(r,n,a){const i=l=>({year:l,isTwoDigitYear:n==="YY"});switch(n){case"Y":return Qd(Rd(4,r),i);case"Yo":return Qd(a.ordinalNumber(r,{unit:"year"}),i);default:return Qd(Rd(n.length,r),i)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,a,i){const l=JCe(r,i);if(a.isTwoDigitYear){const c=set(a.year,l);return r.setFullYear(c,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),jm(r,i)}const o=!("era"in n)||n.era===1?a.year:1-a.year;return r.setFullYear(o,0,i.firstWeekContainsDate),r.setHours(0,0,0,0),jm(r,i)}}class NLt extends pl{constructor(){super(...arguments);Gn(this,"priority",130);Gn(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return jde(n==="R"?4:n.length,r)}set(r,n,a){const i=Cl(r,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),Ib(i)}}class kLt extends pl{constructor(){super(...arguments);Gn(this,"priority",130);Gn(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return jde(n==="u"?4:n.length,r)}set(r,n,a){return r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}}class SLt extends pl{constructor(){super(...arguments);Gn(this,"priority",120);Gn(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"Q":case"QQ":return Rd(n.length,r);case"Qo":return a.ordinalNumber(r,{unit:"quarter"});case"QQQ":return a.quarter(r,{width:"abbreviated",context:"formatting"})||a.quarter(r,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(r,{width:"wide",context:"formatting"})||a.quarter(r,{width:"abbreviated",context:"formatting"})||a.quarter(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=1&&n<=4}set(r,n,a){return r.setMonth((a-1)*3,1),r.setHours(0,0,0,0),r}}class CLt extends pl{constructor(){super(...arguments);Gn(this,"priority",120);Gn(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"q":case"qq":return Rd(n.length,r);case"qo":return a.ordinalNumber(r,{unit:"quarter"});case"qqq":return a.quarter(r,{width:"abbreviated",context:"standalone"})||a.quarter(r,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(r,{width:"wide",context:"standalone"})||a.quarter(r,{width:"abbreviated",context:"standalone"})||a.quarter(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=1&&n<=4}set(r,n,a){return r.setMonth((a-1)*3,1),r.setHours(0,0,0,0),r}}class TLt extends pl{constructor(){super(...arguments);Gn(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Gn(this,"priority",110)}parse(r,n,a){const i=l=>l-1;switch(n){case"M":return Qd(ld(Xd.month,r),i);case"MM":return Qd(Rd(2,r),i);case"Mo":return Qd(a.ordinalNumber(r,{unit:"month"}),i);case"MMM":return a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(r,{width:"wide",context:"formatting"})||a.month(r,{width:"abbreviated",context:"formatting"})||a.month(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}class ELt extends pl{constructor(){super(...arguments);Gn(this,"priority",110);Gn(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(r,n,a){const i=l=>l-1;switch(n){case"L":return Qd(ld(Xd.month,r),i);case"LL":return Qd(Rd(2,r),i);case"Lo":return Qd(a.ordinalNumber(r,{unit:"month"}),i);case"LLL":return a.month(r,{width:"abbreviated",context:"standalone"})||a.month(r,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(r,{width:"wide",context:"standalone"})||a.month(r,{width:"abbreviated",context:"standalone"})||a.month(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.setMonth(a,1),r.setHours(0,0,0,0),r}}function ALt(s,t,r){const n=ma(s),a=e4e(n,r)-t;return n.setDate(n.getDate()-a*7),n}class MLt extends pl{constructor(){super(...arguments);Gn(this,"priority",100);Gn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,a){switch(n){case"w":return ld(Xd.week,r);case"wo":return a.ordinalNumber(r,{unit:"week"});default:return Rd(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a,i){return jm(ALt(r,a,i),i)}}function ILt(s,t){const r=ma(s),n=QCe(r)-t;return r.setDate(r.getDate()-n*7),r}class LLt extends pl{constructor(){super(...arguments);Gn(this,"priority",100);Gn(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(r,n,a){switch(n){case"I":return ld(Xd.week,r);case"Io":return a.ordinalNumber(r,{unit:"week"});default:return Rd(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,a){return Ib(ILt(r,a))}}const PLt=[31,28,31,30,31,30,31,31,30,31,30,31],DLt=[31,29,31,30,31,30,31,31,30,31,30,31];class RLt extends pl{constructor(){super(...arguments);Gn(this,"priority",90);Gn(this,"subPriority",1);Gn(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"d":return ld(Xd.date,r);case"do":return a.ordinalNumber(r,{unit:"date"});default:return Rd(n.length,r)}}validate(r,n){const a=r.getFullYear(),i=ret(a),l=r.getMonth();return i?n>=1&&n<=DLt[l]:n>=1&&n<=PLt[l]}set(r,n,a){return r.setDate(a),r.setHours(0,0,0,0),r}}class OLt extends pl{constructor(){super(...arguments);Gn(this,"priority",90);Gn(this,"subpriority",1);Gn(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(r,n,a){switch(n){case"D":case"DD":return ld(Xd.dayOfYear,r);case"Do":return a.ordinalNumber(r,{unit:"date"});default:return Rd(n.length,r)}}validate(r,n){const a=r.getFullYear();return ret(a)?n>=1&&n<=366:n>=1&&n<=365}set(r,n,a){return r.setMonth(0,a),r.setHours(0,0,0,0),r}}function s4e(s,t,r){var m,x,y,v;const n=Qj(),a=(r==null?void 0:r.weekStartsOn)??((x=(m=r==null?void 0:r.locale)==null?void 0:m.options)==null?void 0:x.weekStartsOn)??n.weekStartsOn??((v=(y=n.locale)==null?void 0:y.options)==null?void 0:v.weekStartsOn)??0,i=ma(s),l=i.getDay(),c=(t%7+7)%7,d=7-a,h=t<0||t>6?t-(l+d)%7:(c+d)%7-(l+d)%7;return Vl(i,h)}class FLt extends pl{constructor(){super(...arguments);Gn(this,"priority",90);Gn(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(r,n,a){switch(n){case"E":case"EE":case"EEE":return a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=s4e(r,a,i),r.setHours(0,0,0,0),r}}class BLt extends pl{constructor(){super(...arguments);Gn(this,"priority",90);Gn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(r,n,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(n){case"e":case"ee":return Qd(Rd(n.length,r),l);case"eo":return Qd(a.ordinalNumber(r,{unit:"day"}),l);case"eee":return a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"eeeee":return a.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=s4e(r,a,i),r.setHours(0,0,0,0),r}}class zLt extends pl{constructor(){super(...arguments);Gn(this,"priority",90);Gn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(r,n,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(n){case"c":case"cc":return Qd(Rd(n.length,r),l);case"co":return Qd(a.ordinalNumber(r,{unit:"day"}),l);case"ccc":return a.day(r,{width:"abbreviated",context:"standalone"})||a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"});case"ccccc":return a.day(r,{width:"narrow",context:"standalone"});case"cccccc":return a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(r,{width:"wide",context:"standalone"})||a.day(r,{width:"abbreviated",context:"standalone"})||a.day(r,{width:"short",context:"standalone"})||a.day(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=6}set(r,n,a,i){return r=s4e(r,a,i),r.setHours(0,0,0,0),r}}function $Lt(s,t){const r=ma(s),n=hLt(r),a=t-n;return Vl(r,a)}class ULt extends pl{constructor(){super(...arguments);Gn(this,"priority",90);Gn(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(r,n,a){const i=l=>l===0?7:l;switch(n){case"i":case"ii":return Rd(n.length,r);case"io":return a.ordinalNumber(r,{unit:"day"});case"iii":return Qd(a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiii":return Qd(a.day(r,{width:"narrow",context:"formatting"}),i);case"iiiiii":return Qd(a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i);case"iiii":default:return Qd(a.day(r,{width:"wide",context:"formatting"})||a.day(r,{width:"abbreviated",context:"formatting"})||a.day(r,{width:"short",context:"formatting"})||a.day(r,{width:"narrow",context:"formatting"}),i)}}validate(r,n){return n>=1&&n<=7}set(r,n,a){return r=$Lt(r,a),r.setHours(0,0,0,0),r}}class qLt extends pl{constructor(){super(...arguments);Gn(this,"priority",80);Gn(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(r,n,a){switch(n){case"a":case"aa":case"aaa":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(t4e(a),0,0,0),r}}class VLt extends pl{constructor(){super(...arguments);Gn(this,"priority",80);Gn(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(r,n,a){switch(n){case"b":case"bb":case"bbb":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(t4e(a),0,0,0),r}}class HLt extends pl{constructor(){super(...arguments);Gn(this,"priority",80);Gn(this,"incompatibleTokens",["a","b","t","T"])}parse(r,n,a){switch(n){case"B":case"BB":case"BBB":return a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(r,{width:"wide",context:"formatting"})||a.dayPeriod(r,{width:"abbreviated",context:"formatting"})||a.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,a){return r.setHours(t4e(a),0,0,0),r}}class GLt extends pl{constructor(){super(...arguments);Gn(this,"priority",70);Gn(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,a){switch(n){case"h":return ld(Xd.hour12h,r);case"ho":return a.ordinalNumber(r,{unit:"hour"});default:return Rd(n.length,r)}}validate(r,n){return n>=1&&n<=12}set(r,n,a){const i=r.getHours()>=12;return i&&a<12?r.setHours(a+12,0,0,0):!i&&a===12?r.setHours(0,0,0,0):r.setHours(a,0,0,0),r}}class WLt extends pl{constructor(){super(...arguments);Gn(this,"priority",70);Gn(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,a){switch(n){case"H":return ld(Xd.hour23h,r);case"Ho":return a.ordinalNumber(r,{unit:"hour"});default:return Rd(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,a){return r.setHours(a,0,0,0),r}}class KLt extends pl{constructor(){super(...arguments);Gn(this,"priority",70);Gn(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,a){switch(n){case"K":return ld(Xd.hour11h,r);case"Ko":return a.ordinalNumber(r,{unit:"hour"});default:return Rd(n.length,r)}}validate(r,n){return n>=0&&n<=11}set(r,n,a){return r.getHours()>=12&&a<12?r.setHours(a+12,0,0,0):r.setHours(a,0,0,0),r}}class YLt extends pl{constructor(){super(...arguments);Gn(this,"priority",70);Gn(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,a){switch(n){case"k":return ld(Xd.hour24h,r);case"ko":return a.ordinalNumber(r,{unit:"hour"});default:return Rd(n.length,r)}}validate(r,n){return n>=1&&n<=24}set(r,n,a){const i=a<=24?a%24:a;return r.setHours(i,0,0,0),r}}class ZLt extends pl{constructor(){super(...arguments);Gn(this,"priority",60);Gn(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"m":return ld(Xd.minute,r);case"mo":return a.ordinalNumber(r,{unit:"minute"});default:return Rd(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setMinutes(a,0,0),r}}class XLt extends pl{constructor(){super(...arguments);Gn(this,"priority",50);Gn(this,"incompatibleTokens",["t","T"])}parse(r,n,a){switch(n){case"s":return ld(Xd.second,r);case"so":return a.ordinalNumber(r,{unit:"second"});default:return Rd(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,a){return r.setSeconds(a,0),r}}class QLt extends pl{constructor(){super(...arguments);Gn(this,"priority",30);Gn(this,"incompatibleTokens",["t","T"])}parse(r,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return Qd(Rd(n.length,r),a)}set(r,n,a){return r.setMilliseconds(a),r}}class JLt extends pl{constructor(){super(...arguments);Gn(this,"priority",10);Gn(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return U0($0.basicOptionalMinutes,r);case"XX":return U0($0.basic,r);case"XXXX":return U0($0.basicOptionalSeconds,r);case"XXXXX":return U0($0.extendedOptionalSeconds,r);case"XXX":default:return U0($0.extended,r)}}set(r,n,a){return n.timestampIsSet?r:Cl(r,r.getTime()-Aj(r)-a)}}class ePt extends pl{constructor(){super(...arguments);Gn(this,"priority",10);Gn(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return U0($0.basicOptionalMinutes,r);case"xx":return U0($0.basic,r);case"xxxx":return U0($0.basicOptionalSeconds,r);case"xxxxx":return U0($0.extendedOptionalSeconds,r);case"xxx":default:return U0($0.extended,r)}}set(r,n,a){return n.timestampIsSet?r:Cl(r,r.getTime()-Aj(r)-a)}}class tPt extends pl{constructor(){super(...arguments);Gn(this,"priority",40);Gn(this,"incompatibleTokens","*")}parse(r){return tet(r)}set(r,n,a){return[Cl(r,a*1e3),{timestampIsSet:!0}]}}class sPt extends pl{constructor(){super(...arguments);Gn(this,"priority",20);Gn(this,"incompatibleTokens","*")}parse(r){return tet(r)}set(r,n,a){return[Cl(r,a),{timestampIsSet:!0}]}}const rPt={G:new _Lt,y:new wLt,Y:new jLt,R:new NLt,u:new kLt,Q:new SLt,q:new CLt,M:new TLt,L:new ELt,w:new MLt,I:new LLt,d:new RLt,D:new OLt,E:new FLt,e:new BLt,c:new zLt,i:new ULt,a:new qLt,b:new VLt,B:new HLt,h:new GLt,H:new WLt,K:new KLt,k:new YLt,m:new ZLt,s:new XLt,S:new QLt,X:new JLt,x:new ePt,t:new tPt,T:new sPt},nPt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,aPt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,iPt=/^'([^]*?)'?$/,oPt=/''/g,lPt=/\S/,cPt=/[a-zA-Z]/;function r4e(s,t,r,n){var w,b,N,S;const a=uLt(),i=a.locale??gfe,l=a.firstWeekContainsDate??((b=(w=a.locale)==null?void 0:w.options)==null?void 0:b.firstWeekContainsDate)??1,o=a.weekStartsOn??((S=(N=a.locale)==null?void 0:N.options)==null?void 0:S.weekStartsOn)??0;if(t==="")return s===""?ma(r):Cl(r,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new bLt],h=t.match(aPt).map(T=>{const A=T[0];if(A in sje){const I=sje[A];return I(T,i.formatLong)}return T}).join("").match(nPt),m=[];for(let T of h){JJe(T)&&rje(T,t,s),QJe(T)&&rje(T,t,s);const A=T[0],I=rPt[A];if(I){const{incompatibleTokens:D}=I;if(Array.isArray(D)){const $=m.find(F=>D.includes(F.token)||F.token===A);if($)throw new RangeError(`The format string mustn't contain \`${$.fullToken}\` and \`${T}\` at the same time`)}else if(I.incompatibleTokens==="*"&&m.length>0)throw new RangeError(`The format string mustn't contain \`${T}\` and any other token at the same time`);m.push({token:A,fullToken:T});const R=I.run(s,T,i.match,c);if(!R)return Cl(r,NaN);d.push(R.setter),s=R.rest}else{if(A.match(cPt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(T==="''"?T="'":A==="'"&&(T=dPt(T)),s.indexOf(T)===0)s=s.slice(T.length);else return Cl(r,NaN)}}if(s.length>0&&lPt.test(s))return Cl(r,NaN);const x=d.map(T=>T.priority).sort((T,A)=>A-T).filter((T,A,I)=>I.indexOf(T)===A).map(T=>d.filter(A=>A.priority===T).sort((A,I)=>I.subPriority-A.subPriority)).map(T=>T[0]);let y=ma(r);if(isNaN(y.getTime()))return Cl(r,NaN);const v={};for(const T of x){if(!T.validate(y,c))return Cl(r,NaN);const A=T.set(y,v,c);Array.isArray(A)?(y=A[0],Object.assign(v,A[1])):y=A}return Cl(r,y)}function dPt(s){return s.match(iPt)[1].replace(oPt,"'")}function hv(s){return+ma(s)i-l);return r>=n&&r<=a}function ace(s,t){return Vl(s,-t)}function nf(s,t){const n=gPt(s);let a;if(n.date){const c=yPt(n.date,2);a=vPt(c.restDateString,c.year)}if(!a||isNaN(a.getTime()))return new Date(NaN);const i=a.getTime();let l=0,o;if(n.time&&(l=bPt(n.time),isNaN(l)))return new Date(NaN);if(n.timezone){if(o=_Pt(n.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 H9={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},fPt=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,pPt=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,xPt=/^([+-])(\d{2})(?::?(\d{2}))?$/;function gPt(s){const t={},r=s.split(H9.dateTimeDelimiter);let n;if(r.length>2)return t;if(/:/.test(r[0])?n=r[0]:(t.date=r[0],n=r[1],H9.timeZoneDelimiter.test(t.date)&&(t.date=s.split(H9.timeZoneDelimiter)[0],n=s.substr(t.date.length,s.length))),n){const a=H9.timezone.exec(n);a?(t.time=n.replace(a[1],""),t.timezone=a[1]):t.time=n}return t}function yPt(s,t){const r=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),n=s.match(r);if(!n)return{year:NaN,restDateString:""};const a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((n[1]||n[2]).length)}}function vPt(s,t){if(t===null)return new Date(NaN);const r=s.match(fPt);if(!r)return new Date(NaN);const n=!!r[4],a=Z6(r[1]),i=Z6(r[2])-1,l=Z6(r[3]),o=Z6(r[4]),c=Z6(r[5])-1;if(n)return SPt(t,o,c)?wPt(t,o,c):new Date(NaN);{const d=new Date(0);return!NPt(t,i,l)||!kPt(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function Z6(s){return s?parseInt(s):1}function bPt(s){const t=s.match(pPt);if(!t)return NaN;const r=pve(t[1]),n=pve(t[2]),a=pve(t[3]);return CPt(r,n,a)?r*rB+n*pfe+a*1e3:NaN}function pve(s){return s&&parseFloat(s.replace(",","."))||0}function _Pt(s){if(s==="Z")return 0;const t=s.match(xPt);if(!t)return 0;const r=t[1]==="+"?-1:1,n=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return TPt(n,a)?r*(n*rB+a*pfe):NaN}function wPt(s,t,r){const n=new Date(0);n.setUTCFullYear(s,0,4);const a=n.getUTCDay()||7,i=(t-1)*7+r+1-a;return n.setUTCDate(n.getUTCDate()+i),n}const jPt=[31,null,31,30,31,30,31,31,30,31,30,31];function net(s){return s%400===0||s%4===0&&s%100!==0}function NPt(s,t,r){return t>=0&&t<=11&&r>=1&&r<=(jPt[t]||(net(s)?29:28))}function kPt(s,t){return t>=1&&t<=(net(s)?366:365)}function SPt(s,t,r){return t>=1&&t<=53&&r>=0&&r<=6}function CPt(s,t,r){return s===24?t===0&&r===0:r>=0&&r<60&&t>=0&&t<60&&s>=0&&s<25}function TPt(s,t){return t>=0&&t<=59}function xve(s,t){const r=ma(s),n=r.getFullYear(),a=r.getDate(),i=Cl(s,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);const l=dLt(i);return r.setMonth(t,Math.min(a,l)),r}function rO(s,t){const r=ma(s);return r.setHours(t),r}function nO(s,t){const r=ma(s);return r.setMinutes(t),r}function kRe(s,t){const r=ma(s);return isNaN(+r)?Cl(s,NaN):(r.setFullYear(t),r)}function t4(s,t){return gf(s,-t)}var Qo;(function(s){s.assertEqual=a=>{};function t(a){}s.assertIs=t;function r(a){throw new Error}s.assertNever=r,s.arrayToEnum=a=>{const i={};for(const l of a)i[l]=l;return i},s.getValidEnumValues=a=>{const i=s.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),l={};for(const o of i)l[o]=a[o];return s.objectValues(l)},s.objectValues=a=>s.objectKeys(a).map(function(i){return a[i]}),s.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const i=[];for(const l in a)Object.prototype.hasOwnProperty.call(a,l)&&i.push(l);return i},s.find=(a,i)=>{for(const l of a)if(i(l))return l},s.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,i=" | "){return a.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}s.joinValues=n,s.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(Qo||(Qo={}));var SRe;(function(s){s.mergeShapes=(t,r)=>({...t,...r})})(SRe||(SRe={}));const Aa=Qo.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sw=s=>{switch(typeof s){case"undefined":return Aa.undefined;case"string":return Aa.string;case"number":return Number.isNaN(s)?Aa.nan:Aa.number;case"boolean":return Aa.boolean;case"function":return Aa.function;case"bigint":return Aa.bigint;case"symbol":return Aa.symbol;case"object":return Array.isArray(s)?Aa.array:s===null?Aa.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?Aa.promise:typeof Map<"u"&&s instanceof Map?Aa.map:typeof Set<"u"&&s instanceof Set?Aa.set:typeof Date<"u"&&s instanceof Date?Aa.date:Aa.object;default:return Aa.unknown}},jn=Qo.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class wv extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(i){return i.message},n={_errors:[]},a=i=>{for(const l of i.issues)if(l.code==="invalid_union")l.unionErrors.map(a);else if(l.code==="invalid_return_type")a(l.returnTypeError);else if(l.code==="invalid_arguments")a(l.argumentsError);else if(l.path.length===0)n._errors.push(r(l));else{let o=n,c=0;for(;cr.message){const r={},n=[];for(const a of this.issues)if(a.path.length>0){const i=a.path[0];r[i]=r[i]||[],r[i].push(t(a))}else n.push(t(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}wv.create=s=>new wv(s);const nje=(s,t)=>{let r;switch(s.code){case jn.invalid_type:s.received===Aa.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case jn.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,Qo.jsonStringifyReplacer)}`;break;case jn.unrecognized_keys:r=`Unrecognized key(s) in object: ${Qo.joinValues(s.keys,", ")}`;break;case jn.invalid_union:r="Invalid input";break;case jn.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Qo.joinValues(s.options)}`;break;case jn.invalid_enum_value:r=`Invalid enum value. Expected ${Qo.joinValues(s.options)}, received '${s.received}'`;break;case jn.invalid_arguments:r="Invalid function arguments";break;case jn.invalid_return_type:r="Invalid function return type";break;case jn.invalid_date:r="Invalid date";break;case jn.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:Qo.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case jn.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case jn.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case jn.custom:r="Invalid input";break;case jn.invalid_intersection_types:r="Intersection results could not be merged";break;case jn.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case jn.not_finite:r="Number must be finite";break;default:r=t.defaultError,Qo.assertNever(s)}return{message:r}};let EPt=nje;function APt(){return EPt}const MPt=s=>{const{data:t,path:r,errorMaps:n,issueData:a}=s,i=[...r,...a.path||[]],l={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let o="";const c=n.filter(d=>!!d).slice().reverse();for(const d of c)o=d(l,{data:t,defaultError:o}).message;return{...a,path:i,message:o}};function aa(s,t){const r=APt(),n=MPt({issueData:t,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===nje?void 0:nje].filter(a=>!!a)});s.common.issues.push(n)}class sx{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const a of r){if(a.status==="aborted")return Ii;a.status==="dirty"&&t.dirty(),n.push(a.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const a of r){const i=await a.key,l=await a.value;n.push({key:i,value:l})}return sx.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const a of r){const{key:i,value:l}=a;if(i.status==="aborted"||l.status==="aborted")return Ii;i.status==="dirty"&&t.dirty(),l.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof l.value<"u"||a.alwaysSet)&&(n[i.value]=l.value)}return{status:t.value,value:n}}}const Ii=Object.freeze({status:"aborted"}),ID=s=>({status:"dirty",value:s}),vg=s=>({status:"valid",value:s}),CRe=s=>s.status==="aborted",TRe=s=>s.status==="dirty",SM=s=>s.status==="valid",Nde=s=>typeof Promise<"u"&&s instanceof Promise;var Da;(function(s){s.errToObj=t=>typeof t=="string"?{message:t}:t||{},s.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Da||(Da={}));class Mj{constructor(t,r,n,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ERe=(s,t)=>{if(SM(t))return{success:!0,data:t.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new wv(s.common.issues);return this._error=r,this._error}}};function lo(s){if(!s)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:a}=s;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(l,o)=>{const{message:c}=s;return l.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:l.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class Zo{get description(){return this._def.description}_getType(t){return sw(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:sw(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new sx,ctx:{common:t.parent.common,data:t.data,parsedType:sw(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(Nde(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sw(t)},a=this._parseSync({data:t,path:n.path,parent:n});return ERe(n,a)}"~validate"(t){var n,a;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sw(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:r});return SM(i)?{value:i.value}:{issues:r.common.issues}}catch(i){(a=(n=i==null?void 0:i.message)==null?void 0:n.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>SM(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:sw(t)},a=this._parse({data:t,path:n.path,parent:n}),i=await(Nde(a)?a:Promise.resolve(a));return ERe(n,i)}refine(t,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,i)=>{const l=t(a),o=()=>i.addIssue({code:jn.custom,...n(a)});return typeof Promise<"u"&&l instanceof Promise?l.then(c=>c?!0:(o(),!1)):l?!0:(o(),!1)})}refinement(t,r){return this._refinement((n,a)=>t(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(t){return new EM({schema:this,typeName:Li.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return mj.create(this,this._def)}nullable(){return AM.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mv.create(this)}promise(){return Tde.create(this,this._def)}or(t){return Sde.create([this,t],this._def)}and(t){return Cde.create(this,t,this._def)}transform(t){return new EM({...lo(this._def),schema:this,typeName:Li.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new lje({...lo(this._def),innerType:this,defaultValue:r,typeName:Li.ZodDefault})}brand(){return new e6t({typeName:Li.ZodBranded,type:this,...lo(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new cje({...lo(this._def),innerType:this,catchValue:r,typeName:Li.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return n4e.create(this,t)}readonly(){return dje.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const IPt=/^c[^\s-]{8,}$/i,LPt=/^[0-9a-z]+$/,PPt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,DPt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,RPt=/^[a-z0-9_-]{21}$/i,OPt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,FPt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,BPt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zPt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let gve;const $Pt=/^(?:(?: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])$/,UPt=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,qPt=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,VPt=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,HPt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,GPt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,aet="((\\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])))",WPt=new RegExp(`^${aet}$`);function iet(s){let t="[0-5]\\d";s.precision?t=`${t}\\.\\d{${s.precision}}`:s.precision==null&&(t=`${t}(\\.\\d+)?`);const r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function KPt(s){return new RegExp(`^${iet(s)}$`)}function YPt(s){let t=`${aet}T${iet(s)}`;const r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function ZPt(s,t){return!!((t==="v4"||!t)&&$Pt.test(s)||(t==="v6"||!t)&&qPt.test(s))}function XPt(s,t){if(!OPt.test(s))return!1;try{const[r]=s.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function QPt(s,t){return!!((t==="v4"||!t)&&UPt.test(s)||(t==="v6"||!t)&&VPt.test(s))}class Pw extends Zo{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Aa.string){const i=this._getOrReturnCtx(t);return aa(i,{code:jn.invalid_type,expected:Aa.string,received:i.parsedType}),Ii}const n=new sx;let a;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(a=this._getOrReturnCtx(t,a),aa(a,{code:jn.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const l=t.data.length>i.value,o=t.data.lengtht.test(a),{validation:r,code:jn.invalid_string,...Da.errToObj(n)})}_addCheck(t){return new Pw({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Da.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Da.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Da.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Da.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Da.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Da.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Da.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Da.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Da.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Da.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Da.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Da.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Da.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...Da.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...Da.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...Da.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Da.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r==null?void 0:r.position,...Da.errToObj(r==null?void 0:r.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Da.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Da.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Da.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Da.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Da.errToObj(r)})}nonempty(t){return this.min(1,Da.errToObj(t))}trim(){return new Pw({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Pw({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Pw({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew Pw({checks:[],typeName:Li.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...lo(s)});function JPt(s,t){const r=(s.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n,i=Number.parseInt(s.toFixed(a).replace(".","")),l=Number.parseInt(t.toFixed(a).replace(".",""));return i%l/10**a}class CM extends Zo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Aa.number){const i=this._getOrReturnCtx(t);return aa(i,{code:jn.invalid_type,expected:Aa.number,received:i.parsedType}),Ii}let n;const a=new sx;for(const i of this._def.checks)i.kind==="int"?Qo.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),aa(n,{code:jn.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),aa(n,{code:jn.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?JPt(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),aa(n,{code:jn.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),aa(n,{code:jn.not_finite,message:i.message}),a.dirty()):Qo.assertNever(i);return{status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Da.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Da.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Da.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Da.toString(r))}setLimit(t,r,n,a){return new CM({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Da.toString(a)}]})}_addCheck(t){return new CM({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Da.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Da.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Da.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Da.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Da.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Da.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Da.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Da.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Da.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuet.kind==="int"||t.kind==="multipleOf"&&Qo.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.valuenew CM({checks:[],typeName:Li.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...lo(s)});class p8 extends Zo{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Aa.bigint)return this._getInvalidInput(t);let n;const a=new sx;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),aa(n,{code:jn.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),aa(n,{code:jn.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):Qo.assertNever(i);return{status:a.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return aa(r,{code:jn.invalid_type,expected:Aa.bigint,received:r.parsedType}),Ii}gte(t,r){return this.setLimit("min",t,!0,Da.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Da.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Da.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Da.toString(r))}setLimit(t,r,n,a){return new p8({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Da.toString(a)}]})}_addCheck(t){return new p8({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Da.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Da.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Da.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Da.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Da.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew p8({checks:[],typeName:Li.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...lo(s)});class aje extends Zo{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Aa.boolean){const n=this._getOrReturnCtx(t);return aa(n,{code:jn.invalid_type,expected:Aa.boolean,received:n.parsedType}),Ii}return vg(t.data)}}aje.create=s=>new aje({typeName:Li.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...lo(s)});class kde extends Zo{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Aa.date){const i=this._getOrReturnCtx(t);return aa(i,{code:jn.invalid_type,expected:Aa.date,received:i.parsedType}),Ii}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return aa(i,{code:jn.invalid_date}),Ii}const n=new sx;let a;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(a=this._getOrReturnCtx(t,a),aa(a,{code:jn.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Qo.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new kde({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Da.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Da.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.valuenew kde({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:Li.ZodDate,...lo(s)});class ARe extends Zo{_parse(t){if(this._getType(t)!==Aa.symbol){const n=this._getOrReturnCtx(t);return aa(n,{code:jn.invalid_type,expected:Aa.symbol,received:n.parsedType}),Ii}return vg(t.data)}}ARe.create=s=>new ARe({typeName:Li.ZodSymbol,...lo(s)});class MRe extends Zo{_parse(t){if(this._getType(t)!==Aa.undefined){const n=this._getOrReturnCtx(t);return aa(n,{code:jn.invalid_type,expected:Aa.undefined,received:n.parsedType}),Ii}return vg(t.data)}}MRe.create=s=>new MRe({typeName:Li.ZodUndefined,...lo(s)});class IRe extends Zo{_parse(t){if(this._getType(t)!==Aa.null){const n=this._getOrReturnCtx(t);return aa(n,{code:jn.invalid_type,expected:Aa.null,received:n.parsedType}),Ii}return vg(t.data)}}IRe.create=s=>new IRe({typeName:Li.ZodNull,...lo(s)});class LRe extends Zo{constructor(){super(...arguments),this._any=!0}_parse(t){return vg(t.data)}}LRe.create=s=>new LRe({typeName:Li.ZodAny,...lo(s)});class PRe extends Zo{constructor(){super(...arguments),this._unknown=!0}_parse(t){return vg(t.data)}}PRe.create=s=>new PRe({typeName:Li.ZodUnknown,...lo(s)});class Ij extends Zo{_parse(t){const r=this._getOrReturnCtx(t);return aa(r,{code:jn.invalid_type,expected:Aa.never,received:r.parsedType}),Ii}}Ij.create=s=>new Ij({typeName:Li.ZodNever,...lo(s)});class DRe extends Zo{_parse(t){if(this._getType(t)!==Aa.undefined){const n=this._getOrReturnCtx(t);return aa(n,{code:jn.invalid_type,expected:Aa.void,received:n.parsedType}),Ii}return vg(t.data)}}DRe.create=s=>new DRe({typeName:Li.ZodVoid,...lo(s)});class mv extends Zo{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),a=this._def;if(r.parsedType!==Aa.array)return aa(r,{code:jn.invalid_type,expected:Aa.array,received:r.parsedType}),Ii;if(a.exactLength!==null){const l=r.data.length>a.exactLength.value,o=r.data.lengtha.maxLength.value&&(aa(r,{code:jn.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((l,o)=>a.type._parseAsync(new Mj(r,l,r.path,o)))).then(l=>sx.mergeArray(n,l));const i=[...r.data].map((l,o)=>a.type._parseSync(new Mj(r,l,r.path,o)));return sx.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new mv({...this._def,minLength:{value:t,message:Da.toString(r)}})}max(t,r){return new mv({...this._def,maxLength:{value:t,message:Da.toString(r)}})}length(t,r){return new mv({...this._def,exactLength:{value:t,message:Da.toString(r)}})}nonempty(t){return this.min(1,t)}}mv.create=(s,t)=>new mv({type:s,minLength:null,maxLength:null,exactLength:null,typeName:Li.ZodArray,...lo(t)});function vE(s){if(s instanceof jd){const t={};for(const r in s.shape){const n=s.shape[r];t[r]=mj.create(vE(n))}return new jd({...s._def,shape:()=>t})}else return s instanceof mv?new mv({...s._def,type:vE(s.element)}):s instanceof mj?mj.create(vE(s.unwrap())):s instanceof AM?AM.create(vE(s.unwrap())):s instanceof L3?L3.create(s.items.map(t=>vE(t))):s}class jd extends Zo{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=Qo.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Aa.object){const d=this._getOrReturnCtx(t);return aa(d,{code:jn.invalid_type,expected:Aa.object,received:d.parsedType}),Ii}const{status:n,ctx:a}=this._processInputParams(t),{shape:i,keys:l}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ij&&this._def.unknownKeys==="strip"))for(const d in a.data)l.includes(d)||o.push(d);const c=[];for(const d of l){const h=i[d],m=a.data[d];c.push({key:{status:"valid",value:d},value:h._parse(new Mj(a,m,a.path,d)),alwaysSet:d in a.data})}if(this._def.catchall instanceof Ij){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of o)c.push({key:{status:"valid",value:h},value:{status:"valid",value:a.data[h]}});else if(d==="strict")o.length>0&&(aa(a,{code:jn.unrecognized_keys,keys:o}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of o){const m=a.data[h];c.push({key:{status:"valid",value:h},value:d._parse(new Mj(a,m,a.path,h)),alwaysSet:h in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of c){const m=await h.key,x=await h.value;d.push({key:m,value:x,alwaysSet:h.alwaysSet})}return d}).then(d=>sx.mergeObjectSync(n,d)):sx.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Da.errToObj,new jd({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{var i,l;const a=((l=(i=this._def).errorMap)==null?void 0:l.call(i,r,n).message)??n.defaultError;return r.code==="unrecognized_keys"?{message:Da.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new jd({...this._def,unknownKeys:"strip"})}passthrough(){return new jd({...this._def,unknownKeys:"passthrough"})}extend(t){return new jd({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new jd({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Li.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new jd({...this._def,catchall:t})}pick(t){const r={};for(const n of Qo.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new jd({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Qo.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new jd({...this._def,shape:()=>r})}deepPartial(){return vE(this)}partial(t){const r={};for(const n of Qo.objectKeys(this.shape)){const a=this.shape[n];t&&!t[n]?r[n]=a:r[n]=a.optional()}return new jd({...this._def,shape:()=>r})}required(t){const r={};for(const n of Qo.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof mj;)i=i._def.innerType;r[n]=i}return new jd({...this._def,shape:()=>r})}keyof(){return oet(Qo.objectKeys(this.shape))}}jd.create=(s,t)=>new jd({shape:()=>s,unknownKeys:"strip",catchall:Ij.create(),typeName:Li.ZodObject,...lo(t)});jd.strictCreate=(s,t)=>new jd({shape:()=>s,unknownKeys:"strict",catchall:Ij.create(),typeName:Li.ZodObject,...lo(t)});jd.lazycreate=(s,t)=>new jd({shape:s,unknownKeys:"strip",catchall:Ij.create(),typeName:Li.ZodObject,...lo(t)});class Sde extends Zo{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function a(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const l=i.map(o=>new wv(o.ctx.common.issues));return aa(r,{code:jn.invalid_union,unionErrors:l}),Ii}if(r.common.async)return Promise.all(n.map(async i=>{const l={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:l}),ctx:l}})).then(a);{let i;const l=[];for(const c of n){const d={...r,common:{...r.common,issues:[]},parent:null},h=c._parseSync({data:r.data,path:r.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;const o=l.map(c=>new wv(c));return aa(r,{code:jn.invalid_union,unionErrors:o}),Ii}}get options(){return this._def.options}}Sde.create=(s,t)=>new Sde({options:s,typeName:Li.ZodUnion,...lo(t)});function ije(s,t){const r=sw(s),n=sw(t);if(s===t)return{valid:!0,data:s};if(r===Aa.object&&n===Aa.object){const a=Qo.objectKeys(t),i=Qo.objectKeys(s).filter(o=>a.indexOf(o)!==-1),l={...s,...t};for(const o of i){const c=ije(s[o],t[o]);if(!c.valid)return{valid:!1};l[o]=c.data}return{valid:!0,data:l}}else if(r===Aa.array&&n===Aa.array){if(s.length!==t.length)return{valid:!1};const a=[];for(let i=0;i{if(CRe(i)||CRe(l))return Ii;const o=ije(i.value,l.value);return o.valid?((TRe(i)||TRe(l))&&r.dirty(),{status:r.value,value:o.data}):(aa(n,{code:jn.invalid_intersection_types}),Ii)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,l])=>a(i,l)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Cde.create=(s,t,r)=>new Cde({left:s,right:t,typeName:Li.ZodIntersection,...lo(r)});class L3 extends Zo{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Aa.array)return aa(n,{code:jn.invalid_type,expected:Aa.array,received:n.parsedType}),Ii;if(n.data.lengththis._def.items.length&&(aa(n,{code:jn.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const i=[...n.data].map((l,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Mj(n,l,n.path,o)):null}).filter(l=>!!l);return n.common.async?Promise.all(i).then(l=>sx.mergeArray(r,l)):sx.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new L3({...this._def,rest:t})}}L3.create=(s,t)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new L3({items:s,typeName:Li.ZodTuple,rest:null,...lo(t)})};class RRe extends Zo{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Aa.map)return aa(n,{code:jn.invalid_type,expected:Aa.map,received:n.parsedType}),Ii;const a=this._def.keyType,i=this._def.valueType,l=[...n.data.entries()].map(([o,c],d)=>({key:a._parse(new Mj(n,o,n.path,[d,"key"])),value:i._parse(new Mj(n,c,n.path,[d,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of l){const d=await c.key,h=await c.value;if(d.status==="aborted"||h.status==="aborted")return Ii;(d.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(d.value,h.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of l){const d=c.key,h=c.value;if(d.status==="aborted"||h.status==="aborted")return Ii;(d.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(d.value,h.value)}return{status:r.value,value:o}}}}RRe.create=(s,t,r)=>new RRe({valueType:t,keyType:s,typeName:Li.ZodMap,...lo(r)});class x8 extends Zo{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Aa.set)return aa(n,{code:jn.invalid_type,expected:Aa.set,received:n.parsedType}),Ii;const a=this._def;a.minSize!==null&&n.data.sizea.maxSize.value&&(aa(n,{code:jn.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const i=this._def.valueType;function l(c){const d=new Set;for(const h of c){if(h.status==="aborted")return Ii;h.status==="dirty"&&r.dirty(),d.add(h.value)}return{status:r.value,value:d}}const o=[...n.data.values()].map((c,d)=>i._parse(new Mj(n,c,n.path,d)));return n.common.async?Promise.all(o).then(c=>l(c)):l(o)}min(t,r){return new x8({...this._def,minSize:{value:t,message:Da.toString(r)}})}max(t,r){return new x8({...this._def,maxSize:{value:t,message:Da.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}x8.create=(s,t)=>new x8({valueType:s,minSize:null,maxSize:null,typeName:Li.ZodSet,...lo(t)});class ORe extends Zo{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}ORe.create=(s,t)=>new ORe({getter:s,typeName:Li.ZodLazy,...lo(t)});class oje extends Zo{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return aa(r,{received:r.data,code:jn.invalid_literal,expected:this._def.value}),Ii}return{status:"valid",value:t.data}}get value(){return this._def.value}}oje.create=(s,t)=>new oje({value:s,typeName:Li.ZodLiteral,...lo(t)});function oet(s,t){return new TM({values:s,typeName:Li.ZodEnum,...lo(t)})}class TM extends Zo{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return aa(r,{expected:Qo.joinValues(n),received:r.parsedType,code:jn.invalid_type}),Ii}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return aa(r,{received:r.data,code:jn.invalid_enum_value,options:n}),Ii}return vg(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return TM.create(t,{...this._def,...r})}exclude(t,r=this._def){return TM.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}}TM.create=oet;class FRe extends Zo{_parse(t){const r=Qo.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Aa.string&&n.parsedType!==Aa.number){const a=Qo.objectValues(r);return aa(n,{expected:Qo.joinValues(a),received:n.parsedType,code:jn.invalid_type}),Ii}if(this._cache||(this._cache=new Set(Qo.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const a=Qo.objectValues(r);return aa(n,{received:n.data,code:jn.invalid_enum_value,options:a}),Ii}return vg(t.data)}get enum(){return this._def.values}}FRe.create=(s,t)=>new FRe({values:s,typeName:Li.ZodNativeEnum,...lo(t)});class Tde extends Zo{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==Aa.promise&&r.common.async===!1)return aa(r,{code:jn.invalid_type,expected:Aa.promise,received:r.parsedType}),Ii;const n=r.parsedType===Aa.promise?r.data:Promise.resolve(r.data);return vg(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Tde.create=(s,t)=>new Tde({type:s,typeName:Li.ZodPromise,...lo(t)});class EM extends Zo{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Li.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),a=this._def.effect||null,i={addIssue:l=>{aa(n,l),l.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){const l=a.transform(n.data,i);if(n.common.async)return Promise.resolve(l).then(async o=>{if(r.value==="aborted")return Ii;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?Ii:c.status==="dirty"||r.value==="dirty"?ID(c.value):c});{if(r.value==="aborted")return Ii;const o=this._def.schema._parseSync({data:l,path:n.path,parent:n});return o.status==="aborted"?Ii:o.status==="dirty"||r.value==="dirty"?ID(o.value):o}}if(a.type==="refinement"){const l=o=>{const c=a.refinement(o,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ii:(o.status==="dirty"&&r.dirty(),l(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Ii:(o.status==="dirty"&&r.dirty(),l(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const l=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!SM(l))return Ii;const o=a.transform(l.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(l=>SM(l)?Promise.resolve(a.transform(l.value,i)).then(o=>({status:r.value,value:o})):Ii);Qo.assertNever(a)}}EM.create=(s,t,r)=>new EM({schema:s,typeName:Li.ZodEffects,effect:t,...lo(r)});EM.createWithPreprocess=(s,t,r)=>new EM({schema:t,effect:{type:"preprocess",transform:s},typeName:Li.ZodEffects,...lo(r)});class mj extends Zo{_parse(t){return this._getType(t)===Aa.undefined?vg(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mj.create=(s,t)=>new mj({innerType:s,typeName:Li.ZodOptional,...lo(t)});class AM extends Zo{_parse(t){return this._getType(t)===Aa.null?vg(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}AM.create=(s,t)=>new AM({innerType:s,typeName:Li.ZodNullable,...lo(t)});class lje extends Zo{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===Aa.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}lje.create=(s,t)=>new lje({innerType:s,typeName:Li.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...lo(t)});class cje extends Zo{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Nde(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new wv(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new wv(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}cje.create=(s,t)=>new cje({innerType:s,typeName:Li.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...lo(t)});class BRe extends Zo{_parse(t){if(this._getType(t)!==Aa.nan){const n=this._getOrReturnCtx(t);return aa(n,{code:jn.invalid_type,expected:Aa.nan,received:n.parsedType}),Ii}return{status:"valid",value:t.data}}}BRe.create=s=>new BRe({typeName:Li.ZodNaN,...lo(s)});class e6t extends Zo{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class n4e extends Zo{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ii:i.status==="dirty"?(r.dirty(),ID(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Ii:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(t,r){return new n4e({in:t,out:r,typeName:Li.ZodPipeline})}}class dje extends Zo{_parse(t){const r=this._def.innerType._parse(t),n=a=>(SM(a)&&(a.value=Object.freeze(a.value)),a);return Nde(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}dje.create=(s,t)=>new dje({innerType:s,typeName:Li.ZodReadonly,...lo(t)});jd.lazycreate;var Li;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(Li||(Li={}));const io=Pw.create,aO=CM.create,t6t=aje.create;Ij.create;mv.create;const qb=jd.create;jd.strictCreate;Sde.create;Cde.create;L3.create;const Vx=oje.create,cet=TM.create;Tde.create;mj.create;AM.create;const or=k.forwardRef(({className:s,...t},r)=>e.jsx("textarea",{className:It("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:r,...t}));or.displayName="Textarea";const s6t=["Excellent","Good","Neutral","Bad","Very Bad"],r6t=[5,4,3,2,1];function n6t({questions:s,visitorId:t,onComplete:r,onSkip:n}){const a=DMt(),[i,l]=k.useState({}),o=s.filter(x=>x.question_type==="rating"),c=s.filter(x=>x.question_type!=="rating"),d=(x,y)=>{l(v=>({...v,[x]:{rating_value:y}}))},h=(x,y)=>{l(v=>({...v,[x]:{text_value:y}}))},m=async()=>{const x=Object.entries(i).filter(([,y])=>y.rating_value!=null||y.text_value&&y.text_value.trim()).map(([y,v])=>{var w;return{visitor_id:t,question_id:y,rating_value:v.rating_value??null,text_value:((w=v.text_value)==null?void 0:w.trim())||null}});if(x.length>0)try{await a.mutateAsync(x)}catch{}r()};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:n,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"}),s6t.map(x=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:x})},x))]}),o.map(x=>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:x.question_text}),r6t.map(y=>{var v;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(x.id,y),className:`w-6 h-6 rounded-full border-2 transition-all ${((v=i[x.id])==null?void 0:v.rating_value)===y?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},y)})]},x.id))]}),c.map(x=>{var y;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:x.question_text}),e.jsx(or,{value:((y=i[x.id])==null?void 0:y.text_value)||"",onChange:v=>h(x.id,v.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},x.id)}),e.jsx(G,{onClick:m,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(es,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var vfe="Checkbox",[a6t,CUs]=pd(vfe),[i6t,a4e]=a6t(vfe);function o6t(s){const{__scopeCheckbox:t,checked:r,children:n,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:h="on",internal_do_not_use_render:m}=s,[x,y]=Sh({prop:r,defaultProp:a??!1,onChange:c,caller:vfe}),[v,w]=k.useState(null),[b,N]=k.useState(null),S=k.useRef(!1),T=v?!!l||!!v.closest("form"):!0,A={checked:x,disabled:i,setChecked:y,control:v,setControl:w,name:o,form:l,value:h,hasConsumerStoppedPropagationRef:S,required:d,defaultChecked:fj(a)?!1:a,isFormControl:T,bubbleInput:b,setBubbleInput:N};return e.jsx(i6t,{scope:t,...A,children:l6t(m)?m(A):n})}var det="CheckboxTrigger",uet=k.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:r,...n},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:x,isFormControl:y,bubbleInput:v}=a4e(det,s),w=Ga(a,h),b=k.useRef(c);return k.useEffect(()=>{const N=i==null?void 0:i.form;if(N){const S=()=>m(b.current);return N.addEventListener("reset",S),()=>N.removeEventListener("reset",S)}},[i,m]),e.jsx(wn.button,{type:"button",role:"checkbox","aria-checked":fj(c)?"mixed":c,"aria-required":d,"data-state":xet(c),"data-disabled":o?"":void 0,disabled:o,value:l,...n,ref:w,onKeyDown:Vr(t,N=>{N.key==="Enter"&&N.preventDefault()}),onClick:Vr(r,N=>{m(S=>fj(S)?!0:!S),v&&y&&(x.current=N.isPropagationStopped(),x.current||N.stopPropagation())})})});uet.displayName=det;var i4e=k.forwardRef((s,t)=>{const{__scopeCheckbox:r,name:n,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:h,...m}=s;return e.jsx(o6t,{__scopeCheckbox:r,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:n,form:h,value:c,internal_do_not_use_render:({isFormControl:x})=>e.jsxs(e.Fragment,{children:[e.jsx(uet,{...m,ref:t,__scopeCheckbox:r}),x&&e.jsx(pet,{__scopeCheckbox:r})]})})});i4e.displayName=vfe;var het="CheckboxIndicator",met=k.forwardRef((s,t)=>{const{__scopeCheckbox:r,forceMount:n,...a}=s,i=a4e(het,r);return e.jsx(ru,{present:n||fj(i.checked)||i.checked===!0,children:e.jsx(wn.span,{"data-state":xet(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});met.displayName=het;var fet="CheckboxBubbleInput",pet=k.forwardRef(({__scopeCheckbox:s,...t},r)=>{const{control:n,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:h,form:m,bubbleInput:x,setBubbleInput:y}=a4e(fet,s),v=Ga(r,y),w=sB(i),b=UF(n);k.useEffect(()=>{const S=x;if(!S)return;const T=window.HTMLInputElement.prototype,I=Object.getOwnPropertyDescriptor(T,"checked").set,D=!a.current;if(w!==i&&I){const R=new Event("click",{bubbles:D});S.indeterminate=fj(i),I.call(S,fj(i)?!1:i),S.dispatchEvent(R)}},[x,w,i,a]);const N=k.useRef(fj(i)?!1:i);return e.jsx(wn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??N.current,required:o,disabled:c,name:d,value:h,form:m,...t,tabIndex:-1,ref:v,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});pet.displayName=fet;function l6t(s){return typeof s=="function"}function fj(s){return s==="indeterminate"}function xet(s){return fj(s)?"indeterminate":s?"checked":"unchecked"}const Si=k.forwardRef(({className:s,...t},r)=>e.jsx(i4e,{ref:r,className:It("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(met,{className:It("flex items-center justify-center text-current"),children:e.jsx(Kn,{className:"h-4 w-4"})})}));Si.displayName=i4e.displayName;const Jj=afe,o4e=VCe,c6t=ife,get=k.forwardRef(({className:s,...t},r)=>e.jsx(zI,{className:It("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:r}));get.displayName=zI.displayName;const d6t=r5("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"}}),Vb=k.forwardRef(({side:s="right",className:t,children:r,...n},a)=>e.jsxs(c6t,{children:[e.jsx(get,{}),e.jsxs($I,{ref:a,className:It(d6t({side:s}),t),...n,children:[r,e.jsxs(tB,{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(vr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Vb.displayName=$I.displayName;const e2=({className:s,...t})=>e.jsx("div",{className:It("flex flex-col space-y-2 text-center sm:text-left",s),...t});e2.displayName="SheetHeader";const t2=k.forwardRef(({className:s,...t},r)=>e.jsx(JF,{ref:r,className:It("text-lg font-semibold text-foreground",s),...t}));t2.displayName=JF.displayName;const l4e=k.forwardRef(({className:s,...t},r)=>e.jsx(eB,{ref:r,className:It("text-sm text-muted-foreground",s),...t}));l4e.displayName=eB.displayName;function uje(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function u6t({rooms:s}){var m;const[t,r]=k.useState(((m=s[0])==null?void 0:m.id)||""),[n,a]=k.useState(null),i=s.find(x=>x.id===t)||s[0],l=n!==null?i==null?void 0:i.media[n]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(x=>x===null||o===0?x:(x-1+o)%o),h=()=>a(x=>x===null||o===0?x:(x+1)%o);return k.useEffect(()=>{if(n===null)return;const x=y=>{y.key==="Escape"?c():y.key==="ArrowLeft"?d():y.key==="ArrowRight"&&h()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n,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(x=>e.jsxs("button",{onClick:()=>r(x.id),className:It("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===x.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[x.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:x.media.length})]},x.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((x,y)=>e.jsx("button",{onClick:()=>a(y),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:x.kind==="video"?e.jsxs(e.Fragment,{children:[uje(x.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:x.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(Jr,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:x.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},x.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," — ",(n??0)+1," / ",o]}),e.jsx("button",{onClick:x=>{x.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:x=>{x.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($o,{className:"h-6 w-6"})}),l.kind==="video"?uje(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:x=>x.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:x=>x.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:x=>x.stopPropagation()}),o>1&&e.jsx("button",{onClick:x=>{x.stopPropagation(),h()},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(va,{className:"h-6 w-6"})})]})]}):null}function h6t({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,h)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:h,total:c.media.length})})});const r=k.useRef(null),[n,a]=k.useState(0);k.useEffect(()=>{const c=r.current;if(!c)return;let d=0;const h=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const m=Math.round(c.scrollLeft/c.clientWidth);a(m)})};return c.addEventListener("scroll",h,{passive:!0}),()=>{c.removeEventListener("scroll",h),cancelAnimationFrame(d)}},[]);const i=c=>{const d=r.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[n])==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(m=>m.roomId===c.id),h=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:It("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",h?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:c.name},c.id)})})}),e.jsx("div",{ref:r,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"?uje(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,n-1)),disabled:n===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[e.jsx($o,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,n+1)),disabled:n===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx(va,{className:"h-4 w-4"})]})]})]})}const yve={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:xi},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:on},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:ln},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:wl}},m6t=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function f6t(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 p6t({openHouse:s,visitorId:t,visitorName:r,visitorEmail:n,visitorPhone:a,previewMode:i=!1}){var Te;const l=s.profiles,o=((Te=l==null?void 0:l.name)==null?void 0:Te.split(" ").map(xe=>xe[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,h]=k.useState(null),[m,x]=k.useState(""),[y,v]=k.useState(n||""),[w,b]=k.useState(a||""),[N,S]=k.useState(!1),[T,A]=k.useState(null),[I,D]=k.useState(""),[R,$]=k.useState(""),[F,z]=k.useState(""),[Q,K]=k.useState([]),[X,Z]=k.useState(""),[re,le]=k.useState(""),[oe,ne]=k.useState(""),[ie,ye]=k.useState(""),ce=f6t(s.price),ve=s.tour_mode==="rooms",{data:be=[]}=HMt(ve?s.id:void 0),Ue=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Be=xe=>{h(xe),x(""),D(""),$(""),z(""),K([]),Z(""),le(""),ne(""),ye("")},De=()=>{h(null)},Ae=xe=>{K(et=>et.includes(xe)?et.filter(fe=>fe!==xe):[...et,xe])},He=xe=>xe==="showing"?{preferred_date:I||null,preferred_time:R||null,alternate_date:F||null}:xe==="disclosure"?{requested_documents:Q}:xe==="offer"?{offer_amount:X||null,financing:re||null,timeline:oe||null,pre_approved:ie||null}:{},Le=d?d==="showing"?!!I:d==="question"?m.trim().length>0:!0:!1,Ie=async()=>{if(d){if(i){cn({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{h(null),A(null)},1500);return}S(!0);try{const xe=He(d),{error:et}=await V.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:m.trim()||null,email:y.trim()||null,phone:w.trim()||null,visitor_name:r,...xe}});if(et)throw et;V.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:m.trim()||null,visitor_name:r,visitor_email:y.trim()||null,visitor_phone:w.trim()||null,extras:xe}}).catch(()=>{}),A(d),cn({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{De(),A(null)},1400)}catch(xe){cn({title:"Something went wrong",description:xe.message,variant:"destructive"})}finally{S(!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(Ca,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),ce&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ce}),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(Ny,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Xf,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(og,{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(Nn,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(ya,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(kn,{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(Cn,{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&&be.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(u6t,{rooms:be}),e.jsx(h6t,{rooms:be})]}),Ue.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:Ue.map(xe=>{const et=yve[xe],fe=et.icon;return e.jsxs("button",{onClick:()=>Be(xe),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(fe,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:et.label})]},xe)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(Jj,{open:!!d,onOpenChange:xe=>!xe&&De(),children:e.jsx(Vb,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(e2,{className:"text-left",children:[e.jsx(t2,{children:yve[d].title}),e.jsxs(l4e,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),T===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(In,{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(he,{className:"text-xs",children:"Email"}),e.jsx(Ne,{type:"email",value:y,onChange:xe=>v(xe.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Phone"}),e.jsx(Ne,{type:"tel",value:w,onChange:xe=>b(xe.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(he,{className:"text-xs",children:"Preferred date *"}),e.jsx(Ne,{type:"date",value:I,onChange:xe=>D(xe.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Preferred time"}),e.jsx(Ne,{type:"time",value:R,onChange:xe=>$(xe.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(Ne,{type:"date",value:F,onChange:xe=>z(xe.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:m6t.map(xe=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Si,{checked:Q.includes(xe),onCheckedChange:()=>Ae(xe)}),e.jsx("span",{children:xe})]},xe))})]}),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(he,{className:"text-xs",children:"Estimated offer"}),e.jsx(Ne,{value:X,onChange:xe=>Z(xe.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Financing"}),e.jsxs(Is,{value:re,onValueChange:le,children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{placeholder:"Select..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"Cash",children:"Cash"}),e.jsx(ct,{value:"Conventional",children:"Conventional"}),e.jsx(ct,{value:"FHA",children:"FHA"}),e.jsx(ct,{value:"VA",children:"VA"}),e.jsx(ct,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Timeline"}),e.jsxs(Is,{value:oe,onValueChange:ne,children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{placeholder:"Select..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"ASAP",children:"ASAP"}),e.jsx(ct,{value:"30 days",children:"30 days"}),e.jsx(ct,{value:"60 days",children:"60 days"}),e.jsx(ct,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(Is,{value:ie,onValueChange:ye,children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{placeholder:"Select..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"Yes",children:"Yes"}),e.jsx(ct,{value:"No",children:"No"}),e.jsx(ct,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(or,{value:m,onChange:xe=>x(xe.target.value),placeholder:yve[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(G,{onClick:Ie,disabled:N||!Le,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:N?e.jsx(es,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const x6t=qb({first_name:io().trim().min(1,"First name is required").max(50),last_name:io().trim().max(50).optional(),email:io().trim().email("Please enter a valid email").max(255).optional().or(Vx("")),phone:io().trim().max(20).optional().or(Vx(""))}),g6t=[{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 yet({slug:s}={}){var Le;const t=Ki(),r=s||t.slug,{data:n,isLoading:a,error:i}=IMt(r),l=$Mt(),o=UMt(),c=qMt(),d=k.useRef(!1),[h,m]=k.useState("welcome"),[x,y]=k.useState(null),[v,w]=k.useState({first_name:"",last_name:"",email:"",phone:""}),[b,N]=k.useState(""),[S,T]=k.useState(!1),[A,I]=k.useState(!1),[D,R]=k.useState(""),[$,F]=k.useState(""),{data:z,isLoading:Q}=PMt(n==null?void 0:n.id),K=!!(n!=null&&n.enable_survey),X=(n==null?void 0:n.ask_visitor_intent)!==!1;k.useEffect(()=>{if(!r||!(n!=null&&n.id)||d.current)return;const Ie=`oh_scan_${n.id}`;if(sessionStorage.getItem(Ie)){d.current=!0;return}d.current=!0,sessionStorage.setItem(Ie,"1"),c.mutate(r)},[r,n==null?void 0:n.id]),k.useEffect(()=>{h==="pending_survey"&&(Q||m(K&&((z==null?void 0:z.length)??0)>0?"survey":"done"))},[h,Q,K,z]);const Z=Ie=>{if(!Ie)return"";const[Te,xe]=Ie.split(":"),et=parseInt(Te),fe=et>=12?"PM":"AM";return`${et>12?et-12:et||12}:${xe} ${fe}`},re=async()=>{F("");const Ie=x6t.safeParse(v);if(!Ie.success){F(Ie.error.issues[0].message);return}if(!v.email&&!v.phone){F("Please provide either an email or phone number");return}const Te=(n==null?void 0:n.kind)==="virtual";if(!x&&(n!=null&&n.id))try{const xe=await l.mutateAsync({open_house_id:n.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,wants_market_updates:S,has_agent:A,working_with_agent_name:A&&D.trim()?D.trim():void 0,partial_signin:Te?!1:X});y(xe.id)}catch{if(Te){F("We could not start the virtual tour. Please try again.");return}}if(Te){m(X?"intent":"done");return}if(!X){K?!Q&&z&&z.length>0?m("survey"):m("pending_survey"):m("done");return}m("intent")},le=async Ie=>{N(Ie);try{let Te=x;if(Te?await o.mutateAsync({visitor_id:Te,visitor_intent:Ie,wants_market_updates:S,has_agent:A,working_with_agent_name:A&&D.trim()?D.trim():null,partial_signin:!1}):(Te=(await l.mutateAsync({open_house_id:n.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,visitor_intent:Ie,wants_market_updates:S,has_agent:A,working_with_agent_name:A&&D.trim()?D.trim():void 0,partial_signin:!1})).id,y(Te)),(n==null?void 0:n.kind)==="virtual"){m("done");return}K?!Q&&z&&z.length>0?m("survey"):m("pending_survey"):m("done")}catch{F("Something went wrong. Please try again.")}};if(a)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(i||!n)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(En,{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 oe=n.profiles,ne=((Le=oe==null?void 0:oe.name)==null?void 0:Le.split(" ").map(Ie=>Ie[0]).join("").slice(0,2))||"?",ie=n.event_type==="community",ye=n.kind==="virtual",ce=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(ye&&(ce||h==="done"))return!ce&&!x?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(nl,{children:[e.jsxs("title",{children:["Virtual Tour | ",n.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${n.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),ce&&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(p6t,{openHouse:n,visitorId:ce?"preview":x,visitorName:ce?"Preview Visitor":`${v.first_name} ${v.last_name}`.trim(),visitorEmail:ce?"":v.email,visitorPhone:ce?"":v.phone,previewMode:ce})]});const be=`${ye?"Virtual Open House":ie?"Community Event":"Open House"} — ${n.property_address}`,Be=[[n.city,n.state].filter(Boolean).join(", "),n.event_date?_s(new Date(n.event_date+"T00:00:00"),"EEE, MMM d"):null,oe!=null&&oe.name?`Hosted by ${oe.name}`:null].filter(Boolean).join(" · "),De=n.photo_url||"",Ae=De&&De.includes("/storage/v1/object/public/")?De.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":De||"https://dashboard.relevelup.com/og-image.png",He=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return e.jsxs(e.Fragment,{children:[e.jsxs(nl,{children:[e.jsx("title",{children:be}),e.jsx("meta",{name:"description",content:Be||`Sign in to ${n.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:Be||`Sign in to ${n.property_address}`}),e.jsx("meta",{property:"og:image",content:Ae}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{property:"og:url",content:He}),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:Be||`Sign in to ${n.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ae}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsxs(Nn,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(ya,{src:(oe==null?void 0:oe.avatar_url)||"",alt:(oe==null?void 0:oe.name)||""}),e.jsx(kn,{className:"bg-white/10 text-white text-lg",children:ne})]}),e.jsx("p",{className:"text-white/60 text-sm",children:oe==null?void 0:oe.name}),(oe==null?void 0:oe.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:oe.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[n.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:n.photo_url,alt:n.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:n.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[n.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),n.city,n.state?`, ${n.state}`:""," ",n.zip]}),!ye&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),_s(new Date(n.event_date+"T00:00:00"),"MMM d, yyyy")]}),n.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),Z(n.start_time),n.end_time?` – ${Z(n.end_time)}`:""]})]})]})]})]}),!n.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:ie?e.jsx(Sa,{className:"h-5 w-5 text-white"}):e.jsx(En,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:n.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[n.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),n.city,n.state?`, ${n.state}`:""," ",n.zip]}),!ye&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),_s(new Date(n.event_date+"T00:00:00"),"MMM d, yyyy")]}),n.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),Z(n.start_time),n.end_time?` – ${Z(n.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[h==="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:n.agent_greeting||"Please sign in below."})]}),e.jsxs(G,{onClick:()=>m("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Ha,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),h==="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:()=>m("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(Ne,{value:v.first_name,onChange:Ie=>w(Te=>({...Te,first_name:Ie.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(Ne,{value:v.last_name,onChange:Ie=>w(Te=>({...Te,last_name:Ie.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(Ne,{type:"email",value:v.email,onChange:Ie=>w(Te=>({...Te,email:Ie.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(Ne,{type:"tel",value:v.phone,onChange:Ie=>w(Te=>({...Te,phone:Ie.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:S,onChange:Ie=>T(Ie.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:A?"Yes":"No"}),e.jsx(_r,{checked:A,onCheckedChange:I})]})]}),A&&e.jsx(Ne,{value:D,onChange:Ie=>R(Ie.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),$&&e.jsx("p",{className:"text-destructive text-sm",children:$}),e.jsxs(G,{onClick:re,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Ha,{className:"h-5 w-5 ml-2"})]})]}),h==="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:()=>m("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"What brings you here?"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:g6t.map(Ie=>e.jsxs("button",{onClick:()=>le(Ie.value),disabled:l.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:Ie.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ie.label})]},Ie.value))}),$&&e.jsx("p",{className:"text-destructive text-sm text-center",children:$})]}),h==="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..."})]}),h==="survey"&&x&&z&&e.jsx(n6t,{questions:z,visitorId:x,onComplete:()=>m("done"),onSkip:()=>m("done")}),h==="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(In,{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, ",v.first_name,". ",ie?"Enjoy the event!":"Enjoy the open house!"]})]}),(n==null?void 0:n.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(n.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(ln,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(oe==null?void 0:oe.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:oe.name})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"})]})})]})}function TUs(s){const{user:t}=js();return mt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:r,error:n}=await V.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return r},enabled:!!t&&!!s})}function EUs(){const s=Xt(),{user:t}=js();return Ct({mutationFn:async({openHouseId:r,label:n})=>{const{data:a,error:i}=await V.from("open_house_cohost_tokens").insert({open_house_id:r,label:n||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function AUs(){const s=Xt();return Ct({mutationFn:async({id:t,openHouseId:r})=>{const{error:n}=await V.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function y6t(s){return mt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:r}=await V.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(r)throw r;if(t.expires_at&&new Date(t.expires_at)t[r][n]??r,s)}var c4e="ScrollArea",[vet,MUs]=pd(c4e),[b6t,bg]=vet(c4e),bet=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,type:n="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=k.useState(null),[d,h]=k.useState(null),[m,x]=k.useState(null),[y,v]=k.useState(null),[w,b]=k.useState(null),[N,S]=k.useState(0),[T,A]=k.useState(0),[I,D]=k.useState(!1),[R,$]=k.useState(!1),F=Ga(t,Q=>c(Q)),z=Kj(a);return e.jsx(b6t,{scope:r,type:n,dir:z,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:h,content:m,onContentChange:x,scrollbarX:y,onScrollbarXChange:v,scrollbarXEnabled:I,onScrollbarXEnabledChange:D,scrollbarY:w,onScrollbarYChange:b,scrollbarYEnabled:R,onScrollbarYEnabledChange:$,onCornerWidthChange:S,onCornerHeightChange:A,children:e.jsx(wn.div,{dir:z,...l,ref:F,style:{position:"relative","--radix-scroll-area-corner-width":N+"px","--radix-scroll-area-corner-height":T+"px",...s.style}})})});bet.displayName=c4e;var _et="ScrollAreaViewport",wet=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,children:n,nonce:a,...i}=s,l=bg(_et,r),o=k.useRef(null),c=Ga(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(wn.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:n})})]})});wet.displayName=_et;var Rv="ScrollAreaScrollbar",d4e=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=bg(Rv,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return k.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(_6t,{...n,ref:t,forceMount:r}):a.type==="scroll"?e.jsx(w6t,{...n,ref:t,forceMount:r}):a.type==="auto"?e.jsx(jet,{...n,ref:t,forceMount:r}):a.type==="always"?e.jsx(u4e,{...n,ref:t}):null});d4e.displayName=Rv;var _6t=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=bg(Rv,s.__scopeScrollArea),[i,l]=k.useState(!1);return k.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},h=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",h),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",h)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(ru,{present:r||i,children:e.jsx(jet,{"data-state":i?"visible":"hidden",...n,ref:t})})}),w6t=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=bg(Rv,s.__scopeScrollArea),i=s.orientation==="horizontal",l=_fe(()=>c("SCROLL_END"),100),[o,c]=v6t("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 k.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),k.useEffect(()=>{const d=a.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const x=()=>{const y=d[h];m!==y&&(c("SCROLL"),l()),m=y};return d.addEventListener("scroll",x),()=>d.removeEventListener("scroll",x)}},[a.viewport,i,c,l]),e.jsx(ru,{present:r||o!=="hidden",children:e.jsx(u4e,{"data-state":o==="hidden"?"hidden":"visible",...n,ref:t,onPointerEnter:Vr(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Vr(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),jet=k.forwardRef((s,t)=>{const r=bg(Rv,s.__scopeScrollArea),{forceMount:n,...a}=s,[i,l]=k.useState(!1),o=s.orientation==="horizontal",c=_fe(()=>{if(r.viewport){const d=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=s,a=bg(Rv,s.__scopeScrollArea),i=k.useRef(null),l=k.useRef(0),[o,c]=k.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Eet(o.viewport,o.content),h={...n,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:x=>i.current=x,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:x=>l.current=x};function m(x,y){return T6t(x,l.current,o,y)}return r==="horizontal"?e.jsx(j6t,{...h,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const x=a.viewport.scrollLeft,y=zRe(x,o,a.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:x=>{a.viewport&&(a.viewport.scrollLeft=x)},onDragScroll:x=>{a.viewport&&(a.viewport.scrollLeft=m(x,a.dir))}}):r==="vertical"?e.jsx(N6t,{...h,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const x=a.viewport.scrollTop,y=zRe(x,o);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:x=>{a.viewport&&(a.viewport.scrollTop=x)},onDragScroll:x=>{a.viewport&&(a.viewport.scrollTop=m(x))}}):null}),j6t=k.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=bg(Rv,s.__scopeScrollArea),[l,o]=k.useState(),c=k.useRef(null),d=Ga(t,c,i.onScrollbarXChange);return k.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(ket,{"data-orientation":"horizontal",...a,ref:d,sizes:r,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":bfe(r)+"px",...s.style},onThumbPointerDown:h=>s.onThumbPointerDown(h.x),onDragScroll:h=>s.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const x=i.viewport.scrollLeft+h.deltaX;s.onWheelScroll(x),Met(x,m)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:Ade(l.paddingLeft),paddingEnd:Ade(l.paddingRight)}})}})}),N6t=k.forwardRef((s,t)=>{const{sizes:r,onSizesChange:n,...a}=s,i=bg(Rv,s.__scopeScrollArea),[l,o]=k.useState(),c=k.useRef(null),d=Ga(t,c,i.onScrollbarYChange);return k.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(ket,{"data-orientation":"vertical",...a,ref:d,sizes:r,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":bfe(r)+"px",...s.style},onThumbPointerDown:h=>s.onThumbPointerDown(h.y),onDragScroll:h=>s.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const x=i.viewport.scrollTop+h.deltaY;s.onWheelScroll(x),Met(x,m)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&n({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:Ade(l.paddingTop),paddingEnd:Ade(l.paddingBottom)}})}})}),[k6t,Net]=vet(Rv),ket=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:m,...x}=s,y=bg(Rv,r),[v,w]=k.useState(null),b=Ga(t,F=>w(F)),N=k.useRef(null),S=k.useRef(""),T=y.viewport,A=n.content-n.viewport,I=Ed(h),D=Ed(c),R=_fe(m,10);function $(F){if(N.current){const z=F.clientX-N.current.left,Q=F.clientY-N.current.top;d({x:z,y:Q})}}return k.useEffect(()=>{const F=z=>{const Q=z.target;(v==null?void 0:v.contains(Q))&&I(z,A)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[T,v,A,I]),k.useEffect(D,[n,D]),MM(v,R),MM(y.content,R),e.jsx(k6t,{scope:r,scrollbar:v,hasThumb:a,onThumbChange:Ed(i),onThumbPointerUp:Ed(l),onThumbPositionChange:D,onThumbPointerDown:Ed(o),children:e.jsx(wn.div,{...x,ref:b,style:{position:"absolute",...x.style},onPointerDown:Vr(s.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),N.current=v.getBoundingClientRect(),S.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),$(F))}),onPointerMove:Vr(s.onPointerMove,$),onPointerUp:Vr(s.onPointerUp,F=>{const z=F.target;z.hasPointerCapture(F.pointerId)&&z.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=S.current,y.viewport&&(y.viewport.style.scrollBehavior=""),N.current=null})})})}),Ede="ScrollAreaThumb",Cet=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=Net(Ede,s.__scopeScrollArea);return e.jsx(ru,{present:r||a.hasThumb,children:e.jsx(S6t,{ref:t,...n})})}),S6t=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,style:n,...a}=s,i=bg(Ede,r),l=Net(Ede,r),{onThumbPositionChange:o}=l,c=Ga(t,m=>l.onThumbChange(m)),d=k.useRef(void 0),h=_fe(()=>{d.current&&(d.current(),d.current=void 0)},100);return k.useEffect(()=>{const m=i.viewport;if(m){const x=()=>{if(h(),!d.current){const y=E6t(m,o);d.current=y,o()}};return o(),m.addEventListener("scroll",x),()=>m.removeEventListener("scroll",x)}},[i.viewport,h,o]),e.jsx(wn.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)",...n},onPointerDownCapture:Vr(s.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),v=m.clientX-y.left,w=m.clientY-y.top;l.onThumbPointerDown({x:v,y:w})}),onPointerUp:Vr(s.onPointerUp,l.onThumbPointerUp)})});Cet.displayName=Ede;var h4e="ScrollAreaCorner",Tet=k.forwardRef((s,t)=>{const r=bg(h4e,s.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?e.jsx(C6t,{...s,ref:t}):null});Tet.displayName=h4e;var C6t=k.forwardRef((s,t)=>{const{__scopeScrollArea:r,...n}=s,a=bg(h4e,r),[i,l]=k.useState(0),[o,c]=k.useState(0),d=!!(i&&o);return MM(a.scrollbarX,()=>{var m;const h=((m=a.scrollbarX)==null?void 0:m.offsetHeight)||0;a.onCornerHeightChange(h),c(h)}),MM(a.scrollbarY,()=>{var m;const h=((m=a.scrollbarY)==null?void 0:m.offsetWidth)||0;a.onCornerWidthChange(h),l(h)}),d?e.jsx(wn.div,{...n,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 Ade(s){return s?parseInt(s,10):0}function Eet(s,t){const r=s/t;return isNaN(r)?0:r}function bfe(s){const t=Eet(s.viewport,s.content),r=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,n=(s.scrollbar.size-r)*t;return Math.max(n,18)}function T6t(s,t,r,n="ltr"){const a=bfe(r),i=a/2,l=t||i,o=a-l,c=r.scrollbar.paddingStart+l,d=r.scrollbar.size-r.scrollbar.paddingEnd-o,h=r.content-r.viewport,m=n==="ltr"?[0,h]:[h*-1,0];return Aet([c,d],m)(s)}function zRe(s,t,r="ltr"){const n=bfe(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,l=t.content-t.viewport,o=i-n,c=r==="ltr"?[0,l]:[l*-1,0],d=f8(s,c);return Aet([0,l],[0,o])(d)}function Aet(s,t){return r=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(s[1]-s[0]);return t[0]+n*(r-s[0])}}function Met(s,t){return s>0&&s{})=>{let r={left:s.scrollLeft,top:s.scrollTop},n=0;return function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=r.left!==i.left,o=r.top!==i.top;(l||o)&&t(),r=i,n=window.requestAnimationFrame(a)}(),()=>window.cancelAnimationFrame(n)};function _fe(s,t){const r=Ed(s),n=k.useRef(0);return k.useEffect(()=>()=>window.clearTimeout(n.current),[]),k.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,t)},[r,t])}function MM(s,t){const r=Ed(t);Dd(()=>{let n=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return a.observe(s),()=>{window.cancelAnimationFrame(n),a.unobserve(s)}}},[s,r])}var Iet=bet,A6t=wet,M6t=Tet;const Qa=k.forwardRef(({className:s,children:t,...r},n)=>e.jsxs(Iet,{ref:n,className:It("relative overflow-hidden",s),...r,children:[e.jsx(A6t,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(wfe,{}),e.jsx(M6t,{})]}));Qa.displayName=Iet.displayName;const wfe=k.forwardRef(({className:s,orientation:t="vertical",...r},n)=>e.jsx(d4e,{ref:n,orientation:t,className:It("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),...r,children:e.jsx(Cet,{className:"relative flex-1 rounded-full bg-border"})}));wfe.displayName=d4e.displayName;const m4e=k.createContext({});function f4e(s){const t=k.useRef(null);return t.current===null&&(t.current=s()),t.current}const I6t=typeof window<"u",Let=I6t?k.useLayoutEffect:k.useEffect,jfe=k.createContext(null);function p4e(s,t){s.indexOf(t)===-1&&s.push(t)}function Mde(s,t){const r=s.indexOf(t);r>-1&&s.splice(r,1)}const jv=(s,t,r)=>r>t?t:r{},IM=()=>{};const Lj={},Pet=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function Det(s){return typeof s=="object"&&s!==null}const Ret=s=>/^0[^.\s]+$/u.test(s);function Oet(s){let t;return()=>(t===void 0&&(t=s()),t)}const cg=s=>s,L6t=(s,t)=>r=>t(s(r)),nB=(...s)=>s.reduce(L6t),g8=(s,t,r)=>{const n=t-s;return n===0?1:(r-s)/n};class x4e{constructor(){this.subscriptions=[]}add(t){return p4e(this.subscriptions,t),()=>Mde(this.subscriptions,t)}notify(t,r,n){const a=this.subscriptions.length;if(a)if(a===1)this.subscriptions[0](t,r,n);else for(let i=0;is*1e3,tg=s=>s/1e3;function Fet(s,t){return t?s*(1e3/t):0}const Bet=(s,t,r)=>(((1-3*r+3*t)*s+(3*r-6*t))*s+3*t)*s,P6t=1e-7,D6t=12;function R6t(s,t,r,n,a){let i,l,o=0;do l=t+(r-t)/2,i=Bet(l,n,a)-s,i>0?r=l:t=l;while(Math.abs(i)>P6t&&++oR6t(i,0,1,s,r);return i=>i===0||i===1?i:Bet(a(i),t,n)}const zet=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,$et=s=>t=>1-s(1-t),Uet=aB(.33,1.53,.69,.99),g4e=$et(Uet),qet=zet(g4e),Vet=s=>s>=1?1:(s*=2)<1?.5*g4e(s):.5*(2-Math.pow(2,-10*(s-1))),y4e=s=>1-Math.sin(Math.acos(s)),Het=$et(y4e),Get=zet(y4e),O6t=aB(.42,0,1,1),F6t=aB(0,0,.58,1),Wet=aB(.42,0,.58,1),B6t=s=>Array.isArray(s)&&typeof s[0]!="number",Ket=s=>Array.isArray(s)&&typeof s[0]=="number",$Re={linear:cg,easeIn:O6t,easeInOut:Wet,easeOut:F6t,circIn:y4e,circInOut:Get,circOut:Het,backIn:g4e,backInOut:qet,backOut:Uet,anticipate:Vet},z6t=s=>typeof s=="string",URe=s=>{if(Ket(s)){IM(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,r,n,a]=s;return aB(t,r,n,a)}else if(z6t(s))return IM($Re[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),$Re[s];return s},G9=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],qRe={value:null,addProjectionMetrics:null};function $6t(s,t){let r=new Set,n=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(m){l.has(m)&&(h.schedule(m),s()),c++,m(o)}const h={schedule:(m,x=!1,y=!1)=>{const w=y&&a?r:n;return x&&l.add(m),w.add(m),m},cancel:m=>{n.delete(m),l.delete(m)},process:m=>{if(o=m,a){i=!0;return}a=!0;const x=r;r=n,n=x,r.forEach(d),t&&qRe.value&&qRe.value.frameloop[t].push(c),c=0,r.clear(),a=!1,i&&(i=!1,h.process(m))}};return h}const U6t=40;function Yet(s,t){let r=!1,n=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>r=!0,l=G9.reduce((T,A)=>(T[A]=$6t(i,t?A:void 0),T),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:h,update:m,preRender:x,render:y,postRender:v}=l,w=()=>{const T=Lj.useManualTiming,A=T?a.timestamp:performance.now();r=!1,T||(a.delta=n?1e3/60:Math.max(Math.min(A-a.timestamp,U6t),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),h.process(a),m.process(a),x.process(a),y.process(a),v.process(a),a.isProcessing=!1,r&&t&&(n=!1,s(w))},b=()=>{r=!0,n=!0,a.isProcessing||s(w)};return{schedule:G9.reduce((T,A)=>{const I=l[A];return T[A]=(D,R=!1,$=!1)=>(r||b(),I.schedule(D,R,$)),T},{}),cancel:T=>{for(let A=0;A(ice===void 0&&af.set($h.isProcessing||Lj.useManualTiming?$h.timestamp:performance.now()),ice),set:s=>{ice=s,queueMicrotask(q6t)}},Zet=s=>t=>typeof t=="string"&&t.startsWith(s),Xet=Zet("--"),V6t=Zet("var(--"),v4e=s=>V6t(s)?H6t.test(s.split("/*")[0].trim()):!1,H6t=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function VRe(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const qI={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},y8={...qI,transform:s=>jv(0,1,s)},W9={...qI,default:1},iO=s=>Math.round(s*1e5)/1e5,b4e=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function G6t(s){return s==null}const W6t=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,_4e=(s,t)=>r=>!!(typeof r=="string"&&W6t.test(r)&&r.startsWith(s)||t&&!G6t(r)&&Object.prototype.hasOwnProperty.call(r,t)),Qet=(s,t,r)=>n=>{if(typeof n!="string")return n;const[a,i,l,o]=n.match(b4e);return{[s]:parseFloat(a),[t]:parseFloat(i),[r]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},K6t=s=>jv(0,255,s),bve={...qI,transform:s=>Math.round(K6t(s))},s4={test:_4e("rgb","red"),parse:Qet("red","green","blue"),transform:({red:s,green:t,blue:r,alpha:n=1})=>"rgba("+bve.transform(s)+", "+bve.transform(t)+", "+bve.transform(r)+", "+iO(y8.transform(n))+")"};function Y6t(s){let t="",r="",n="",a="";return s.length>5?(t=s.substring(1,3),r=s.substring(3,5),n=s.substring(5,7),a=s.substring(7,9)):(t=s.substring(1,2),r=s.substring(2,3),n=s.substring(3,4),a=s.substring(4,5),t+=t,r+=r,n+=n,a+=a),{red:parseInt(t,16),green:parseInt(r,16),blue:parseInt(n,16),alpha:a?parseInt(a,16)/255:1}}const hje={test:_4e("#"),parse:Y6t,transform:s4.transform},iB=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),Y_=iB("deg"),fv=iB("%"),wa=iB("px"),Z6t=iB("vh"),X6t=iB("vw"),HRe={...fv,parse:s=>fv.parse(s)/100,transform:s=>fv.transform(s*100)},UE={test:_4e("hsl","hue"),parse:Qet("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:r,alpha:n=1})=>"hsla("+Math.round(s)+", "+fv.transform(iO(t))+", "+fv.transform(iO(r))+", "+iO(y8.transform(n))+")"},hu={test:s=>s4.test(s)||hje.test(s)||UE.test(s),parse:s=>s4.test(s)?s4.parse(s):UE.test(s)?UE.parse(s):hje.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?s4.transform(s):UE.transform(s),getAnimatableNone:s=>{const t=hu.parse(s);return t.alpha=0,hu.transform(t)}},Q6t=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function J6t(s){var t,r;return isNaN(s)&&typeof s=="string"&&(((t=s.match(b4e))==null?void 0:t.length)||0)+(((r=s.match(Q6t))==null?void 0:r.length)||0)>0}const Jet="number",ett="color",eDt="var",tDt="var(",GRe="${}",sDt=/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 LM(s){const t=s.toString(),r=[],n={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(sDt,c=>(hu.test(c)?(n.color.push(i),a.push(ett),r.push(hu.parse(c))):c.startsWith(tDt)?(n.var.push(i),a.push(eDt),r.push(c)):(n.number.push(i),a.push(Jet),r.push(parseFloat(c))),++i,GRe)).split(GRe);return{values:r,split:o,indexes:n,types:a}}function rDt(s){return LM(s).values}function ttt({split:s,types:t}){const r=s.length;return n=>{let a="";for(let i=0;itypeof s=="number"?0:hu.test(s)?hu.getAnimatableNone(s):s,iDt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:aDt(s);function oDt(s){const t=LM(s);return ttt(t)(t.values.map((n,a)=>iDt(n,t.split[a])))}const My={test:J6t,parse:rDt,createTransformer:nDt,getAnimatableNone:oDt};function _ve(s,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?s+(t-s)*6*r:r<1/2?t:r<2/3?s+(t-s)*(2/3-r)*6:s}function lDt({hue:s,saturation:t,lightness:r,alpha:n}){s/=360,t/=100,r/=100;let a=0,i=0,l=0;if(!t)a=i=l=r;else{const o=r<.5?r*(1+t):r+t-r*t,c=2*r-o;a=_ve(c,o,s+1/3),i=_ve(c,o,s),l=_ve(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:n}}function Ide(s,t){return r=>r>0?t:s}const Cc=(s,t,r)=>s+(t-s)*r,wve=(s,t,r)=>{const n=s*s,a=r*(t*t-n)+n;return a<0?0:Math.sqrt(a)},cDt=[hje,s4,UE],dDt=s=>cDt.find(t=>t.test(s));function WRe(s){const t=dDt(s);if(Nfe(!!t,`'${s}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let r=t.parse(s);return t===UE&&(r=lDt(r)),r}const KRe=(s,t)=>{const r=WRe(s),n=WRe(t);if(!r||!n)return Ide(s,t);const a={...r};return i=>(a.red=wve(r.red,n.red,i),a.green=wve(r.green,n.green,i),a.blue=wve(r.blue,n.blue,i),a.alpha=Cc(r.alpha,n.alpha,i),s4.transform(a))},mje=new Set(["none","hidden"]);function uDt(s,t){return mje.has(s)?r=>r<=0?s:t:r=>r>=1?t:s}function hDt(s,t){return r=>Cc(s,t,r)}function w4e(s){return typeof s=="number"?hDt:typeof s=="string"?v4e(s)?Ide:hu.test(s)?KRe:pDt:Array.isArray(s)?stt:typeof s=="object"?hu.test(s)?KRe:mDt:Ide}function stt(s,t){const r=[...s],n=r.length,a=s.map((i,l)=>w4e(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in n)r[i]=n[i](a);return r}}function fDt(s,t){const r=[],n={color:0,var:0,number:0};for(let a=0;a{const r=My.createTransformer(t),n=LM(s),a=LM(t);return n.indexes.var.length===a.indexes.var.length&&n.indexes.color.length===a.indexes.color.length&&n.indexes.number.length>=a.indexes.number.length?mje.has(s)&&!a.values.length||mje.has(t)&&!n.values.length?uDt(s,t):nB(stt(fDt(n,a),a.values),r):(Nfe(!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"),Ide(s,t))};function rtt(s,t,r){return typeof s=="number"&&typeof t=="number"&&typeof r=="number"?Cc(s,t,r):w4e(s)(s,t)}const xDt=s=>{const t=({timestamp:r})=>s(r);return{start:(r=!0)=>Zl.update(t,r),stop:()=>Pj(t),now:()=>$h.isProcessing?$h.timestamp:af.now()}},ntt=(s,t,r=10)=>{let n="";const a=Math.max(Math.round(t/r),2);for(let i=0;i=Lde?1/0:t}function gDt(s,t=100,r){const n=r({...s,keyframes:[0,t]}),a=Math.min(j4e(n),Lde);return{type:"keyframes",ease:i=>n.next(a*i).value/t,duration:tg(a)}}const rd={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 fje(s,t){return s*Math.sqrt(1-t*t)}const yDt=12;function vDt(s,t,r){let n=r;for(let a=1;a{const h=d*l,m=h*s,x=h-r,y=fje(d,l),v=Math.exp(-m);return jve-x/y*v},i=d=>{const m=d*l*s,x=m*r+r,y=Math.pow(l,2)*Math.pow(d,2)*s,v=Math.exp(-m),w=fje(Math.pow(d,2),l);return(-a(d)+jve>0?-1:1)*((x-y)*v)/w}):(a=d=>{const h=Math.exp(-d*s),m=(d-r)*s+1;return-jve+h*m},i=d=>{const h=Math.exp(-d*s),m=(r-d)*(s*s);return h*m});const o=5/s,c=vDt(a,i,o);if(s=tp(s),isNaN(c))return{stiffness:rd.stiffness,damping:rd.damping,duration:s};{const d=Math.pow(c,2)*n;return{stiffness:d,damping:l*2*Math.sqrt(n*d),duration:s}}}const _Dt=["duration","bounce"],wDt=["stiffness","damping","mass"];function YRe(s,t){return t.some(r=>s[r]!==void 0)}function jDt(s){let t={velocity:rd.velocity,stiffness:rd.stiffness,damping:rd.damping,mass:rd.mass,isResolvedFromDuration:!1,...s};if(!YRe(s,wDt)&&YRe(s,_Dt))if(t.velocity=0,s.visualDuration){const r=s.visualDuration,n=2*Math.PI/(r*1.2),a=n*n,i=2*jv(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:rd.mass,stiffness:a,damping:i}}else{const r=bDt({...s,velocity:0});t={...t,...r,mass:rd.mass},t.isResolvedFromDuration=!0}return t}function Pde(s=rd.visualDuration,t=rd.bounce){const r=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:n,restDelta:a}=r;const i=r.keyframes[0],l=r.keyframes[r.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:h,duration:m,velocity:x,isResolvedFromDuration:y}=jDt({...r,velocity:-tg(r.velocity||0)}),v=x||0,w=d/(2*Math.sqrt(c*h)),b=l-i,N=tg(Math.sqrt(c/h)),S=Math.abs(b)<5;n||(n=S?rd.restSpeed.granular:rd.restSpeed.default),a||(a=S?rd.restDelta.granular:rd.restDelta.default);let T,A,I,D,R,$;if(w<1)I=fje(N,w),D=(v+w*N*b)/I,T=z=>{const Q=Math.exp(-w*N*z);return l-Q*(D*Math.sin(I*z)+b*Math.cos(I*z))},R=w*N*D+b*I,$=w*N*b-D*I,A=z=>Math.exp(-w*N*z)*(R*Math.sin(I*z)+$*Math.cos(I*z));else if(w===1){T=Q=>l-Math.exp(-N*Q)*(b+(v+N*b)*Q);const z=v+N*b;A=Q=>Math.exp(-N*Q)*(N*z*Q-v)}else{const z=N*Math.sqrt(w*w-1);T=Z=>{const re=Math.exp(-w*N*Z),le=Math.min(z*Z,300);return l-re*((v+w*N*b)*Math.sinh(le)+z*b*Math.cosh(le))/z};const Q=(v+w*N*b)/z,K=w*N*Q-b*z,X=w*N*b-Q*z;A=Z=>{const re=Math.exp(-w*N*Z),le=Math.min(z*Z,300);return re*(K*Math.sinh(le)+X*Math.cosh(le))}}const F={calculatedDuration:y&&m||null,velocity:z=>tp(A(z)),next:z=>{if(!y&&w<1){const K=Math.exp(-w*N*z),X=Math.sin(I*z),Z=Math.cos(I*z),re=l-K*(D*X+b*Z),le=tp(K*(R*X+$*Z));return o.done=Math.abs(le)<=n&&Math.abs(l-re)<=a,o.value=o.done?l:re,o}const Q=T(z);if(y)o.done=z>=m;else{const K=tp(A(z));o.done=Math.abs(K)<=n&&Math.abs(l-Q)<=a}return o.value=o.done?l:Q,o},toString:()=>{const z=Math.min(j4e(F),Lde),Q=ntt(K=>F.next(z*K).value,z,30);return z+"ms "+Q},toTransition:()=>{}};return F}Pde.applyToOptions=s=>{const t=gDt(s,100,Pde);return s.ease=t.ease,s.duration=tp(t.duration),s.type="keyframes",s};const NDt=5;function att(s,t,r){const n=Math.max(t-NDt,0);return Fet(r-s(n),t-n)}function pje({keyframes:s,velocity:t=0,power:r=.8,timeConstant:n=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:h}){const m=s[0],x={done:!1,value:m},y=$=>o!==void 0&&$c,v=$=>o===void 0?c:c===void 0||Math.abs(o-$)-w*Math.exp(-$/n),T=$=>N+S($),A=$=>{const F=S($),z=T($);x.done=Math.abs(F)<=d,x.value=x.done?N:z};let I,D;const R=$=>{y(x.value)&&(I=$,D=Pde({keyframes:[x.value,v(x.value)],velocity:att(T,$,x.value),damping:a,stiffness:i,restDelta:d,restSpeed:h}))};return R(0),{calculatedDuration:null,next:$=>{let F=!1;return!D&&I===void 0&&(F=!0,A($),R($)),I!==void 0&&$>=I?D.next($-I):(!F&&A($),x)}}}function kDt(s,t,r){const n=[],a=r||Lj.mix||rtt,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=kDt(t,n,a),c=o.length,d=h=>{if(l&&h1)for(;md(jv(s[0],s[i-1],h)):d}function CDt(s,t){const r=s[s.length-1];for(let n=1;n<=t;n++){const a=g8(0,t,n);s.push(Cc(r,1,a))}}function TDt(s){const t=[0];return CDt(t,s.length-1),t}function EDt(s,t){return s.map(r=>r*t)}function ADt(s,t){return s.map(()=>t||Wet).splice(0,s.length-1)}function oO({duration:s=300,keyframes:t,times:r,ease:n="easeInOut"}){const a=B6t(n)?n.map(URe):URe(n),i={done:!1,value:t[0]},l=EDt(r&&r.length===t.length?r:TDt(t),s),o=SDt(l,t,{ease:Array.isArray(a)?a:ADt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const MDt=s=>s!==null;function kfe(s,{repeat:t,repeatType:r="loop"},n,a=1){const i=s.filter(MDt),o=a<0||t&&r!=="loop"&&t%2===1?0:i.length-1;return!o||n===void 0?i[o]:n}const IDt={decay:pje,inertia:pje,tween:oO,keyframes:oO,spring:Pde};function itt(s){typeof s.type=="string"&&(s.type=IDt[s.type])}class N4e{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,r){return this.finished.then(t,r)}}const LDt=s=>s/100;class Dde extends N4e{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 n,a;const{motionValue:r}=this.options;r&&r.updatedAt!==af.now()&&this.tick(af.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(a=(n=this.options).onStop)==null||a.call(n))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;itt(t);const{type:r=oO,repeat:n=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=r||oO;c!==oO&&typeof o[0]!="number"&&(this.mixKeyframes=nB(LDt,rtt(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=j4e(d));const{calculatedDuration:h}=d;this.calculatedDuration=h,this.resolvedDuration=h+a,this.totalDuration=this.resolvedDuration*(n+1)-a,this.generator=d}updateTime(t){const r=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(t,r=!1){const{generator:n,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return n.next(0);const{delay:d=0,keyframes:h,repeat:m,repeatType:x,repeatDelay:y,type:v,onUpdate:w,finalKeyframe:b}=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)),r?this.currentTime=t:this.updateTime(t);const N=this.currentTime-d*(this.playbackSpeed>=0?1:-1),S=this.playbackSpeed>=0?N<0:N>a;this.currentTime=Math.max(N,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let T=this.currentTime,A=n;if(m){const $=Math.min(this.currentTime,a)/o;let F=Math.floor($),z=$%1;!z&&$>=1&&(z=1),z===1&&F--,F=Math.min(F,m+1),!!(F%2)&&(x==="reverse"?(z=1-z,y&&(z-=y/o)):x==="mirror"&&(A=l)),T=jv(0,1,z)*o}let I;S?(this.delayState.value=h[0],I=this.delayState):I=A.next(T),i&&!S&&(I.value=i(I.value));let{done:D}=I;!S&&c!==null&&(D=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const R=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return R&&v!==pje&&(I.value=kfe(h,this.options,b,this.speed)),w&&w(I.value),R&&this.finish(),I}then(t,r){return this.finished.then(t,r)}get duration(){return tg(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+tg(t)}get time(){return tg(this.currentTime)}set time(t){t=tp(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 r=this.generator.next(t).value;return att(n=>this.generator.next(n).value,t,r)}get speed(){return this.playbackSpeed}set speed(t){const r=this.playbackSpeed!==t;r&&this.driver&&this.updateTime(af.now()),this.playbackSpeed=t,r&&this.driver&&(this.time=tg(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=xDt,startTime:r}=this.options;this.driver||(this.driver=t(l=>this.tick(l))),(i=(a=this.options).onPlay)==null||i.call(a);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=r??n),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(af.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,r;this.notifyFinished(),this.teardown(),this.state="finished",(r=(t=this.options).onComplete)==null||r.call(t)}cancel(){var t,r;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(r=(t=this.options).onCancel)==null||r.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 r;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(r=this.driver)==null||r.stop(),t.observe(this)}}function PDt(s){for(let t=1;ts*180/Math.PI,xje=s=>{const t=r4(Math.atan2(s[1],s[0]));return gje(t)},DDt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:xje,rotateZ:xje,skewX:s=>r4(Math.atan(s[1])),skewY:s=>r4(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},gje=s=>(s=s%360,s<0&&(s+=360),s),ZRe=xje,XRe=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),QRe=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),RDt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:XRe,scaleY:QRe,scale:s=>(XRe(s)+QRe(s))/2,rotateX:s=>gje(r4(Math.atan2(s[6],s[5]))),rotateY:s=>gje(r4(Math.atan2(-s[2],s[0]))),rotateZ:ZRe,rotate:ZRe,skewX:s=>r4(Math.atan(s[4])),skewY:s=>r4(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function yje(s){return s.includes("scale")?1:0}function vje(s,t){if(!s||s==="none")return yje(t);const r=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,a;if(r)n=RDt,a=r;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=DDt,a=o}if(!a)return yje(t);const i=n[t],l=a[1].split(",").map(FDt);return typeof i=="function"?i(l):l[i]}const ODt=(s,t)=>{const{transform:r="none"}=getComputedStyle(s);return vje(r,t)};function FDt(s){return parseFloat(s.trim())}const VI=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],HI=new Set(VI),JRe=s=>s===qI||s===wa,BDt=new Set(["x","y","z"]),zDt=VI.filter(s=>!BDt.has(s));function $Dt(s){const t=[];return zDt.forEach(r=>{const n=s.getValue(r);n!==void 0&&(t.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),t}const Dw={width:({x:s},{paddingLeft:t="0",paddingRight:r="0",boxSizing:n})=>{const a=s.max-s.min;return n==="border-box"?a:a-parseFloat(t)-parseFloat(r)},height:({y:s},{paddingTop:t="0",paddingBottom:r="0",boxSizing:n})=>{const a=s.max-s.min;return n==="border-box"?a:a-parseFloat(t)-parseFloat(r)},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})=>vje(t,"x"),y:(s,{transform:t})=>vje(t,"y")};Dw.translateX=Dw.x;Dw.translateY=Dw.y;const a3=new Set;let bje=!1,_je=!1,wje=!1;function ott(){if(_je){const s=Array.from(a3).filter(n=>n.needsMeasurement),t=new Set(s.map(n=>n.element)),r=new Map;t.forEach(n=>{const a=$Dt(n);a.length&&(r.set(n,a),n.render())}),s.forEach(n=>n.measureInitialState()),t.forEach(n=>{n.render();const a=r.get(n);a&&a.forEach(([i,l])=>{var o;(o=n.getValue(i))==null||o.set(l)})}),s.forEach(n=>n.measureEndState()),s.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}_je=!1,bje=!1,a3.forEach(s=>s.complete(wje)),a3.clear()}function ltt(){a3.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(_je=!0)})}function UDt(){wje=!0,ltt(),ott(),wje=!1}class k4e{constructor(t,r,n,a,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=r,this.name=n,this.motionValue=a,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(a3.add(this),bje||(bje=!0,Zl.read(ltt),Zl.resolveKeyframes(ott))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:r,element:n,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(n&&r){const o=n.readValue(r,l);o!=null&&(t[0]=o)}t[0]===void 0&&(t[0]=l),a&&i===void 0&&a.set(t[0])}PDt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),a3.delete(this)}cancel(){this.state==="scheduled"&&(a3.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const qDt=s=>s.startsWith("--");function ctt(s,t,r){qDt(t)?s.style.setProperty(t,r):s.style[t]=r}const VDt={};function dtt(s,t){const r=Oet(s);return()=>VDt[t]??r()}const HDt=dtt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),utt=dtt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),LD=([s,t,r,n])=>`cubic-bezier(${s}, ${t}, ${r}, ${n})`,eOe={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:LD([0,.65,.55,1]),circOut:LD([.55,0,1,.45]),backIn:LD([.31,.01,.66,-.59]),backOut:LD([.33,1.53,.69,.99])};function htt(s,t){if(s)return typeof s=="function"?utt()?ntt(s,t):"ease-out":Ket(s)?LD(s):Array.isArray(s)?s.map(r=>htt(r,t)||eOe.easeOut):eOe[s]}function GDt(s,t,r,{delay:n=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const h={[t]:r};c&&(h.offset=c);const m=htt(o,a);Array.isArray(m)&&(h.easing=m);const x={delay:n,duration:a,easing:Array.isArray(m)?"linear":m,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(x.pseudoElement=d),s.animate(h,x)}function mtt(s){return typeof s=="function"&&"applyToOptions"in s}function WDt({type:s,...t}){return mtt(s)&&utt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class ftt extends N4e{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:r,name:n,keyframes:a,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=t;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=t,IM(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=WDt(t);this.animation=GDt(r,n,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const h=kfe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(h),ctt(r,n,h),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,r;(r=(t=this.animation).finish)==null||r.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 r,n,a;const t=(r=this.options)==null?void 0:r.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(n=this.animation).commitStyles)==null||a.call(n))}get duration(){var r,n;const t=((n=(r=this.animation.effect)==null?void 0:r.getComputedTiming)==null?void 0:n.call(r).duration)||0;return tg(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+tg(t)}get time(){return tg(Number(this.animation.currentTime)||0)}set time(t){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=tp(t),r&&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:r,rangeEnd:n,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&HDt()?(this.animation.timeline=t,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),cg):a(this)}}const ptt={anticipate:Vet,backInOut:qet,circInOut:Get};function KDt(s){return s in ptt}function YDt(s){typeof s.ease=="string"&&KDt(s.ease)&&(s.ease=ptt[s.ease])}const Nve=10;class ZDt extends ftt{constructor(t){YDt(t),itt(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:r,onUpdate:n,onComplete:a,element:i,...l}=this.options;if(!r)return;if(t!==void 0){r.set(t);return}const o=new Dde({...l,autoplay:!1}),c=Math.max(Nve,af.now()-this.startTime),d=jv(0,Nve,c-Nve),h=o.sample(c).value,{name:m}=this.options;i&&m&&ctt(i,m,h),r.setWithVelocity(o.sample(Math.max(0,c-d)).value,h,d),o.stop()}}const tOe=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(My.test(s)||s==="0")&&!s.startsWith("url("));function XDt(s){const t=s[0];if(s.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function rRt(s){var m;const{motionValue:t,name:r,repeatDelay:n,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((m=t==null?void 0:t.owner)==null?void 0:m.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:h}=t.owner.getProps();return sRt()&&r&&(xtt.has(r)||tRt.has(r)&&eRt(o))&&(r!=="transform"||!h)&&!d&&!n&&a!=="mirror"&&i!==0&&l!=="inertia"}const nRt=40;class aRt extends N4e{constructor({autoplay:t=!0,delay:r=0,type:n="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:h,...m}){var v;super(),this.stop=()=>{var w,b;this._animation&&(this._animation.stop(),(w=this.stopTimeline)==null||w.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=af.now();const x={autoplay:t,delay:r,type:n,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:h,...m},y=(h==null?void 0:h.KeyframeResolver)||k4e;this.keyframeResolver=new y(o,(w,b,N)=>this.onKeyframesResolved(w,b,x,!N),c,d,h),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(t,r,n,a){var N,S;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:h}=n;this.resolvedAt=af.now();let m=!0;QDt(t,i,l,o)||(m=!1,(Lj.instantAnimations||!c)&&(h==null||h(kfe(t,n,r))),t[0]=t[t.length-1],jje(n),n.repeat=0);const y={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>nRt?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:t},v=m&&!d&&rRt(y),w=(S=(N=y.motionValue)==null?void 0:N.owner)==null?void 0:S.current;let b;if(v)try{b=new ZDt({...y,element:w})}catch{b=new Dde(y)}else b=new Dde(y);b.finished.then(()=>{this.notifyFinished()}).catch(cg),this.pendingTimeline&&(this.stopTimeline=b.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=b}get finished(){return this._animation?this.animation.finished:this._finished}then(t,r){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),UDt()),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 gtt(s,t,r,n=0,a=1){const i=Array.from(s).sort((d,h)=>d.sortNodePosition(h)).indexOf(t),l=s.size,o=(l-1)*n;return typeof r=="function"?r(i,l):a===1?i*n:o-i*n}const iRt=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function oRt(s){const t=iRt.exec(s);if(!t)return[,];const[,r,n,a]=t;return[`--${r??n}`,a]}const lRt=4;function ytt(s,t,r=1){IM(r<=lRt,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,a]=oRt(s);if(!n)return;const i=window.getComputedStyle(t).getPropertyValue(n);if(i){const l=i.trim();return Pet(l)?parseFloat(l):l}return v4e(a)?ytt(a,t,r+1):a}const cRt={type:"spring",stiffness:500,damping:25,restSpeed:10},dRt=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),uRt={type:"keyframes",duration:.8},hRt={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},mRt=(s,{keyframes:t})=>t.length>2?uRt:HI.has(s)?s.startsWith("scale")?dRt(t[1]):cRt:hRt;function vtt(s,t){if(s!=null&&s.inherit&&t){const{inherit:r,...n}=s;return{...t,...n}}return s}function S4e(s,t){const r=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return r!==s?vtt(r,s):r}const fRt=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function pRt(s){for(const t in s)if(!fRt.has(t))return!0;return!1}const C4e=(s,t,r,n={},a,i)=>l=>{const o=S4e(n,s)||{},c=o.delay||n.delay||0;let{elapsed:d=0}=n;d=d-tp(c);const h={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:x=>{t.set(x),o.onUpdate&&o.onUpdate(x)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};pRt(o)||Object.assign(h,mRt(s,h)),h.duration&&(h.duration=tp(h.duration)),h.repeatDelay&&(h.repeatDelay=tp(h.repeatDelay)),h.from!==void 0&&(h.keyframes[0]=h.from);let m=!1;if((h.type===!1||h.duration===0&&!h.repeatDelay)&&(jje(h),h.delay===0&&(m=!0)),(Lj.instantAnimations||Lj.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(m=!0,jje(h),h.delay=0),h.allowFlatten=!o.type&&!o.ease,m&&!i&&t.get()!==void 0){const x=kfe(h.keyframes,o);if(x!==void 0){Zl.update(()=>{h.onUpdate(x),h.onComplete()});return}}return o.isSync?new Dde(h):new aRt(h)};function sOe(s){const t=[{},{}];return s==null||s.values.forEach((r,n)=>{t[0][n]=r.get(),t[1][n]=r.getVelocity()}),t}function T4e(s,t,r,n){if(typeof t=="function"){const[a,i]=sOe(n);t=t(r!==void 0?r:s.custom,a,i)}if(typeof t=="string"&&(t=s.variants&&s.variants[t]),typeof t=="function"){const[a,i]=sOe(n);t=t(r!==void 0?r:s.custom,a,i)}return t}function i3(s,t,r){const n=s.getProps();return T4e(n,t,r!==void 0?r:n.custom,s)}const btt=new Set(["width","height","top","left","right","bottom",...VI]),rOe=30,xRt=s=>!isNaN(parseFloat(s));class gRt{constructor(t,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var i;const a=af.now();if(this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),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=r.owner}setCurrent(t){this.current=t,this.updatedAt=af.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=xRt(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,r){this.events[t]||(this.events[t]=new x4e);const n=this.events[t].add(r);return t==="change"?()=>{n(),Zl.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,r){this.passiveEffect=t,this.stopPassiveEffect=r}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,r,n){this.set(r),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-n}jump(t,r=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,r&&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=af.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>rOe)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,rOe);return Fet(parseFloat(this.current)-parseFloat(this.prevFrameValue),r)}start(t){return this.stop(),new Promise(r=>{this.hasAnimated=!0,this.animation=t(r),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,r;(t=this.dependents)==null||t.clear(),(r=this.events.destroy)==null||r.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function PM(s,t){return new gRt(s,t)}const Nje=s=>Array.isArray(s);function yRt(s,t,r){s.hasValue(t)?s.getValue(t).set(r):s.addValue(t,PM(r))}function vRt(s){return Nje(s)?s[s.length-1]||0:s}function bRt(s,t){const r=i3(s,t);let{transitionEnd:n={},transition:a={},...i}=r||{};i={...i,...n};for(const l in i){const o=vRt(i[l]);yRt(s,l,o)}}const Wh=s=>!!(s&&s.getVelocity);function _Rt(s){return!!(Wh(s)&&s.add)}function kje(s,t){const r=s.getValue("willChange");if(_Rt(r))return r.add(t);if(!r&&Lj.WillChange){const n=new Lj.WillChange("auto");s.addValue("willChange",n),n.add(t)}}function E4e(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const wRt="framerAppearId",_tt="data-"+E4e(wRt);function wtt(s){return s.props[_tt]}function jRt({protectedKeys:s,needsAnimating:t},r){const n=s.hasOwnProperty(r)&&t[r]!==!0;return t[r]=!1,n}function jtt(s,t,{delay:r=0,transitionOverride:n,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?vtt(i,c):c;const d=i==null?void 0:i.reduceMotion;n&&(i=n);const h=[],m=a&&s.animationState&&s.animationState.getState()[a];for(const x in o){const y=s.getValue(x,s.latestValues[x]??null),v=o[x];if(v===void 0||m&&jRt(m,x))continue;const w={delay:r,...S4e(i||{},x)},b=y.get();if(b!==void 0&&!y.isAnimating()&&!Array.isArray(v)&&v===b&&!w.velocity){Zl.update(()=>y.set(v));continue}let N=!1;if(window.MotionHandoffAnimation){const A=wtt(s);if(A){const I=window.MotionHandoffAnimation(A,x,Zl);I!==null&&(w.startTime=I,N=!0)}}kje(s,x);const S=d??s.shouldReduceMotion;y.start(C4e(x,y,v,S&&btt.has(x)?{type:!1}:w,s,N));const T=y.animation;T&&h.push(T)}if(l){const x=()=>Zl.update(()=>{l&&bRt(s,l)});h.length?Promise.all(h).then(x):x()}return h}function Sje(s,t,r={}){var c;const n=i3(s,t,r.type==="exit"?(c=s.presenceContext)==null?void 0:c.custom:void 0);let{transition:a=s.getDefaultTransition()||{}}=n||{};r.transitionOverride&&(a=r.transitionOverride);const i=n?()=>Promise.all(jtt(s,n,r)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:h=0,staggerChildren:m,staggerDirection:x}=a;return NRt(s,t,d,h,m,x,r)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,h]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>h())}else return Promise.all([i(),l(r.delay)])}function NRt(s,t,r=0,n=0,a=0,i=1,l){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",t),o.push(Sje(c,t,{...l,delay:r+(typeof n=="function"?0:n)+gtt(s.variantChildren,c,n,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function kRt(s,t,r={}){s.notify("AnimationStart",t);let n;if(Array.isArray(t)){const a=t.map(i=>Sje(s,i,r));n=Promise.all(a)}else if(typeof t=="string")n=Sje(s,t,r);else{const a=typeof t=="function"?i3(s,t,r.custom):t;n=Promise.all(jtt(s,a,r))}return n.then(()=>{s.notify("AnimationComplete",t)})}const SRt={test:s=>s==="auto",parse:s=>s},Ntt=s=>t=>t.test(s),ktt=[qI,wa,fv,Y_,X6t,Z6t,SRt],nOe=s=>ktt.find(Ntt(s));function CRt(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||Ret(s):!0}const TRt=new Set(["brightness","contrast","saturate","opacity"]);function ERt(s){const[t,r]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[n]=r.match(b4e)||[];if(!n)return s;const a=r.replace(n,"");let i=TRt.has(t)?1:0;return n!==r&&(i*=100),t+"("+i+a+")"}const ARt=/\b([a-z-]*)\(.*?\)/gu,Cje={...My,getAnimatableNone:s=>{const t=s.match(ARt);return t?t.map(ERt).join(" "):s}},Tje={...My,getAnimatableNone:s=>{const t=My.parse(s);return My.createTransformer(s)(t.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},aOe={...qI,transform:Math.round},MRt={rotate:Y_,rotateX:Y_,rotateY:Y_,rotateZ:Y_,scale:W9,scaleX:W9,scaleY:W9,scaleZ:W9,skew:Y_,skewX:Y_,skewY:Y_,distance:wa,translateX:wa,translateY:wa,translateZ:wa,x:wa,y:wa,z:wa,perspective:wa,transformPerspective:wa,opacity:y8,originX:HRe,originY:HRe,originZ:wa},A4e={borderWidth:wa,borderTopWidth:wa,borderRightWidth:wa,borderBottomWidth:wa,borderLeftWidth:wa,borderRadius:wa,borderTopLeftRadius:wa,borderTopRightRadius:wa,borderBottomRightRadius:wa,borderBottomLeftRadius:wa,width:wa,maxWidth:wa,height:wa,maxHeight:wa,top:wa,right:wa,bottom:wa,left:wa,inset:wa,insetBlock:wa,insetBlockStart:wa,insetBlockEnd:wa,insetInline:wa,insetInlineStart:wa,insetInlineEnd:wa,padding:wa,paddingTop:wa,paddingRight:wa,paddingBottom:wa,paddingLeft:wa,paddingBlock:wa,paddingBlockStart:wa,paddingBlockEnd:wa,paddingInline:wa,paddingInlineStart:wa,paddingInlineEnd:wa,margin:wa,marginTop:wa,marginRight:wa,marginBottom:wa,marginLeft:wa,marginBlock:wa,marginBlockStart:wa,marginBlockEnd:wa,marginInline:wa,marginInlineStart:wa,marginInlineEnd:wa,fontSize:wa,backgroundPositionX:wa,backgroundPositionY:wa,...MRt,zIndex:aOe,fillOpacity:y8,strokeOpacity:y8,numOctaves:aOe},IRt={...A4e,color:hu,backgroundColor:hu,outlineColor:hu,fill:hu,stroke:hu,borderColor:hu,borderTopColor:hu,borderRightColor:hu,borderBottomColor:hu,borderLeftColor:hu,filter:Cje,WebkitFilter:Cje,mask:Tje,WebkitMask:Tje},Stt=s=>IRt[s],LRt=new Set([Cje,Tje]);function Ctt(s,t){let r=Stt(s);return LRt.has(r)||(r=My),r.getAnimatableNone?r.getAnimatableNone(t):void 0}const PRt=new Set(["auto","none","0"]);function DRt(s,t,r){let n=0,a;for(;n{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function M4e(s,t,r){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(n=>n!=null)}const Ttt=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function oce(s){return Det(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:I4e,cancel:IUs}=Yet(queueMicrotask,!1),ry={x:!1,y:!1};function Ett(){return ry.x||ry.y}function ORt(s){return s==="x"||s==="y"?ry[s]?null:(ry[s]=!0,()=>{ry[s]=!1}):ry.x||ry.y?null:(ry.x=ry.y=!0,()=>{ry.x=ry.y=!1})}function Att(s,t){const r=M4e(s),n=new AbortController,a={passive:!0,...t,signal:n.signal};return[r,a,()=>n.abort()]}function FRt(s){return!(s.pointerType==="touch"||Ett())}function BRt(s,t,r={}){const[n,a,i]=Att(s,r);return n.forEach(l=>{let o=!1,c=!1,d;const h=()=>{l.removeEventListener("pointerleave",v)},m=b=>{d&&(d(b),d=void 0),h()},x=b=>{o=!1,window.removeEventListener("pointerup",x),window.removeEventListener("pointercancel",x),c&&(c=!1,m(b))},y=()=>{o=!0,window.addEventListener("pointerup",x,a),window.addEventListener("pointercancel",x,a)},v=b=>{if(b.pointerType!=="touch"){if(o){c=!0;return}m(b)}},w=b=>{if(!FRt(b))return;c=!1;const N=t(l,b);typeof N=="function"&&(d=N,l.addEventListener("pointerleave",v,a))};l.addEventListener("pointerenter",w,a),l.addEventListener("pointerdown",y,a)}),i}const Mtt=(s,t)=>t?s===t?!0:Mtt(s,t.parentElement):!1,L4e=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,zRt=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function $Rt(s){return zRt.has(s.tagName)||s.isContentEditable===!0}const URt=new Set(["INPUT","SELECT","TEXTAREA"]);function qRt(s){return URt.has(s.tagName)||s.isContentEditable===!0}const lce=new WeakSet;function iOe(s){return t=>{t.key==="Enter"&&s(t)}}function kve(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const VRt=(s,t)=>{const r=s.currentTarget;if(!r)return;const n=iOe(()=>{if(lce.has(r))return;kve(r,"down");const a=iOe(()=>{kve(r,"up")}),i=()=>kve(r,"cancel");r.addEventListener("keyup",a,t),r.addEventListener("blur",i,t)});r.addEventListener("keydown",n,t),r.addEventListener("blur",()=>r.removeEventListener("keydown",n),t)};function oOe(s){return L4e(s)&&!Ett()}const lOe=new WeakSet;function HRt(s,t,r={}){const[n,a,i]=Att(s,r),l=o=>{const c=o.currentTarget;if(!oOe(o)||lOe.has(o))return;lce.add(c),r.stopPropagation&&lOe.add(o);const d=t(c,o),h=(y,v)=>{window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",x),lce.has(c)&&lce.delete(c),oOe(y)&&typeof d=="function"&&d(y,{success:v})},m=y=>{h(y,c===window||c===document||r.useGlobalTarget||Mtt(c,y.target))},x=y=>{h(y,!1)};window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",x,a)};return n.forEach(o=>{(r.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),oce(o)&&(o.addEventListener("focus",d=>VRt(d,a)),!$Rt(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function P4e(s){return Det(s)&&"ownerSVGElement"in s}const cce=new WeakMap;let Z_;const Itt=(s,t,r)=>(n,a)=>a&&a[0]?a[0][s+"Size"]:P4e(n)&&"getBBox"in n?n.getBBox()[t]:n[r],GRt=Itt("inline","width","offsetWidth"),WRt=Itt("block","height","offsetHeight");function KRt({target:s,borderBoxSize:t}){var r;(r=cce.get(s))==null||r.forEach(n=>{n(s,{get width(){return GRt(s,t)},get height(){return WRt(s,t)}})})}function YRt(s){s.forEach(KRt)}function ZRt(){typeof ResizeObserver>"u"||(Z_=new ResizeObserver(YRt))}function XRt(s,t){Z_||ZRt();const r=M4e(s);return r.forEach(n=>{let a=cce.get(n);a||(a=new Set,cce.set(n,a)),a.add(t),Z_==null||Z_.observe(n)}),()=>{r.forEach(n=>{const a=cce.get(n);a==null||a.delete(t),a!=null&&a.size||Z_==null||Z_.unobserve(n)})}}const dce=new Set;let qE;function QRt(){qE=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};dce.forEach(t=>t(s))},window.addEventListener("resize",qE)}function JRt(s){return dce.add(s),qE||QRt(),()=>{dce.delete(s),!dce.size&&typeof qE=="function"&&(window.removeEventListener("resize",qE),qE=void 0)}}function cOe(s,t){return typeof s=="function"?JRt(s):XRt(s,t)}function eOt(s){return P4e(s)&&s.tagName==="svg"}const tOt=[...ktt,hu,My],sOt=s=>tOt.find(Ntt(s)),dOe=()=>({translate:0,scale:1,origin:0,originPoint:0}),VE=()=>({x:dOe(),y:dOe()}),uOe=()=>({min:0,max:0}),Lu=()=>({x:uOe(),y:uOe()}),rOt=new WeakMap;function Sfe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function v8(s){return typeof s=="string"||Array.isArray(s)}const D4e=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],R4e=["initial",...D4e];function Cfe(s){return Sfe(s.animate)||R4e.some(t=>v8(s[t]))}function Ltt(s){return!!(Cfe(s)||s.variants)}function nOt(s,t,r){for(const n in t){const a=t[n],i=r[n];if(Wh(a))s.addValue(n,a);else if(Wh(i))s.addValue(n,PM(a,{owner:s}));else if(i!==a)if(s.hasValue(n)){const l=s.getValue(n);l.liveStyle===!0?l.jump(a):l.hasAnimated||l.set(a)}else{const l=s.getStaticValue(n);s.addValue(n,PM(l!==void 0?l:a,{owner:s}))}}for(const n in r)t[n]===void 0&&s.removeValue(n);return t}const Eje={current:null},Ptt={current:!1},aOt=typeof window<"u";function iOt(){if(Ptt.current=!0,!!aOt)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>Eje.current=s.matches;s.addEventListener("change",t),t()}else Eje.current=!1}const hOe=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Rde={};function Dtt(s){Rde=s}function oOt(){return Rde}class lOt{scrapeMotionValuesFromProps(t,r,n){return{}}constructor({parent:t,props:r,presenceContext:n,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=k4e,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 y=af.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Ptt.current||iOt(),this.shouldReduceMotion=Eje.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var t;this.projection&&this.projection.unmount(),Pj(this.notifyUpdate),Pj(this.render),this.valueSubscriptions.forEach(r=>r()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const r in this.events)this.events[r].clear();for(const r in this.features){const n=this.features[r];n&&(n.unmount(),n.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,r){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),r.accelerate&&xtt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:h}=r.accelerate,m=new ftt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:tp(h)}),x=l(m);this.valueSubscriptions.set(t,()=>{x(),m.cancel()});return}const n=HI.has(t);n&&this.onBindTransform&&this.onBindTransform();const a=r.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Zl.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,r)),this.valueSubscriptions.set(t,()=>{a(),i&&i(),r.owner&&r.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 Rde){const r=Rde[t];if(!r)continue;const{isEnabled:n,Feature:a}=r;if(!this.features[t]&&a&&n(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):Lu()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,r){this.latestValues[t]=r}update(t,r){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=r;for(let n=0;nr.variantChildren.delete(t)}addValue(t,r){const n=this.values.get(t);r!==n&&(n&&this.removeValue(t),this.bindToMotionValue(t,r),this.values.set(t,r),this.latestValues[t]=r.get())}removeValue(t){this.values.delete(t);const r=this.valueSubscriptions.get(t);r&&(r(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,r){if(this.props.values&&this.props.values[t])return this.props.values[t];let n=this.values.get(t);return n===void 0&&r!==void 0&&(n=PM(r===null?void 0:r,{owner:this}),this.addValue(t,n)),n}readValue(t,r){let n=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return n!=null&&(typeof n=="string"&&(Pet(n)||Ret(n))?n=parseFloat(n):!sOt(n)&&My.test(r)&&(n=Ctt(t,r)),this.setBaseTarget(t,Wh(n)?n.get():n)),Wh(n)?n.get():n}setBaseTarget(t,r){this.baseTarget[t]=r}getBaseTarget(t){var i;const{initial:r}=this.props;let n;if(typeof r=="string"||typeof r=="object"){const l=T4e(this.props,r,(i=this.presenceContext)==null?void 0:i.custom);l&&(n=l[t])}if(r&&n!==void 0)return n;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!Wh(a)?a:this.initialValues[t]!==void 0&&n===void 0?void 0:this.baseTarget[t]}on(t,r){return this.events[t]||(this.events[t]=new x4e),this.events[t].add(r)}notify(t,...r){this.events[t]&&this.events[t].notify(...r)}scheduleRenderMicrotask(){I4e.render(this.render)}}class Rtt extends lOt{constructor(){super(...arguments),this.KeyframeResolver=RRt}sortInstanceNodePosition(t,r){return t.compareDocumentPosition(r)&2?1:-1}getBaseTargetFromProps(t,r){const n=t.style;return n?n[r]:void 0}removeValueFromRenderState(t,{vars:r,style:n}){delete r[t],delete n[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Wh(t)&&(this.childSubscription=t.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class s2{constructor(t){this.isMounted=!1,this.node=t}update(){}}function Ott({top:s,left:t,right:r,bottom:n}){return{x:{min:t,max:r},y:{min:s,max:n}}}function cOt({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function dOt(s,t){if(!t)return s;const r=t({x:s.left,y:s.top}),n=t({x:s.right,y:s.bottom});return{top:r.y,left:r.x,bottom:n.y,right:n.x}}function Sve(s){return s===void 0||s===1}function Aje({scale:s,scaleX:t,scaleY:r}){return!Sve(s)||!Sve(t)||!Sve(r)}function $C(s){return Aje(s)||Ftt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function Ftt(s){return mOe(s.x)||mOe(s.y)}function mOe(s){return s&&s!=="0%"}function Ode(s,t,r){const n=s-r,a=t*n;return r+a}function fOe(s,t,r,n,a){return a!==void 0&&(s=Ode(s,a,n)),Ode(s,r,n)+t}function Mje(s,t=0,r=1,n,a){s.min=fOe(s.min,t,r,n,a),s.max=fOe(s.max,t,r,n,a)}function Btt(s,{x:t,y:r}){Mje(s.x,t.translate,t.scale,t.originPoint),Mje(s.y,r.translate,r.scale,r.originPoint)}const pOe=.999999999999,xOe=1.0000000000001;function uOt(s,t,r,n=!1){var o;const a=r.length;if(!a)return;t.x=t.y=1;let i,l;for(let c=0;cpOe&&(t.x=1),t.ypOe&&(t.y=1)}function O0(s,t){s.min+=t,s.max+=t}function gOe(s,t,r,n,a=.5){const i=Cc(s.min,s.max,a);Mje(s,t,r,i,n)}function yOe(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function uce(s,t,r){const n=r??s;gOe(s.x,yOe(t.x,n.x),t.scaleX,t.scale,t.originX),gOe(s.y,yOe(t.y,n.y),t.scaleY,t.scale,t.originY)}function ztt(s,t){return Ott(dOt(s.getBoundingClientRect(),t))}function hOt(s,t,r){const n=ztt(s,r),{scroll:a}=t;return a&&(O0(n.x,a.offset.x),O0(n.y,a.offset.y)),n}const mOt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},fOt=VI.length;function pOt(s,t,r){let n="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(wa.test(s))s=parseFloat(s);else return s;const r=vOe(s,t.target.x),n=vOe(s,t.target.y);return`${r}% ${n}%`}},xOt={correct:(s,{treeScale:t,projectionDelta:r})=>{const n=s,a=My.parse(s);if(a.length>5)return n;const i=My.createTransformer(s),l=typeof a[0]!="number"?1:0,o=r.x.scale*t.x,c=r.y.scale*t.y;a[0+l]/=o,a[1+l]/=c;const d=Cc(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},Ije={borderRadius:{...X6,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:X6,borderTopRightRadius:X6,borderBottomLeftRadius:X6,borderBottomRightRadius:X6,boxShadow:xOt};function Utt(s,{layout:t,layoutId:r}){return HI.has(s)||s.startsWith("origin")||(t||r!==void 0)&&(!!Ije[s]||s==="opacity")}function F4e(s,t,r){var l;const n=s.style,a=t==null?void 0:t.style,i={};if(!n)return i;for(const o in n)(Wh(n[o])||a&&Wh(a[o])||Utt(o,s)||((l=r==null?void 0:r.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=n[o]);return i}function gOt(s){return window.getComputedStyle(s)}class yOt extends Rtt{constructor(){super(...arguments),this.type="html",this.renderInstance=$tt}readValueFromInstance(t,r){var n;if(HI.has(r))return(n=this.projection)!=null&&n.isProjecting?yje(r):ODt(t,r);{const a=gOt(t),i=(Xet(r)?a.getPropertyValue(r):a[r])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:r}){return ztt(t,r)}build(t,r,n){O4e(t,r,n.transformTemplate)}scrapeMotionValuesFromProps(t,r,n){return F4e(t,r,n)}}const vOt={offset:"stroke-dashoffset",array:"stroke-dasharray"},bOt={offset:"strokeDashoffset",array:"strokeDasharray"};function _Ot(s,t,r=1,n=0,a=!0){s.pathLength=1;const i=a?vOt:bOt;s[i.offset]=`${-n}`,s[i.array]=`${t} ${r}`}const wOt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function qtt(s,{attrX:t,attrY:r,attrScale:n,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,h){if(O4e(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:m,style:x}=s;m.transform&&(x.transform=m.transform,delete m.transform),(x.transform||m.transformOrigin)&&(x.transformOrigin=m.transformOrigin??"50% 50%",delete m.transformOrigin),x.transform&&(x.transformBox=(h==null?void 0:h.transformBox)??"fill-box",delete m.transformBox);for(const y of wOt)m[y]!==void 0&&(x[y]=m[y],delete m[y]);t!==void 0&&(m.x=t),r!==void 0&&(m.y=r),n!==void 0&&(m.scale=n),a!==void 0&&_Ot(m,a,i,l,!1)}const Vtt=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"]),Htt=s=>typeof s=="string"&&s.toLowerCase()==="svg";function jOt(s,t,r,n){$tt(s,t,void 0,n);for(const a in t.attrs)s.setAttribute(Vtt.has(a)?a:E4e(a),t.attrs[a])}function Gtt(s,t,r){const n=F4e(s,t,r);for(const a in s)if(Wh(s[a])||Wh(t[a])){const i=VI.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;n[i]=s[a]}return n}class NOt extends Rtt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Lu}getBaseTargetFromProps(t,r){return t[r]}readValueFromInstance(t,r){if(HI.has(r)){const n=Stt(r);return n&&n.default||0}return r=Vtt.has(r)?r:E4e(r),t.getAttribute(r)}scrapeMotionValuesFromProps(t,r,n){return Gtt(t,r,n)}build(t,r,n){qtt(t,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(t,r,n,a){jOt(t,r,n,a)}mount(t){this.isSVGTag=Htt(t.tagName),super.mount(t)}}const kOt=R4e.length;function Wtt(s){if(!s)return;if(!s.isControllingVariants){const r=s.parent?Wtt(s.parent)||{}:{};return s.props.initial!==void 0&&(r.initial=s.props.initial),r}const t={};for(let r=0;rPromise.all(t.map(({animation:r,options:n})=>kRt(s,r,n)))}function EOt(s){let t=TOt(s),r=bOe(),n=!0,a=!1;const i=d=>(h,m)=>{var y;const x=i3(s,m,d==="exit"?(y=s.presenceContext)==null?void 0:y.custom:void 0);if(x){const{transition:v,transitionEnd:w,...b}=x;h={...h,...b,...w}}return h};function l(d){t=d(s)}function o(d){const{props:h}=s,m=Wtt(s.parent)||{},x=[],y=new Set;let v={},w=1/0;for(let N=0;Nw&&I,z=!1;const Q=Array.isArray(A)?A:[A];let K=Q.reduce(i(S),{});D===!1&&(K={});const{prevResolvedValues:X={}}=T,Z={...X,...K},re=ne=>{F=!0,y.has(ne)&&(z=!0,y.delete(ne)),T.needsAnimating[ne]=!0;const ie=s.getValue(ne);ie&&(ie.liveStyle=!1)};for(const ne in Z){const ie=K[ne],ye=X[ne];if(v.hasOwnProperty(ne))continue;let ce=!1;Nje(ie)&&Nje(ye)?ce=!Ktt(ie,ye):ce=ie!==ye,ce?ie!=null?re(ne):y.add(ne):ie!==void 0&&y.has(ne)?re(ne):T.protectedKeys[ne]=!0}T.prevProp=A,T.prevResolvedValues=K,T.isActive&&(v={...v,...K}),(n||a)&&s.blockInitialAnimation&&(F=!1);const le=R&&$;F&&(!le||z)&&x.push(...Q.map(ne=>{const ie={type:S};if(typeof ne=="string"&&(n||a)&&!le&&s.manuallyAnimateOnMount&&s.parent){const{parent:ye}=s,ce=i3(ye,ne);if(ye.enteringChildren&&ce){const{delayChildren:ve}=ce.transition||{};ie.delay=gtt(ye.enteringChildren,s,ve)}}return{animation:ne,options:ie}}))}if(y.size){const N={};if(typeof h.initial!="boolean"){const S=i3(s,Array.isArray(h.initial)?h.initial[0]:h.initial);S&&S.transition&&(N.transition=S.transition)}y.forEach(S=>{const T=s.getBaseTarget(S),A=s.getValue(S);A&&(A.liveStyle=!0),N[S]=T??null}),x.push({animation:N})}let b=!!x.length;return n&&(h.initial===!1||h.initial===h.animate)&&!s.manuallyAnimateOnMount&&(b=!1),n=!1,a=!1,b?t(x):Promise.resolve()}function c(d,h){var x;if(r[d].isActive===h)return Promise.resolve();(x=s.variantChildren)==null||x.forEach(y=>{var v;return(v=y.animationState)==null?void 0:v.setActive(d,h)}),r[d].isActive=h;const m=o(d);for(const y in r)r[y].protectedKeys={};return m}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>r,reset:()=>{r=bOe(),a=!0}}}function AOt(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!Ktt(t,s):!1}function _N(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function bOe(){return{animate:_N(!0),whileInView:_N(),whileHover:_N(),whileTap:_N(),whileDrag:_N(),whileFocus:_N(),exit:_N()}}function Lje(s,t){s.min=t.min,s.max=t.max}function Qg(s,t){Lje(s.x,t.x),Lje(s.y,t.y)}function _Oe(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const Ytt=1e-4,MOt=1-Ytt,IOt=1+Ytt,Ztt=.01,LOt=0-Ztt,POt=0+Ztt;function of(s){return s.max-s.min}function DOt(s,t,r){return Math.abs(s-t)<=r}function wOe(s,t,r,n=.5){s.origin=n,s.originPoint=Cc(t.min,t.max,s.origin),s.scale=of(r)/of(t),s.translate=Cc(r.min,r.max,s.origin)-s.originPoint,(s.scale>=MOt&&s.scale<=IOt||isNaN(s.scale))&&(s.scale=1),(s.translate>=LOt&&s.translate<=POt||isNaN(s.translate))&&(s.translate=0)}function lO(s,t,r,n){wOe(s.x,t.x,r.x,n?n.originX:void 0),wOe(s.y,t.y,r.y,n?n.originY:void 0)}function jOe(s,t,r,n=0){const a=n?Cc(r.min,r.max,n):r.min;s.min=a+t.min,s.max=s.min+of(t)}function ROt(s,t,r,n){jOe(s.x,t.x,r.x,n==null?void 0:n.x),jOe(s.y,t.y,r.y,n==null?void 0:n.y)}function NOe(s,t,r,n=0){const a=n?Cc(r.min,r.max,n):r.min;s.min=t.min-a,s.max=s.min+of(t)}function Fde(s,t,r,n){NOe(s.x,t.x,r.x,n==null?void 0:n.x),NOe(s.y,t.y,r.y,n==null?void 0:n.y)}function kOe(s,t,r,n,a){return s-=t,s=Ode(s,1/r,n),a!==void 0&&(s=Ode(s,1/a,n)),s}function OOt(s,t=0,r=1,n=.5,a,i=s,l=s){if(fv.test(t)&&(t=parseFloat(t),t=Cc(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Cc(i.min,i.max,n);s===i&&(o-=t),s.min=kOe(s.min,t,r,o,a),s.max=kOe(s.max,t,r,o,a)}function SOe(s,t,[r,n,a],i,l){OOt(s,t[r],t[n],t[a],t.scale,i,l)}const FOt=["x","scaleX","originX"],BOt=["y","scaleY","originY"];function COe(s,t,r,n){SOe(s.x,t,FOt,r?r.x:void 0,n?n.x:void 0),SOe(s.y,t,BOt,r?r.y:void 0,n?n.y:void 0)}function TOe(s){return s.translate===0&&s.scale===1}function Xtt(s){return TOe(s.x)&&TOe(s.y)}function EOe(s,t){return s.min===t.min&&s.max===t.max}function zOt(s,t){return EOe(s.x,t.x)&&EOe(s.y,t.y)}function AOe(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function Qtt(s,t){return AOe(s.x,t.x)&&AOe(s.y,t.y)}function MOe(s){return of(s.x)/of(s.y)}function IOe(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function S0(s){return[s("x"),s("y")]}function $Ot(s,t,r){let n="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(r==null?void 0:r.z)||0;if((a||i||l)&&(n=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(n+=`scale(${1/t.x}, ${1/t.y}) `),r){const{transformPerspective:d,rotate:h,rotateX:m,rotateY:x,skewX:y,skewY:v}=r;d&&(n=`perspective(${d}px) ${n}`),h&&(n+=`rotate(${h}deg) `),m&&(n+=`rotateX(${m}deg) `),x&&(n+=`rotateY(${x}deg) `),y&&(n+=`skewX(${y}deg) `),v&&(n+=`skewY(${v}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(n+=`scale(${o}, ${c})`),n||"none"}const Jtt=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],UOt=Jtt.length,LOe=s=>typeof s=="string"?parseFloat(s):s,POe=s=>typeof s=="number"||wa.test(s);function qOt(s,t,r,n,a,i){a?(s.opacity=Cc(0,r.opacity??1,VOt(n)),s.opacityExit=Cc(t.opacity??1,0,HOt(n))):i&&(s.opacity=Cc(t.opacity??1,r.opacity??1,n));for(let l=0;lnt?1:r(g8(s,t,n))}function GOt(s,t,r){const n=Wh(s)?s:PM(s);return n.start(C4e("",n,t,r)),n.animation}function b8(s,t,r,n={passive:!0}){return s.addEventListener(t,r,n),()=>s.removeEventListener(t,r)}const WOt=(s,t)=>s.depth-t.depth;class KOt{constructor(){this.children=[],this.isDirty=!1}add(t){p4e(this.children,t),this.isDirty=!0}remove(t){Mde(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(WOt),this.isDirty=!1,this.children.forEach(t)}}function YOt(s,t){const r=af.now(),n=({timestamp:a})=>{const i=a-r;i>=t&&(Pj(n),s(i-t))};return Zl.setup(n,!0),()=>Pj(n)}function hce(s){return Wh(s)?s.get():s}class ZOt{constructor(){this.members=[]}add(t){p4e(this.members,t);for(let r=this.members.length-1;r>=0;r--){const n=this.members[r];if(n===t||n===this.lead||n===this.prevLead)continue;const a=n.instance;(!a||a.isConnected===!1)&&!n.snapshot&&(Mde(this.members,n),n.unmount())}t.scheduleRender()}remove(t){if(Mde(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const r=this.members[this.members.length-1];r&&this.promote(r)}}relegate(t){var r;for(let n=this.members.indexOf(t)-1;n>=0;n--){const a=this.members[n];if(a.isPresent!==!1&&((r=a.instance)==null?void 0:r.isConnected)!==!1)return this.promote(a),!0}return!1}promote(t,r){var a;const n=this.lead;if(t!==n&&(this.prevLead=n,this.lead=t,t.show(),n)){n.updateSnapshot(),t.scheduleRender();const{layoutDependency:i}=n.options,{layoutDependency:l}=t.options;(i===void 0||i!==l)&&(t.resumeFrom=n,r&&(n.preserveOpacity=!0),n.snapshot&&(t.snapshot=n.snapshot,t.snapshot.latestValues=n.animationValues||n.latestValues),(a=t.root)!=null&&a.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(t=>{var r,n,a,i,l;(n=(r=t.options).onExitComplete)==null||n.call(r),(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 mce={hasAnimatedSinceResize:!0,hasEverUpdated:!1},Cve=["","X","Y","Z"],XOt=1e3;let QOt=0;function Tve(s,t,r,n){const{latestValues:a}=t;a[s]&&(r[s]=a[s],t.setStaticValue(s,0),n&&(n[s]=0))}function tst(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const r=wtt(t);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(r,"transform",Zl,!(a||i))}const{parent:n}=s;n&&!n.hasCheckedOptimisedAppear&&tst(n)}function sst({attachResizeListener:s,defaultParent:t,measureScroll:r,checkIsScrollRoot:n,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=QOt++,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(t8t),this.nodes.forEach(o8t),this.nodes.forEach(l8t),this.nodes.forEach(s8t)},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;Zl.read(()=>{m=window.innerWidth}),s(l,()=>{const y=window.innerWidth;y!==m&&(m=y,this.root.updateBlockedByResize=!0,h&&h(),h=YOt(x,250),mce.hasAnimatedSinceResize&&(mce.hasAnimatedSinceResize=!1,this.nodes.forEach(FOe)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:h,hasLayoutChanged:m,hasRelativeLayoutChanged:x,layout:y})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||d.getDefaultTransition()||m8t,{onLayoutAnimationStart:w,onLayoutAnimationComplete:b}=d.getProps(),N=!this.targetLayout||!Qtt(this.targetLayout,y),S=!m&&x;if(this.options.layoutRoot||this.resumeFrom||S||m&&(N||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const T={...S4e(v,"layout"),onPlay:w,onComplete:b};(d.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(h,S)}else m||FOe(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=y})}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(),Pj(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(c8t),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&&tst(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let h=0;h{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!of(this.snapshot.measuredBox.x)&&!of(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 I=A/1e3;BOe(m.x,l.x,I),BOe(m.y,l.y,I),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Fde(x,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),u8t(this.relativeTarget,this.relativeTargetOrigin,x,I),T&&zOt(this.relativeTarget,T)&&(this.isProjectionDirty=!1),T||(T=Lu()),Qg(T,this.relativeTarget)),w&&(this.animationValues=h,qOt(h,d,this.latestValues,I,S,N)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=I},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&&(Pj(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Zl.update(()=>{mce.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=PM(0)),this.motionValue.jump(0,!1),this.currentAnimation=GOt(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:h=>{this.mixTargetDelta(h),l.onUpdate&&l.onUpdate(h)},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(XOt),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:h}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&rst(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Lu();const m=of(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+m;const x=of(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+x}Qg(o,c),uce(o,h),lO(this.projectionDeltaWithTransform,this.layoutCorrected,o,h)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new ZOt),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&&Tve("z",l,d,this.animationValues);for(let h=0;h{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(ROe),this.root.sharedNodes.clear()}}}function JOt(s){s.updateLayout()}function e8t(s){var r;const t=((r=s.resumeFrom)==null?void 0:r.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")S0(m=>{const x=l?t.measuredBox[m]:t.layoutBox[m],y=of(x);x.min=n[m].min,x.max=x.min+y});else if(i==="x"||i==="y"){const m=i==="x"?"y":"x";Lje(l?t.measuredBox[m]:t.layoutBox[m],n[m])}else rst(i,t.layoutBox,n)&&S0(m=>{const x=l?t.measuredBox[m]:t.layoutBox[m],y=of(n[m]);x.max=x.min+y,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[m].max=s.relativeTarget[m].min+y)});const o=VE();lO(o,n,t.layoutBox);const c=VE();l?lO(c,s.applyTransform(a,!0),t.measuredBox):lO(c,n,t.layoutBox);const d=!Xtt(o);let h=!1;if(!s.resumeFrom){const m=s.getClosestProjectingParent();if(m&&!m.resumeFrom){const{snapshot:x,layout:y}=m;if(x&&y){const v=s.options.layoutAnchor||void 0,w=Lu();Fde(w,t.layoutBox,x.layoutBox,v);const b=Lu();Fde(b,n,y.layoutBox,v),Qtt(w,b)||(h=!0),m.options.layoutRoot&&(s.relativeTarget=b,s.relativeTargetOrigin=w,s.relativeParent=m)}}}s.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:h})}else if(s.isLead()){const{onExitComplete:n}=s.options;n&&n()}s.options.transition=void 0}function t8t(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 s8t(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function r8t(s){s.clearSnapshot()}function ROe(s){s.clearMeasurements()}function n8t(s){s.isLayoutDirty=!0,s.updateLayout()}function OOe(s){s.isLayoutDirty=!1}function a8t(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function i8t(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function FOe(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function o8t(s){s.resolveTargetDelta()}function l8t(s){s.calcProjection()}function c8t(s){s.resetSkewAndRotation()}function d8t(s){s.removeLeadSnapshot()}function BOe(s,t,r){s.translate=Cc(t.translate,0,r),s.scale=Cc(t.scale,1,r),s.origin=t.origin,s.originPoint=t.originPoint}function zOe(s,t,r,n){s.min=Cc(t.min,r.min,n),s.max=Cc(t.max,r.max,n)}function u8t(s,t,r,n){zOe(s.x,t.x,r.x,n),zOe(s.y,t.y,r.y,n)}function h8t(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const m8t={duration:.45,ease:[.4,0,.1,1]},$Oe=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),UOe=$Oe("applewebkit/")&&!$Oe("chrome/")?Math.round:cg;function qOe(s){s.min=UOe(s.min),s.max=UOe(s.max)}function f8t(s){qOe(s.x),qOe(s.y)}function rst(s,t,r){return s==="position"||s==="preserve-aspect"&&!DOt(MOe(t),MOe(r),.2)}function p8t(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const x8t=sst({attachResizeListener:(s,t)=>b8(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}),Eve={current:void 0},nst=sst({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!Eve.current){const s=new x8t({});s.mount(window),s.setOptions({layoutScroll:!0}),Eve.current=s}return Eve.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),B4e=k.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function VOe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function g8t(...s){return t=>{let r=!1;const n=s.map(a=>{const i=VOe(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a{const{width:y,height:v,top:w,left:b,right:N,bottom:S}=c.current;if(t||i===!1||!o.current||!y||!v)return;const T=r==="left"?`left: ${b}`:`right: ${N}`,A=n==="bottom"?`bottom: ${S}`:`top: ${w}`;o.current.dataset.motionPopId=l;const I=document.createElement("style");d&&(I.nonce=d);const D=a??document.head;return D.appendChild(I),I.sheet&&I.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${y}px !important; height: ${v}px !important; ${T}px !important; ${A}px !important; } `),()=>{var R;(R=o.current)==null||R.removeAttribute("data-motion-pop-id"),D.contains(I)&&D.removeChild(I)}},[t]),e.jsx(v8t,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:k.cloneElement(s,{ref:m})})}const _8t=({children:s,initial:t,isPresent:r,onExitComplete:n,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const h=f4e(w8t),m=k.useId();let x=!0,y=k.useMemo(()=>(x=!1,{id:m,initial:t,isPresent:r,custom:a,onExitComplete:v=>{h.set(v,!0);for(const w of h.values())if(!w)return;n&&n()},register:v=>(h.set(v,!1),()=>h.delete(v))}),[r,h,n]);return i&&x&&(y={...y}),k.useMemo(()=>{h.forEach((v,w)=>h.set(w,!1))},[r]),k.useEffect(()=>{!r&&!h.size&&n&&n()},[r]),s=e.jsx(b8t,{pop:l==="popLayout",isPresent:r,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(jfe.Provider,{value:y,children:s})};function w8t(){return new Map}function ast(s=!0){const t=k.useContext(jfe);if(t===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:a}=t,i=k.useId();k.useEffect(()=>{if(s)return a(i)},[s]);const l=k.useCallback(()=>s&&n&&n(i),[i,n,s]);return!r&&n?[!1,l]:[!0]}const K9=s=>s.key||"";function HOe(s){const t=[];return k.Children.forEach(s,r=>{k.isValidElement(r)&&t.push(r)}),t}const z4e=({children:s,custom:t,initial:r=!0,onExitComplete:n,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[h,m]=ast(l),x=k.useMemo(()=>HOe(s),[s]),y=l&&!h?[]:x.map(K9),v=k.useRef(!0),w=k.useRef(x),b=f4e(()=>new Map),N=k.useRef(new Set),[S,T]=k.useState(x),[A,I]=k.useState(x);Let(()=>{v.current=!1,w.current=x;for(let $=0;${const F=K9($),z=l&&!h?!1:x===A||y.includes(F),Q=()=>{if(N.current.has(F))return;if(b.has(F))N.current.add(F),b.set(F,!0);else return;let K=!0;b.forEach(X=>{X||(K=!1)}),K&&(R==null||R(),I(w.current),l&&(m==null||m()),n&&n())};return e.jsx(_8t,{isPresent:z,initial:!v.current||r?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:z?void 0:Q,anchorX:o,anchorY:c,children:$},F)})})},ist=k.createContext({strict:!1}),GOe={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 WOe=!1;function j8t(){if(WOe)return;const s={};for(const t in GOe)s[t]={isEnabled:r=>GOe[t].some(n=>!!r[n])};Dtt(s),WOe=!0}function ost(){return j8t(),oOt()}function N8t(s){const t=ost();for(const r in s)t[r]={...t[r],...s[r]};Dtt(t)}const k8t=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 Bde(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||k8t.has(s)}let lst=s=>!Bde(s);function S8t(s){typeof s=="function"&&(lst=t=>t.startsWith("on")?!Bde(t):s(t))}try{S8t(require("@emotion/is-prop-valid").default)}catch{}function C8t(s,t,r){const n={};for(const a in s)a==="values"&&typeof s.values=="object"||Wh(s[a])||(lst(a)||r===!0&&Bde(a)||!t&&!Bde(a)||s.draggable&&a.startsWith("onDrag"))&&(n[a]=s[a]);return n}const Tfe=k.createContext({});function T8t(s,t){if(Cfe(s)){const{initial:r,animate:n}=s;return{initial:r===!1||v8(r)?r:void 0,animate:v8(n)?n:void 0}}return s.inherit!==!1?t:{}}function E8t(s){const{initial:t,animate:r}=T8t(s,k.useContext(Tfe));return k.useMemo(()=>({initial:t,animate:r}),[KOe(t),KOe(r)])}function KOe(s){return Array.isArray(s)?s.join(" "):s}const $4e=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function cst(s,t,r){for(const n in t)!Wh(t[n])&&!Utt(n,r)&&(s[n]=t[n])}function A8t({transformTemplate:s},t){return k.useMemo(()=>{const r=$4e();return O4e(r,t,s),Object.assign({},r.vars,r.style)},[t])}function M8t(s,t){const r=s.style||{},n={};return cst(n,r,s),Object.assign(n,A8t(s,t)),n}function I8t(s,t){const r={},n=M8t(s,t);return s.drag&&s.dragListener!==!1&&(r.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(r.tabIndex=0),r.style=n,r}const dst=()=>({...$4e(),attrs:{}});function L8t(s,t,r,n){const a=k.useMemo(()=>{const i=dst();return qtt(i,t,Htt(n),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};cst(i,s.style,s),a.style={...i,...a.style}}return a}const P8t=["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 U4e(s){return typeof s!="string"||s.includes("-")?!1:!!(P8t.indexOf(s)>-1||/[A-Z]/u.test(s))}function D8t(s,t,r,{latestValues:n},a,i=!1,l){const c=(l??U4e(s)?L8t:I8t)(t,n,a,s),d=C8t(t,typeof s=="string",i),h=s!==k.Fragment?{...d,...c,ref:r}:{},{children:m}=t,x=k.useMemo(()=>Wh(m)?m.get():m,[m]);return k.createElement(s,{...h,children:x})}function R8t({scrapeMotionValuesFromProps:s,createRenderState:t},r,n,a){return{latestValues:O8t(r,n,a,s),renderState:t()}}function O8t(s,t,r,n){const a={},i=n(s,{});for(const x in i)a[x]=hce(i[x]);let{initial:l,animate:o}=s;const c=Cfe(s),d=Ltt(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let h=r?r.initial===!1:!1;h=h||l===!1;const m=h?o:l;if(m&&typeof m!="boolean"&&!Sfe(m)){const x=Array.isArray(m)?m:[m];for(let y=0;y(t,r)=>{const n=k.useContext(Tfe),a=k.useContext(jfe),i=()=>R8t(s,t,n,a);return r?i():f4e(i)},F8t=ust({scrapeMotionValuesFromProps:F4e,createRenderState:$4e}),B8t=ust({scrapeMotionValuesFromProps:Gtt,createRenderState:dst}),z8t=Symbol.for("motionComponentSymbol");function $8t(s,t,r){const n=k.useRef(r);k.useInsertionEffect(()=>{n.current=r});const a=k.useRef(null);return k.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=n.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 hst=k.createContext({});function bE(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function U8t(s,t,r,n,a,i){var T,A;const{visualElement:l}=k.useContext(Tfe),o=k.useContext(ist),c=k.useContext(jfe),d=k.useContext(B4e),h=d.reducedMotion,m=d.skipAnimations,x=k.useRef(null),y=k.useRef(!1);n=n||o.renderer,!x.current&&n&&(x.current=n(s,{visualState:t,parent:l,props:r,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:h,skipAnimations:m,isSVG:i}),y.current&&x.current&&(x.current.manuallyAnimateOnMount=!0));const v=x.current,w=k.useContext(hst);v&&!v.projection&&a&&(v.type==="html"||v.type==="svg")&&q8t(x.current,r,a,w);const b=k.useRef(!1);k.useInsertionEffect(()=>{v&&b.current&&v.update(r,c)});const N=r[_tt],S=k.useRef(!!N&&typeof window<"u"&&!((T=window.MotionHandoffIsComplete)!=null&&T.call(window,N))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,N)));return Let(()=>{y.current=!0,v&&(b.current=!0,window.MotionIsMounted=!0,v.updateFeatures(),v.scheduleRenderMicrotask(),S.current&&v.animationState&&v.animationState.animateChanges())}),k.useEffect(()=>{v&&(!S.current&&v.animationState&&v.animationState.animateChanges(),S.current&&(queueMicrotask(()=>{var I;(I=window.MotionHandoffMarkAsComplete)==null||I.call(window,N)}),S.current=!1),v.enteringChildren=void 0)}),v}function q8t(s,t,r,n){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:h,layoutCrossfade:m}=t;s.projection=new r(s.latestValues,t["data-framer-portal-id"]?void 0:mst(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&bE(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:n,crossfade:m,layoutScroll:c,layoutRoot:d,layoutAnchor:h})}function mst(s){if(s)return s.options.allowProjection!==!1?s.projection:mst(s.parent)}function Ave(s,{forwardMotionProps:t=!1,type:r}={},n,a){n&&N8t(n);const i=r?r==="svg":U4e(s),l=i?B8t:F8t;function o(d,h){let m;const x={...k.useContext(B4e),...d,layoutId:V8t(d)},{isStatic:y}=x,v=E8t(d),w=l(d,y);if(!y&&typeof window<"u"){H8t();const b=G8t(x);m=b.MeasureLayout,v.visualElement=U8t(s,w,x,a,b.ProjectionNode,i)}return e.jsxs(Tfe.Provider,{value:v,children:[m&&v.visualElement?e.jsx(m,{visualElement:v.visualElement,...x}):null,D8t(s,d,$8t(w,v.visualElement,h),w,y,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=k.forwardRef(o);return c[z8t]=s,c}function V8t({layoutId:s}){const t=k.useContext(m4e).id;return t&&s!==void 0?t+"-"+s:s}function H8t(s,t){k.useContext(ist).strict}function G8t(s){const t=ost(),{drag:r,layout:n}=t;if(!r&&!n)return{};const a={...r,...n};return{MeasureLayout:r!=null&&r.isEnabled(s)||n!=null&&n.isEnabled(s)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function W8t(s,t){if(typeof Proxy>"u")return Ave;const r=new Map,n=(i,l)=>Ave(i,l,s,t),a=(i,l)=>n(i,l);return new Proxy(a,{get:(i,l)=>l==="create"?n:(r.has(l)||r.set(l,Ave(l,void 0,s,t)),r.get(l))})}const K8t=(s,t)=>t.isSVG??U4e(s)?new NOt(t):new yOt(t,{allowProjection:s!==k.Fragment});class Y8t extends s2{constructor(t){super(t),t.animationState||(t.animationState=EOt(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Sfe(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:r}=this.node.prevProps||{};t!==r&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let Z8t=0;class X8t extends s2{constructor(){super(...arguments),this.id=Z8t++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:r}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===n)return;if(t&&n===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"){const c=i3(this.node,l,o);if(c){const{transition:d,transitionEnd:h,...m}=c;for(const x in m)(i=this.node.getValue(x))==null||i.jump(m[x])}}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);r&&!t&&a.then(()=>{this.isExitComplete=!0,r(this.id)})}mount(){const{register:t,onExitComplete:r}=this.node.presenceContext||{};r&&r(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Q8t={animation:{Feature:Y8t},exit:{Feature:X8t}};function oB(s){return{point:{x:s.pageX,y:s.pageY}}}const J8t=s=>t=>L4e(t)&&s(t,oB(t));function cO(s,t,r,n){return b8(s,t,J8t(r),n)}const fst=({current:s})=>s?s.ownerDocument.defaultView:null,YOe=(s,t)=>Math.abs(s-t);function eFt(s,t){const r=YOe(s.x,t.x),n=YOe(s.y,t.y);return Math.sqrt(r**2+n**2)}const ZOe=new Set(["auto","scroll"]);class pst{constructor(t,r,{transformPagePoint:n,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=y=>{this.handleScroll(y.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Y9(this.lastRawMoveEventInfo,this.transformPagePoint));const y=Mve(this.lastMoveEventInfo,this.history),v=this.startEvent!==null,w=eFt(y.offset,{x:0,y:0})>=this.distanceThreshold;if(!v&&!w)return;const{point:b}=y,{timestamp:N}=$h;this.history.push({...b,timestamp:N});const{onStart:S,onMove:T}=this.handlers;v||(S&&S(this.lastMoveEvent,y),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,y)},this.handlePointerMove=(y,v)=>{this.lastMoveEvent=y,this.lastRawMoveEventInfo=v,this.lastMoveEventInfo=Y9(v,this.transformPagePoint),Zl.update(this.updatePoint,!0)},this.handlePointerUp=(y,v)=>{this.end();const{onEnd:w,onSessionEnd:b,resumeAnimation:N}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&N&&N(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const S=Mve(y.type==="pointercancel"?this.lastMoveEventInfo:Y9(v,this.transformPagePoint),this.history);this.startEvent&&w&&w(y,S),b&&b(y,S)},!L4e(t))return;this.dragSnapToOrigin=i,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=l,this.contextWindow=a||window;const c=oB(t),d=Y9(c,this.transformPagePoint),{point:h}=d,{timestamp:m}=$h;this.history=[{...h,timestamp:m}];const{onSessionStart:x}=r;x&&x(t,Mve(d,this.history)),this.removeListeners=nB(cO(this.contextWindow,"pointermove",this.handlePointerMove),cO(this.contextWindow,"pointerup",this.handlePointerUp),cO(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let r=t.parentElement;for(;r;){const n=getComputedStyle(r);(ZOe.has(n.overflowX)||ZOe.has(n.overflowY))&&this.scrollPositions.set(r,{x:r.scrollLeft,y:r.scrollTop}),r=r.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 r=this.scrollPositions.get(t);if(!r)return;const n=t===window,a=n?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-r.x,y:a.y-r.y};i.x===0&&i.y===0||(n?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),Zl.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Pj(this.updatePoint)}}function Y9(s,t){return t?{point:t(s.point)}:s}function XOe(s,t){return{x:s.x-t.x,y:s.y-t.y}}function Mve({point:s},t){return{point:s,delta:XOe(s,xst(t)),offset:XOe(s,tFt(t)),velocity:sFt(t,.1)}}function tFt(s){return s[0]}function xst(s){return s[s.length-1]}function sFt(s,t){if(s.length<2)return{x:0,y:0};let r=s.length-1,n=null;const a=xst(s);for(;r>=0&&(n=s[r],!(a.timestamp-n.timestamp>tp(t)));)r--;if(!n)return{x:0,y:0};n===s[0]&&s.length>2&&a.timestamp-n.timestamp>tp(t)*2&&(n=s[1]);const i=tg(a.timestamp-n.timestamp);if(i===0)return{x:0,y:0};const l={x:(a.x-n.x)/i,y:(a.y-n.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function rFt(s,{min:t,max:r},n){return t!==void 0&&sr&&(s=n?Cc(r,s,n.max):Math.min(s,r)),s}function QOe(s,t,r){return{min:t!==void 0?s.min+t:void 0,max:r!==void 0?s.max+r-(s.max-s.min):void 0}}function nFt(s,{top:t,left:r,bottom:n,right:a}){return{x:QOe(s.x,r,a),y:QOe(s.y,t,n)}}function JOe(s,t){let r=t.min-s.min,n=t.max-s.max;return t.max-t.minn?r=g8(t.min,t.max-n,s.min):n>a&&(r=g8(s.min,s.max-a,t.min)),jv(0,1,r)}function oFt(s,t){const r={};return t.min!==void 0&&(r.min=t.min-s.min),t.max!==void 0&&(r.max=t.max-s.min),r}const Pje=.35;function lFt(s=Pje){return s===!1?s=0:s===!0&&(s=Pje),{x:e8e(s,"left","right"),y:e8e(s,"top","bottom")}}function e8e(s,t,r){return{min:t8e(s,t),max:t8e(s,r)}}function t8e(s,t){return typeof s=="number"?s:s[t]||0}const cFt=new WeakMap;class dFt{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=Lu(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:r=!1,distanceThreshold:n}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=m=>{r&&this.snapToCursor(oB(m).point),this.stopAnimation()},l=(m,x)=>{const{drag:y,dragPropagation:v,onDragStart:w}=this.getProps();if(y&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ORt(y),!this.openDragLock))return;this.latestPointerEvent=m,this.latestPanInfo=x,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),S0(N=>{let S=this.getAxisMotionValue(N).get()||0;if(fv.test(S)){const{projection:T}=this.visualElement;if(T&&T.layout){const A=T.layout.layoutBox[N];A&&(S=of(A)*(parseFloat(S)/100))}}this.originPoint[N]=S}),w&&Zl.update(()=>w(m,x),!1,!0),kje(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},o=(m,x)=>{this.latestPointerEvent=m,this.latestPanInfo=x;const{dragPropagation:y,dragDirectionLock:v,onDirectionLock:w,onDrag:b}=this.getProps();if(!y&&!this.openDragLock)return;const{offset:N}=x;if(v&&this.currentDirection===null){this.currentDirection=hFt(N),this.currentDirection!==null&&w&&w(this.currentDirection);return}this.updateAxis("x",x.point,N),this.updateAxis("y",x.point,N),this.visualElement.render(),b&&Zl.update(()=>b(m,x),!1,!0)},c=(m,x)=>{this.latestPointerEvent=m,this.latestPanInfo=x,this.stop(m,x),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:m}=this.getProps();(m||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:h}=this.getProps();this.panSession=new pst(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:h,distanceThreshold:n,contextWindow:fst(this.visualElement),element:this.visualElement.current})}stop(t,r){const n=t||this.latestPointerEvent,a=r||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!n)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Zl.postRender(()=>o(n,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:r}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),r&&r.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,r,n){const{drag:a}=this.getProps();if(!n||!Z9(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+n[t];this.constraints&&this.constraints[t]&&(l=rFt(l,this.constraints[t],this.elastic[t])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:t,dragElastic:r}=this.getProps(),n=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&&bE(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&n?this.constraints=nFt(n.layoutBox,t):this.constraints=!1,this.elastic=lFt(r),a!==this.constraints&&!bE(t)&&n&&this.constraints&&!this.hasMutatedConstraints&&S0(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=oFt(n.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:r}=this.getProps();if(!t||!bE(t))return!1;const n=t.current;IM(n!==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=hOt(n,a.root,this.visualElement.getTransformPagePoint());let l=aFt(a.layout.layoutBox,i);if(r){const o=r(cOt(l));this.hasMutatedConstraints=!!o,o&&(l=Ott(o))}return l}startAnimation(t){const{drag:r,dragMomentum:n,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=S0(h=>{if(!Z9(h,r,this.currentDirection))return;let m=c&&c[h]||{};(l===!0||l===h)&&(m={min:0,max:0});const x=a?200:1e6,y=a?40:1e7,v={type:"inertia",velocity:n?t[h]:0,bounceStiffness:x,bounceDamping:y,timeConstant:750,restDelta:1,restSpeed:10,...i,...m};return this.startAxisValueAnimation(h,v)});return Promise.all(d).then(o)}startAxisValueAnimation(t,r){const n=this.getAxisMotionValue(t);return kje(this.visualElement,t),n.start(C4e(t,n,0,r,this.visualElement,!1))}stopAnimation(){S0(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const r=`_drag${t.toUpperCase()}`,n=this.visualElement.getProps(),a=n[r];return a||this.visualElement.getValue(t,(n.initial?n.initial[t]:void 0)||0)}snapToCursor(t){S0(r=>{const{drag:n}=this.getProps();if(!Z9(r,n,this.currentDirection))return;const{projection:a}=this.visualElement,i=this.getAxisMotionValue(r);if(a&&a.layout){const{min:l,max:o}=a.layout.layoutBox[r],c=i.get()||0;i.set(t[r]-Cc(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!bE(r)||!n||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};S0(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=iFt({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),S0(l=>{if(!Z9(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Cc(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;cFt.set(this.visualElement,this);const t=this.visualElement.current,r=cO(t,"pointerdown",d=>{const{drag:h,dragListener:m=!0}=this.getProps(),x=d.target,y=x!==t&&qRt(x);h&&m&&!y&&this.start(d)});let n;const a=()=>{const{dragConstraints:d}=this.getProps();bE(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),n||(n=uFt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Zl.read(a);const o=b8(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:h})=>{this.isDragging&&h&&(S0(m=>{const x=this.getAxisMotionValue(m);x&&(this.originPoint[m]+=d[m].translate,x.set(x.get()+d[m].translate))}),this.visualElement.render())});return()=>{o(),r(),l(),c&&c(),n&&n()}}getProps(){const t=this.visualElement.getProps(),{drag:r=!1,dragDirectionLock:n=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=Pje,dragMomentum:o=!0}=t;return{...t,drag:r,dragDirectionLock:n,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function s8e(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function uFt(s,t,r){const n=cOe(s,s8e(r)),a=cOe(t,s8e(r));return()=>{n(),a()}}function Z9(s,t,r){return(t===!0||t===s)&&(r===null||r===s)}function hFt(s,t=10){let r=null;return Math.abs(s.y)>t?r="y":Math.abs(s.x)>t&&(r="x"),r}class mFt extends s2{constructor(t){super(t),this.removeGroupControls=cg,this.removeListeners=cg,this.controls=new dFt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||cg}update(){const{dragControls:t}=this.node.getProps(),{dragControls:r}=this.node.prevProps||{};t!==r&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const Ive=s=>(t,r)=>{s&&Zl.update(()=>s(t,r),!1,!0)};class fFt extends s2{constructor(){super(...arguments),this.removePointerDownListener=cg}onPointerDown(t){this.session=new pst(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:fst(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:r,onPan:n,onPanEnd:a}=this.node.getProps();return{onSessionStart:Ive(t),onStart:Ive(r),onMove:Ive(n),onEnd:(i,l)=>{delete this.session,a&&Zl.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=cO(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 Lve=!1;class pFt extends k.Component{componentDidMount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n,layoutId:a}=this.props,{projection:i}=t;i&&(r.group&&r.group.add(i),n&&n.register&&a&&n.register(i),Lve&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),mce.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:r,visualElement:n,drag:a,isPresent:i}=this.props,{projection:l}=n;return l&&(l.isPresent=i,t.layoutDependency!==r&&l.setOptions({...l.options,layoutDependency:r}),Lve=!0,a||t.layoutDependency!==r||r===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Zl.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:r}=this.props,{projection:n}=t;n&&(n.options.layoutAnchor=r,n.root.didUpdate(),I4e.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:a}=t;Lve=!0,a&&(a.scheduleCheckAfterUnmount(),r&&r.group&&r.group.remove(a),n&&n.deregister&&n.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function gst(s){const[t,r]=ast(),n=k.useContext(m4e);return e.jsx(pFt,{...s,layoutGroup:n,switchLayoutGroup:k.useContext(hst),isPresent:t,safeToRemove:r})}const xFt={pan:{Feature:fFt},drag:{Feature:mFt,ProjectionNode:nst,MeasureLayout:gst}};function r8e(s,t,r){const{props:n}=s;s.animationState&&n.whileHover&&s.animationState.setActive("whileHover",r==="Start");const a="onHover"+r,i=n[a];i&&Zl.postRender(()=>i(t,oB(t)))}class gFt extends s2{mount(){const{current:t}=this.node;t&&(this.unmount=BRt(t,(r,n)=>(r8e(this.node,n,"Start"),a=>r8e(this.node,a,"End"))))}unmount(){}}class yFt extends s2{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=nB(b8(this.node.current,"focus",()=>this.onFocus()),b8(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function n8e(s,t,r){const{props:n}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&n.whileTap&&s.animationState.setActive("whileTap",r==="Start");const a="onTap"+(r==="End"?"":r),i=n[a];i&&Zl.postRender(()=>i(t,oB(t)))}class vFt extends s2{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=HRt(t,(a,i)=>(n8e(this.node,i,"Start"),(l,{success:o})=>n8e(this.node,l,o?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const Dje=new WeakMap,Pve=new WeakMap,bFt=s=>{const t=Dje.get(s.target);t&&t(s)},_Ft=s=>{s.forEach(bFt)};function wFt({root:s,...t}){const r=s||document;Pve.has(r)||Pve.set(r,{});const n=Pve.get(r),a=JSON.stringify(t);return n[a]||(n[a]=new IntersectionObserver(_Ft,{root:s,...t})),n[a]}function jFt(s,t,r){const n=wFt(t);return Dje.set(s,r),n.observe(s),()=>{Dje.delete(s),n.unobserve(s)}}const NFt={some:0,all:1};class kFt extends s2{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:r,margin:n,amount:a="some",once:i}=t,l={root:r?r.current:void 0,rootMargin:n,threshold:typeof a=="number"?a:NFt[a]},o=d=>{const{isIntersecting:h}=d;if(this.isInView===h||(this.isInView=h,i&&!h&&this.hasEnteredView))return;h&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",h);const{onViewportEnter:m,onViewportLeave:x}=this.node.getProps(),y=h?m:x;y&&y(d)};this.stopObserver=jFt(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:r}=this.node;["amount","margin","root"].some(SFt(t,r))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function SFt({viewport:s={}},{viewport:t={}}={}){return r=>s[r]!==t[r]}const CFt={inView:{Feature:kFt},tap:{Feature:vFt},focus:{Feature:yFt},hover:{Feature:gFt}},TFt={layout:{ProjectionNode:nst,MeasureLayout:gst}},EFt={...Q8t,...CFt,...xFt,...TFt},Sr=W8t(EFt,K8t),AFt={some:0,all:1};function MFt(s,t,{root:r,margin:n,amount:a="some"}={}){const i=M4e(s),l=new WeakMap,o=d=>{d.forEach(h=>{const m=l.get(h.target);if(h.isIntersecting!==!!m)if(h.isIntersecting){const x=t(h.target,h);typeof x=="function"?l.set(h.target,x):c.unobserve(h.target)}else typeof m=="function"&&(m(h),l.delete(h.target))})},c=new IntersectionObserver(o,{root:r,rootMargin:n,threshold:typeof a=="number"?a:AFt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function IFt(s,{root:t,margin:r,amount:n,once:a=!1,initial:i=!1}={}){const[l,o]=k.useState(i);return k.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:r,amount:n};return MFt(s.current,c,d)},[t,s,r,a,n]),l}function LFt(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 a8e(s){return s.visitor_intent==="buying"&&!s.has_agent}function PFt({token:s}={}){var v;const t=Ki(),r=s||t.token,{data:n,isLoading:a,isError:i}=y6t(r),l=Xt(),o=(v=n==null?void 0:n.open_houses)==null?void 0:v.id,{data:c}=mt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:w,error:b}=await V.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(b)throw b;return w},enabled:!!o});if(k.useEffect(()=>{if(!o)return;const w=V.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()=>{V.removeChannel(w)}},[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||!n)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=n.open_houses,h=(c==null?void 0:c.length)||0,m=(c==null?void 0:c.filter(w=>w.visitor_intent==="buying").length)||0,x=(c==null?void 0:c.filter(a8e).length)||0,y=w=>{if(!w)return"";const[b,N]=w.split(":"),S=parseInt(b);return`${S>12?S-12:S||12}:${N} ${S>=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(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(mc,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:x})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(En,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:m})]})]})]}),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:_s(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[y(d.start_time),d.end_time?` – ${y(d.end_time)}`:""]})]}),e.jsx(Qa,{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(z4e,{children:c.map((w,b)=>{var T;const N=LFt(w.visitor_intent),S=a8e(w);return e.jsxs(Sr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:b*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${S?"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 ${S?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(T=w.first_name[0])==null?void 0:T.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:[w.first_name," ",w.last_name||""]}),S&&e.jsx(Ge,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),w.has_agent&&e.jsx(Ge,{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(Ge,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${N.color}`,children:[N.emoji," ",N.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:_s(new Date(w.created_at),"h:mm a")})]})]})]},w.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(gb,{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 DFt(){const t=ec().pathname.slice(1);if(k.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const r=t.slice(5);if(r)return e.jsx(PFt,{token:r})}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(yet,{slug:t})}const RFt="#2a4c64",OFt="#406E71";function FFt({dealData:s,agentProfile:t,welcomeMessage:r,isWon:n,branding:a}){var v;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.brand_color)||RFt,o=(a==null?void 0:a.accent_color)||OFt,c=(a==null?void 0:a.logo_url)||null,d=(a==null?void 0:a.cover_photo_url)||null,h=(a==null?void 0:a.tagline)||"Your Real Estate Agent",m=d?{backgroundImage:`linear-gradient(135deg, ${l}d9 0%, ${l}b3 50%, ${o}d9 100%), url(${d})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${l} 0%, ${l} 30%, ${o} 100%)`},x="flex items-center gap-2 px-4 py-2.5 rounded-xl transition-colors",y={backgroundColor:`${l}1a`,color:l};return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative text-white px-4 pt-10 pb-16",style:m,children:[!d&&e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&e.jsx("div",{className:"mb-4 flex justify-center",children:e.jsx("div",{className:"bg-white/95 backdrop-blur-sm rounded-2xl px-4 py-2.5 shadow-lg",children:e.jsx("img",{src:c,alt:"Brand logo",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs("div",{className:"mb-6",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-20 h-20 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx("span",{className:"text-2xl font-bold text-white/70",children:((v=t.name)==null?void 0:v.charAt(0))||"?"})}),e.jsx("p",{className:"text-sm font-medium text-white/95",children:t.name}),e.jsx("p",{className:"text-xs text-white/60 mt-0.5",children:h})]}),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/80 mb-3",children:[e.jsx(En,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Listing":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1.5 font-serif",children:(s==null?void 0:s.deal_name)||"Your Transaction Portal"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-white/70 text-sm",children:[e.jsx(Ca,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:i})]}),r&&e.jsx("p",{className:"mt-4 text-sm text-white/80 leading-relaxed max-w-sm mx-auto",children:r})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-8 relative z-10",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-4",children:e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:x,style:y,children:[e.jsx(Cn,{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:x,style:y,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:x,style:y,children:[e.jsx(Jl,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function yst({targetCloseDate:s,actualCloseDate:t,clientName:r}){if(t||!s)return null;const n=s.split(/[-/T]/),a=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),i=new Date,l=pg(a,i);if(hIt(a,i),hv(a)&&!zu(a))return null;let o="from-blue-500 to-cyan-400",c="from-blue-50 to-cyan-50",d="text-blue-900",h="text-blue-600",m="🏡";l<=3?(o="from-emerald-500 to-teal-400",c="from-emerald-50 to-teal-50",d="text-emerald-900",h="text-emerald-600",m="🎉"):l<=7?(o="from-amber-500 to-orange-400",c="from-amber-50 to-orange-50",d="text-amber-900",h="text-amber-600",m="⏳"):l<=14&&(o="from-violet-500 to-purple-400",c="from-violet-50 to-purple-50",d="text-violet-900",h="text-violet-600",m="📅");const x=zu(a)?"Today!":l===1?"1":String(l),y=zu(a)?"Closing Day":l===1?"day until closing":"days until closing";return e.jsxs("div",{className:`bg-gradient-to-br ${c} rounded-2xl p-6 border border-white/60 shadow-sm text-center`,children:[e.jsx("span",{className:"text-3xl mb-2 block",children:m}),zu(a)?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:`text-2xl font-bold ${d}`,children:"It's Closing Day!"}),e.jsxs("p",{className:`text-sm ${h} mt-1`,children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","! 🎊"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-baseline justify-center gap-1.5",children:e.jsx("span",{className:`text-5xl font-bold ${d} tabular-nums leading-none`,children:x})}),e.jsx("p",{className:`text-sm font-medium ${h} mt-1.5`,children:y}),l<=7&&e.jsxs("p",{className:`text-xs ${h} opacity-70 mt-1`,children:["You're almost there",r?`, ${r.split(" ")[0]}`:"","!"]})]}),!zu(a)&&l<=30&&e.jsx("div",{className:"mt-4 mx-auto w-full max-w-[200px]",children:e.jsx("div",{className:"h-2 rounded-full bg-white/60 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full bg-gradient-to-r ${o} transition-all duration-1000`,style:{width:`${Math.max(5,Math.min(100,(30-l)/30*100))}%`}})})})]})}function vst({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800 mb-1",children:"Your Home Journey"}),e.jsx("p",{className:"text-xs text-slate-400 mb-5",children:"Follow along as your transaction progresses"}),e.jsx("div",{className:"relative",children:s.map((r,n)=>{const a=nt;return e.jsxs("div",{className:"flex items-start gap-3.5 relative",children:[n{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",{className:"bg-gradient-to-br from-[#406E71]/5 via-white to-[#406E71]/5 rounded-2xl border border-[#406E71]/15 overflow-hidden",children:[e.jsx("div",{className:"bg-[#406E71] px-5 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{className:"w-4 h-4 text-white/80"}),e.jsx("h3",{className:"text-sm font-semibold text-white",children:"Current Stage"})]})}),e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-lg font-bold text-slate-800",children:s.label}),e.jsx("p",{className:"text-sm text-slate-500 mt-1 leading-relaxed",children:s.description})]}),t&&e.jsxs("div",{className:"bg-slate-50 rounded-xl p-4 border border-slate-100",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:"Update from your agent"}),e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:t})]}),r&&e.jsxs("div",{className:"bg-blue-50/60 rounded-xl p-4 border border-blue-100",children:[e.jsx("p",{className:"text-xs font-semibold text-blue-600 uppercase tracking-wider mb-1.5",children:"What's Next"}),e.jsx("p",{className:"text-sm text-blue-800 leading-relaxed",children:r})]}),n&&e.jsx("div",{className:"rounded-xl overflow-hidden bg-slate-900 aspect-video shadow-md",children:e.jsx("iframe",{src:a(n)||n,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})]})}function Fl(s){const t=s.split(/[-/T]/);if(t.length>=3){const r=Number(t[0]);return r>99?new Date(r,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 BFt(s,t){const r=_s(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${r}/${r}`,details:"Added from your Client Portal"}).toString()}`}function zFt(s,t){const r=_s(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${r} DTEND;VALUE=DATE:${r} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function _st({targetCloseDate:s,contractDate:t,inspectionDate:r,appraisalDate:n,actualCloseDate:a}){const i=[{label:"Contract Date",date:t,icon:uA,color:"text-blue-600 bg-blue-50"},{label:"Inspection",date:r,icon:yn,color:"text-amber-600 bg-amber-50"},{label:"Appraisal",date:n,icon:En,color:"text-purple-600 bg-purple-50"},{label:a?"Closed":"Target Close",date:a||s,icon:on,color:"text-emerald-600 bg-emerald-50"}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const h=Fl(c);if(d==="google")window.open(BFt(o,h),"_blank");else{const m=zFt(o,h),x=document.createElement("a");x.href=m,x.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,x.click()}};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Key Dates"}),e.jsx("div",{className:"space-y-3",children:i.map(({label:o,date:c,icon:d,color:h})=>{const m=Fl(c),x=hv(m)&&!zu(m),y=zu(m),v=!x&&!y;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 ${h}`,children:e.jsx(d,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs text-slate-500",children:o}),e.jsxs("p",{className:`text-sm font-medium ${y?"text-emerald-600":x?"text-slate-400":"text-slate-800"}`,children:[_s(m,"MMM d, yyyy"),y&&e.jsx("span",{className:"ml-1.5 text-xs bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded-full",children:"Today"})]})]}),x&&e.jsx("span",{className:"text-xs text-slate-400",children:"✓"}),v&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"text-xs text-slate-400 hover:text-blue-500 transition-colors px-1.5 py-1 rounded hover:bg-blue-50",title:"Add to Google Calendar",children:e.jsx(rb,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>l(o,c,"apple"),className:"text-[10px] text-slate-400 hover:text-slate-600 transition-colors px-1.5 py-1 rounded hover:bg-slate-100",title:"Download .ics file",children:".ics"})]})]},o)})})]})}function wst({documents:s}){const t=n=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,r=async n=>{const{data:a}=await V.storage.from("deal-files").createSignedUrl(n.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-3",children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(n=>e.jsxs("button",{onClick:()=>r(n),className:"w-full flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors text-left group",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-slate-100 flex items-center justify-center flex-shrink-0 group-hover:bg-blue-50 transition-colors",children:e.jsx(ln,{className:"w-4 h-4 text-slate-500 group-hover:text-blue-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-slate-700 truncate",children:n.file_name}),e.jsx("p",{className:"text-xs text-slate-400",children:t(n.file_size)})]}),e.jsx(Ya,{className:"w-4 h-4 text-slate-300 group-hover:text-blue-500 transition-colors"})]},n.id))})]})}function jst({updates:s}){const t=r=>{var n,a;if(r.includes("youtube.com/watch")){const i=new URL(r).searchParams.get("v");return i?`https://www.youtube.com/embed/${i}`:null}if(r.includes("youtu.be/")){const i=(n=r.split("youtu.be/")[1])==null?void 0:n.split("?")[0];return i?`https://www.youtube.com/embed/${i}`:null}if(r.includes("loom.com/share/")){const i=(a=r.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return i?`https://www.loom.com/embed/${i}`:null}return r};return e.jsxs("div",{className:"bg-white rounded-2xl p-5 shadow-sm border border-slate-100",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-4",children:"Updates from Your Agent"}),e.jsx("div",{className:"space-y-4",children:s.map((r,n)=>e.jsx("div",{className:`${n>0?"pt-4 border-t border-slate-100":""}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 ${r.is_stage_change?"bg-emerald-100":"bg-blue-100"}`,children:r.is_stage_change?e.jsx(Ad,{className:"w-3.5 h-3.5 text-emerald-600"}):e.jsx(_m,{className:"w-3.5 h-3.5 text-blue-600"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"text-sm font-medium text-slate-800",children:r.title}),e.jsx("span",{className:"text-xs text-slate-400 flex-shrink-0",children:_s(new Date(r.created_at),"MMM d")})]}),r.content&&e.jsx("p",{className:"text-sm text-slate-500 mt-1 leading-relaxed",children:r.content}),r.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden bg-slate-900 aspect-video",children:e.jsx("iframe",{src:t(r.video_url)||r.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:r.title})})]})]})},r.id))})]})}const lB=[{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"}],$Ft=[{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 UFt(s){return mt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(r)throw r;return t||[]},enabled:!!s})}function qFt(){const s=sa(),{brokerageId:t}=js();return mt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let r=V.from("vendors").select("*");t?r=r.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):r=r.eq("owner_type","agent").eq("owner_user_id",s);const[{data:n,error:a},{data:i,error:l}]=await Promise.all([r.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),V.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:n||[],selections:i||[]}},enabled:!!s})}function VFt(){const s=Xt();return Ct({mutationFn:async t=>{if(t.id){const{id:r,created_at:n,...a}=t,{data:i,error:l}=await V.from("vendors").update(a).eq("id",r).select().single();if(l)throw l;return i}else{const{data:r,error:n}=await V.from("vendors").insert(t).select().single();if(n)throw n;return r}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function Nst(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("vendors").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function HFt(){const s=sa(),t=Xt();return Ct({mutationFn:async({vendorId:r,isVisible:n})=>{if(!s)throw new Error("No user");const{data:a}=await V.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",r).maybeSingle();if(a){const{error:i}=await V.from("agent_vendor_selections").update({is_visible:n}).eq("id",a.id);if(i)throw i}else{const{error:i}=await V.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:r,is_visible:n});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function GFt(s){return mt({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const[{data:t},{data:r}]=await Promise.all([V.from("agent_vendor_selections").select("vendor_id, display_order, stage_filter, is_visible, vendors:vendors!inner(*)").eq("agent_user_id",s.owner_user_id).eq("is_visible",!0),V.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]),n=new Map;return(r||[]).forEach(i=>n.set(i.vendor_id,i.is_visible)),(t||[]).map(i=>({...i.vendors,display_order:i.display_order})).filter(i=>i.is_active&&n.get(i.id)!==!1).sort((i,l)=>(i.display_order||0)-(l.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function WFt(s){try{await V.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 kst(s,t){return mt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:r}=await V.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),n=(r||[]).map(l=>l.id);if(n.length===0)return{};const{data:a}=await V.from("vendor_clicks").select("vendor_id").in("vendor_id",n),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function Sst({portalId:s,ownerUserId:t,currentStage:r,brandingColor:n}){const{data:a=[],isLoading:i}=GFt({id:s,owner_user_id:t});if(i||a.length===0)return null;const l=a.filter(x=>!x.stage_filter||x.stage_filter.length===0||!r?!0:x.stage_filter.includes(r));if(l.length===0)return null;const o=l.reduce((x,y)=>((x[y.category]=x[y.category]||[]).push(y),x),{}),c=n||"#406E71",d=x=>{let y=x.action_type,v=null;switch(x.action_type){case"book":v=x.booking_url;break;case"website":v=x.website;break;case"call":v=x.phone?`tel:${x.phone.replace(/[^\d+]/g,"")}`:null;break;case"email":case"quote":v=x.email?`mailto:${x.email}`:null;break}WFt({vendorId:x.id,portalId:s,agentUserId:t,actionTaken:y}),v&&window.open(v,x.action_type==="call"||x.action_type==="email"||x.action_type==="quote"?"_self":"_blank")},h=x=>{switch(x.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"}},m=x=>{switch(x.action_type){case"book":return e.jsx(on,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Cn,{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(fc,{className:"w-3.5 h-3.5"})}};return e.jsxs(ke,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[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(jr,{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"})]})]}),e.jsx("div",{className:"space-y-4",children:Object.entries(o).map(([x,y])=>{var w;const v=((w=lB.find(b=>b.value===x))==null?void 0:w.label)||x;return e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:v}),e.jsx("div",{className:"space-y-2",children:y.map(b=>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: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-sm font-semibold text-slate-500",children:b.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:b.company||b.name}),b.company&&b.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:b.name}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:b.description})]}),e.jsxs(G,{size:"sm",onClick:()=>d(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[m(b),e.jsx("span",{className:"ml-1.5 text-xs",children:h(b)})]})]},b.id))})]},x)})}),l.some(x=>x.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:l.filter(x=>x.disclosure_text).map(x=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[x.company||x.name,":"]})," ",x.disclosure_text]},x.id))})]})}function KFt(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 YFt(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 r=s.match(/loom\.com\/share\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:(s.match(/\.(mp4|webm|mov)(\?|$)/i),s)}function Cst({portalId:s,portalSlug:t,ownerUserId:r,rewardText:n,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,h]=k.useState(!1),m=k.useRef(!1),x=KFt(t);k.useEffect(()=>{m.current||(m.current=!0,V.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,r]);const y=async D=>{await V.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:r,click_type:D,user_agent:navigator.userAgent.slice(0,500)})},v=()=>`${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: ${x}`,w=async()=>{await navigator.clipboard.writeText(x),h(!0),y("copy_link"),setTimeout(()=>h(!1),2e3)},b=()=>{y("share_sms");const D=encodeURIComponent(v());window.location.href=`sms:?&body=${D}`},N=()=>{y("share_email");const D=encodeURIComponent("A referral you'll thank me for"),R=encodeURIComponent(v());window.location.href=`mailto:?subject=${D}&body=${R}`},S=()=>{y("open_form"),window.open(x,"_blank")},T=a||"Know someone buying or selling?",A=c?YFt(c):null,I=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(jr,{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:I?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(ii,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:T}),n&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),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:S,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(Ha,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:b,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Jl,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:N,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:w,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(Kn,{className:"w-3.5 h-3.5"}):e.jsx(Ra,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>y("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(Ha,{className:"w-4 h-4 text-slate-400"})]})})]})}function ZFt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function XFt(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 QFt={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. 🎉"}},Tst=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Efe(s){return Tst.map(t=>{if(t==="Active")return{key:"Active",label:ZFt(s),description:XFt(s)};const r=QFt[t];return{key:t,label:r.label,description:r.description}})}function zde(s){if(!s)return 0;const t=Tst.indexOf(s);return t>=0?t:0}const JFt="#2a4c64",eBt="#406E71";function tBt({portal:s,linkedPortal:t,activePortal:r,activeTab:n,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var Z,re,le;const d=(l==null?void 0:l.brand_color)||JFt,h=(l==null?void 0:l.accent_color)||eBt,m=(l==null?void 0:l.cover_photo_url)||null,x=(l==null?void 0:l.logo_url)||null,y=(l==null?void 0:l.tagline)||"Your Real Estate Agent",v=r==null?void 0:r.deal_pipeline,w=v==null?void 0:v.deal_pipeline_stages,b=w==null?void 0:w.is_won_stage,N=v==null?void 0:v.deal_type,S=r==null?void 0:r.stage_mapping;let T=Efe(N);S&&S.length>0&&(T=S.map((oe,ne)=>{var ie,ye;return{key:`custom-${ne}`,label:oe.label||((ie=T[ne])==null?void 0:ie.label)||`Stage ${ne+1}`,description:oe.description||((ye=T[ne])==null?void 0:ye.description)||"",video_url:oe.video_url||void 0}}));const A=S&&S.length>0?Math.min(zde(w==null?void 0:w.name),T.length-1):zde(w==null?void 0:w.name),I=T[A],D=I==null?void 0:I.video_url,R=b&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,$=v!=null&&v.property_address?`${v.property_address}, ${v.city||""}, ${v.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,F=!!t,z=(Z=s==null?void 0:s.deal_pipeline)==null?void 0:Z.deal_type,Q=(re=t==null?void 0:t.deal_pipeline)==null?void 0:re.deal_type,K=oe=>oe==="listing"?"Your Sale":oe==="buy-side"?"Your Purchase":"Transaction",X=T.length>1?Math.round((A+1)/T.length*100):0;return e.jsxs("div",{className:"min-h-screen relative",style:{background:`radial-gradient(ellipse 80% 60% at 50% -10%, ${d}22, transparent 60%), linear-gradient(180deg, #f8fafc 0%, #ffffff 100%)`},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[480px] opacity-50",style:{background:`radial-gradient(circle at 80% 0%, ${h}33, transparent 50%), radial-gradient(circle at 10% 10%, ${d}33, transparent 55%)`}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[x?e.jsx("div",{className:"bg-white/80 backdrop-blur-sm rounded-xl px-3 py-1.5 shadow-sm border border-white",children:e.jsx("img",{src:x,alt:"Brand",className:"h-7 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center text-white font-bold shadow-md",style:{background:`linear-gradient(135deg, ${d}, ${h})`},children:e.jsx(jr,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.18em] text-slate-400 font-semibold",children:"Client Portal"}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:r!=null&&r.client_name?`Welcome, ${r.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(Wu,{className:"w-3.5 h-3.5"}),"Secure portal"]})]}),e.jsxs(Sr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.5,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl shadow-2xl border border-white/60 mb-8",style:{minHeight:320},children:[e.jsx("div",{className:"absolute inset-0",style:m?{backgroundImage:`linear-gradient(135deg, ${d}e6 0%, ${d}b3 45%, ${h}cc 100%), url(${m})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:`linear-gradient(135deg, ${d} 0%, ${h} 100%)`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"28px 28px"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-10 text-white",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 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-4 self-start",children:[e.jsx(En,{className:"w-3 h-3"}),N==="listing"?"Listing":N==="buy-side"?"Purchase":"Transaction",b&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"•"}),"Complete"]})]}),e.jsx("h1",{className:"text-5xl font-bold tracking-tight leading-[1.05] mb-3 font-serif",children:(v==null?void 0:v.deal_name)||"Your Transaction"}),$&&e.jsxs("div",{className:"flex items-center gap-1.5 text-white/80 text-base",children:[e.jsx(Ca,{className:"w-4 h-4"}),e.jsx("span",{children:$})]}),(r==null?void 0:r.welcome_message)&&e.jsx("p",{className:"mt-5 text-white/85 text-sm leading-relaxed max-w-2xl",children:r.welcome_message})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(sBt,{pct:X,brand:d,accent:h}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/70 mt-3",children:"Journey progress"}),e.jsxs("p",{className:"text-sm font-medium text-white/95 mt-1",children:["Stage ",A+1," of ",T.length]})]})]})]}),F&&e.jsx("div",{className:"inline-flex gap-1 bg-white/70 backdrop-blur border border-slate-200 rounded-xl p-1 mb-6 shadow-sm",children:["primary","linked"].map(oe=>{const ne=oe==="primary"?z:Q;return e.jsx("button",{onClick:()=>a(oe),className:`px-4 py-2 rounded-lg text-sm font-medium transition-all ${n===oe?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:K(ne)},oe)})}),e.jsxs("div",{className:"grid grid-cols-12 gap-6",children:[e.jsx("aside",{className:"col-span-3",children:e.jsxs("div",{className:"sticky top-6 space-y-4",children:[e.jsxs(O_,{children:[e.jsxs("div",{className:"text-center pt-2",children:[i!=null&&i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 rounded-full mx-auto object-cover ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center text-3xl font-bold text-white ring-4 ring-white shadow-lg",style:{background:`linear-gradient(135deg, ${d}, ${h})`},children:((le=i==null?void 0:i.name)==null?void 0:le.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 text-lg font-bold text-slate-800",children:i==null?void 0:i.name}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:y})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(Dve,{href:`tel:${i.phone}`,icon:Cn,label:"Call",sub:i.phone,brand:d}),(i==null?void 0:i.phone)&&e.jsx(Dve,{href:`sms:${i.phone}`,icon:Jl,label:"Text message",brand:d}),(i==null?void 0:i.email)&&e.jsx(Dve,{href:`mailto:${i.email}`,icon:Vs,label:"Email",sub:i.email,brand:d})]})]}),e.jsxs(O_,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"At a glance"}),e.jsxs("div",{className:"space-y-3",children:[(v==null?void 0:v.target_close_date)&&e.jsx(Rve,{icon:on,label:"Target close",value:i8e(v.target_close_date),brand:d}),(v==null?void 0:v.contract_date)&&e.jsx(Rve,{icon:fn,label:"Under contract",value:i8e(v.contract_date),brand:d}),e.jsx(Rve,{icon:jr,label:"Progress",value:`${X}%`,brand:d})]})]}),e.jsx("div",{className:"text-center pt-2 space-y-1",children:e.jsx("p",{className:"text-[11px] text-slate-400",children:"Powered by ReLevelUp"})})]})}),e.jsxs("main",{className:"col-span-6 space-y-6",children:[R&&e.jsx(Cst,{portalId:r.id,portalSlug:r.slug,ownerUserId:r.owner_user_id,rewardText:r.referral_reward_text,ctaHeadline:r.referral_cta_headline,agentName:i==null?void 0:i.name,clientName:r.client_name,reviewUrl:r.review_url,hubVideoUrl:r.homeowner_hub_video_url}),e.jsx(yst,{targetCloseDate:v==null?void 0:v.target_close_date,actualCloseDate:v==null?void 0:v.actual_close_date,clientName:r.client_name}),I&&e.jsxs(O_,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-3",children:"Where you are now"}),e.jsx(bst,{currentStage:I,nextStepText:r.next_step_text,nextStepVideoUrl:D||r.next_step_video_url})]}),e.jsxs(O_,{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-400 font-semibold mb-4",children:"Your journey"}),e.jsx(vst,{journeyStages:T,currentIndex:A})]}),o&&o.length>0&&e.jsx(O_,{children:e.jsx(jst,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-6",children:[e.jsx(O_,{children:e.jsx(_st,{targetCloseDate:v==null?void 0:v.target_close_date,contractDate:v==null?void 0:v.contract_date,inspectionDate:r.inspection_date,appraisalDate:r.appraisal_date,actualCloseDate:v==null?void 0:v.actual_close_date})}),c&&c.length>0&&e.jsx(O_,{children:e.jsx(wst,{documents:c})}),(r==null?void 0:r.id)&&(r==null?void 0:r.owner_user_id)&&e.jsx(O_,{children:e.jsx(Sst,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:w==null?void 0:w.name})})]})]})]})]})}function O_({children:s}){return e.jsx("div",{className:"bg-white/80 backdrop-blur-xl rounded-2xl border border-white shadow-[0_8px_32px_-8px_rgba(15,23,42,0.08)] p-5",children:s})}function Dve({href:s,icon:t,label:r,sub:n,brand:a}){return e.jsxs("a",{href:s,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all hover:scale-[1.02] hover:shadow-sm border border-transparent hover:border-slate-100",style:{backgroundColor:`${a}0d`},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${a}1f`,color:a},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 font-medium text-slate-800 leading-tight",children:r}),n&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:n})]})]})}function Rve({icon:s,label:t,value:r,brand: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:{backgroundColor:`${n}14`,color:n},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-slate-400 uppercase tracking-wide",children:t}),e.jsx("p",{className:"text-sm font-semibold text-slate-800 truncate",children:r})]})]})}function sBt({pct:s,brand:t,accent:r}){const l=2*Math.PI*74,o=l-s/100*l,c="pg-"+t.replace("#","");return e.jsxs("div",{className:"relative",style:{width:160,height:160},children:[e.jsxs("svg",{width:160,height:160,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"#ffffff",stopOpacity:"0.95"}),e.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:"0.9"})]})}),e.jsx("circle",{cx:160/2,cy:160/2,r:74,stroke:"rgba(255,255,255,0.18)",strokeWidth:12,fill:"none"}),e.jsx(Sr.circle,{cx:160/2,cy:160/2,r:74,stroke:`url(#${c})`,strokeWidth:12,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:l},animate:{strokeDashoffset:o},transition:{duration:1.2,ease:"easeOut"},strokeDasharray:l})]}),e.jsx("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:e.jsxs("span",{className:"text-4xl font-bold tabular-nums",children:[s,"%"]})})]})}function i8e(s){const t=s.split(/[-/T]/),r=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(r)}function rBt({portal:s,dealData:t,agentProfile:r,customQuestions:n,deviceFingerprint:a,onComplete:i}){var v,w;const[l,o]=k.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((w=s.client_name)==null?void 0:w.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]=k.useState({}),[h,m]=k.useState(!1),x=Ct({mutationFn:async()=>{const{error:b}=await V.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:h&&l.spouse_first_name||null,spouse_last_name:h&&l.spouse_last_name||null,spouse_email:h&&l.spouse_email||null,spouse_phone:h&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),ue.error("Something went wrong. Please try again.")}}),y=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null;return e.jsxs("div",{className:"max-w-md mx-auto px-4 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&e.jsx("img",{src:r.avatar_url,alt:r.name,className:"w-14 h-14 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-xl font-bold text-slate-800",children:"Welcome to Your Portal"}),y&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(Ca,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:y.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),x.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"First Name *"}),e.jsx(Ne,{required:!0,value:l.first_name,onChange:b=>o(N=>({...N,first_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(Ne,{value:l.last_name,onChange:b=>o(N=>({...N,last_name:b.target.value})),className:"mt-1 rounded-xl",placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(Ne,{type:"email",value:l.email,onChange:b=>o(N=>({...N,email:b.target.value})),className:"mt-1 rounded-xl",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(Ne,{type:"tel",value:l.phone,onChange:b=>o(N=>({...N,phone:b.target.value})),className:"mt-1 rounded-xl",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",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(N=>({...N,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(he,{className:"text-xs text-slate-600",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(N=>({...N,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))})]}),n.map(b=>e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs text-slate-600",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(Ne,{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:"mt-1 rounded-xl"}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:"mt-1 w-full rounded-xl 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"}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:N=>d(S=>({...S,[b.id]:N.target.value})),className:"mt-1 w-full rounded-xl border border-input bg-background px-3 py-2 text-sm h-10",children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(N=>e.jsx("option",{value:N,children:N},N))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(N=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:N})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===N?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:N},N))})]},b.id)),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(N=>({...N,notes:b.target.value})),className:"mt-1 w-full rounded-xl 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:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>m(!h),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:h?"− Remove spouse/partner":"+ Add spouse/partner"}),h&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"First Name"}),e.jsx(Ne,{value:l.spouse_first_name,onChange:b=>o(N=>({...N,spouse_first_name:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Last Name"}),e.jsx(Ne,{value:l.spouse_last_name,onChange:b=>o(N=>({...N,spouse_last_name:b.target.value})),className:"mt-1 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Email"}),e.jsx(Ne,{type:"email",value:l.spouse_email,onChange:b=>o(N=>({...N,spouse_email:b.target.value})),className:"mt-1 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-slate-600",children:"Phone"}),e.jsx(Ne,{type:"tel",value:l.spouse_phone,onChange:b=>o(N=>({...N,spouse_phone:b.target.value})),className:"mt-1 rounded-xl"})]})]})]}),e.jsx(G,{type:"submit",disabled:x.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:x.isPending?"Submitting...":"Access My Portal"})]})]})}function nBt(s,t){const r=(n,a)=>a!=null&&a!==""?a:n!=null&&n!==""?n:null;return{logo_url:r(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:r(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:r(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:r(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:r(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:r(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message)}}function Est(){const s=sa();return mt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function aBt(s){return mt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function iBt(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("agent_portal_branding").upsert({user_id:s,...r},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function Ast(s,t,r){var o;const n=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${r}-${Date.now()}.${n}`,{error:i}=await V.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=V.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function oBt(s,t){return mt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:r,error:n}=await V.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(n)throw n;return r},enabled:t})}function lBt(s){return mt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})}function Mst({slug:s}){var oe,ne,ie,ye,ce,ve;const[t,r]=k.useState(!1),[n,a]=k.useState("primary"),[i]=k.useState(()=>{const be=`portal_fp_${s}`;let Ue=localStorage.getItem(be);return Ue||(Ue=localStorage.getItem("portal_fp"),Ue?localStorage.setItem(be,Ue):(Ue=crypto.randomUUID(),localStorage.setItem(be,Ue),localStorage.setItem("portal_fp",Ue))),Ue});k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=oBt(s,!0),d=l==null?void 0:l.linked_portal_id,{data:h}=lBt(d),m=(oe=l==null?void 0:l.deal_pipeline)==null?void 0:oe.owner_user_id;mt({queryKey:["portal-stages",m],queryFn:async()=>{const{data:be,error:Ue}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",m).order("sort_order",{ascending:!0});if(Ue)throw Ue;return be},enabled:!!m});const{data:x}=mt({queryKey:["portal-agent",m],queryFn:async()=>{const{data:be,error:Ue}=await V.from("profiles").select("id, name, avatar_url, phone, email").eq("id",m).single();if(Ue)throw Ue;return be},enabled:!!m}),{data:y}=aBt(m),v=n==="linked"&&h?h:l,w=v==null?void 0:v.id,b=nBt(y,v==null?void 0:v.branding_override),{data:N}=mt({queryKey:["portal-updates-public",w],queryFn:async()=>{const{data:be,error:Ue}=await V.from("portal_updates").select("*").eq("portal_id",w).order("created_at",{ascending:!1});if(Ue)throw Ue;return be},enabled:!!w}),S=(ne=v==null?void 0:v.deal_pipeline)==null?void 0:ne.id,{data:T}=mt({queryKey:["portal-documents",S],queryFn:async()=>{const{data:be,error:Ue}=await V.from("deal_files").select("*").eq("deal_id",S).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(Ue)throw Ue;return be},enabled:!!S}),A=l==null?void 0:l.id,I=A?`portal_onboarded_${A}_${i}`:null,D=I?localStorage.getItem(I)==="1":!1,{data:R,isLoading:$}=mt({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:be,error:Ue}=await V.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(Ue)throw Ue;return be&&I&&localStorage.setItem(I,"1"),be},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!D,staleTime:5*60*1e3}),F=!!(l!=null&&l.require_onboarding)&&!D&&!R&&!t,{data:z}=mt({queryKey:["portal-custom-questions-public",m],queryFn:async()=>{const{data:be,error:Ue}=await V.from("portal_custom_questions").select("*").eq("owner_user_id",m).eq("is_active",!0).order("sort_order",{ascending:!0});if(Ue)throw Ue;return be},enabled:!!m&&F}),Q=D||!!R||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!D&&$)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(es,{className:"w-6 h-6 text-slate-400 animate-spin"})});if(c||!l)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("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:"Portal Not Available"}),e.jsx("p",{className:"text-slate-500",children:"This portal is no longer active or doesn't exist."})]})});if(!Q){const be=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:e.jsx(rBt,{portal:l,dealData:be,agentProfile:x,customQuestions:z||[],deviceFingerprint:i,onComplete:()=>{I&&localStorage.setItem(I,"1"),r(!0)}})})}const K=(ie=l==null?void 0:l.deal_pipeline)==null?void 0:ie.deal_type,X=(ye=h==null?void 0:h.deal_pipeline)==null?void 0:ye.deal_type,Z=!!h,re=be=>be==="listing"?"Your Sale":be==="buy-side"?"Your Purchase":"Transaction",le=be=>be==="listing"?e.jsx(En,{className:"w-3.5 h-3.5"}):e.jsx(ep,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(tBt,{portal:l,linkedPortal:h,activePortal:v,activeTab:n,onTabChange:a,agentProfile:x,branding:b,updates:N,documents:T})}),e.jsxs("div",{className:"lg:hidden min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsx(FFt,{dealData:v==null?void 0:v.deal_pipeline,agentProfile:x,welcomeMessage:(v==null?void 0:v.welcome_message)||b.welcome_message,isWon:(ve=(ce=v==null?void 0:v.deal_pipeline)==null?void 0:ce.deal_pipeline_stages)==null?void 0:ve.is_won_stage,branding:b}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-6",children:[Z&&e.jsxs("div",{className:"flex gap-1 bg-slate-100 rounded-xl p-1",children:[e.jsxs("button",{onClick:()=>a("primary"),className:`flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all ${n==="primary"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[le(K),re(K)]}),e.jsxs("button",{onClick:()=>a("linked"),className:`flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all ${n==="linked"?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[le(X),re(X)]})]}),e.jsx(cBt,{portal:v,updates:N,documents:T,agentProfile:x}),e.jsxs("div",{className:"text-center pt-6 pb-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-slate-400",children:[e.jsx(Wu,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-xs",children:"Secure Client Portal"})]}),x&&e.jsxs("p",{className:"text-xs text-slate-400",children:["Managed by ",e.jsx("span",{className:"font-medium text-slate-500",children:x.name})]}),e.jsx("p",{className:"text-[10px] text-slate-300",children:"Powered by ReLevelUp"})]})]})]})]})}function cBt({portal:s,updates:t,documents:r,agentProfile:n}){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 h=Efe(c);d&&d.length>0&&(h=d.map((w,b)=>{var N,S;return{key:`custom-${b}`,label:w.label||((N=h[b])==null?void 0:N.label)||`Stage ${b+1}`,description:w.description||((S=h[b])==null?void 0:S.description)||"",video_url:w.video_url||void 0}}));const m=d&&d.length>0?Math.min(zde(l==null?void 0:l.name),h.length-1):zde(l==null?void 0:l.name),x=h[m],y=x==null?void 0:x.video_url,v=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[v&&e.jsx(Cst,{portalId:s.id,portalSlug:s.slug,ownerUserId:s.owner_user_id,rewardText:s.referral_reward_text,ctaHeadline:s.referral_cta_headline,agentName:n==null?void 0:n.name,clientName:s.client_name,reviewUrl:s.review_url,hubVideoUrl:s.homeowner_hub_video_url}),e.jsx(yst,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(vst,{journeyStages:h,currentIndex:m}),x&&e.jsx(bst,{currentStage:x,nextStepText:s.next_step_text,nextStepVideoUrl:y||s.next_step_video_url}),e.jsx(_st,{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}),r&&r.length>0&&e.jsx(wst,{documents:r}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(Sst,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(jst,{updates:t})]})}function Ist({slug:s}){const t=Ki(),r=s||t.slug,[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState("buying"),[T,A]=k.useState("");k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:I,isLoading:D,error:R}=mt({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:z,error:Q}=await V.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",r).eq("is_enabled",!0).maybeSingle();if(Q)throw Q;return z},enabled:!!r}),{data:$}=mt({queryKey:["portal-referral-agent",I==null?void 0:I.owner_user_id],queryFn:async()=>{const{data:z}=await V.from("profiles").select("id, name, avatar_url").eq("id",I.owner_user_id).single();return z},enabled:!!(I!=null&&I.owner_user_id)}),F=async z=>{if(z.preventDefault(),!I||!m.trim()){ue.error("Please enter your friend's name");return}if(!y.trim()&&!w.trim()){ue.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:Q}=await V.from("portal_referrals").insert({portal_id:I.id,owner_user_id:I.owner_user_id,referrer_name:o.trim()||I.client_name||null,referrer_email:d.trim()||null,friend_name:m.trim(),friend_email:y.trim()||null,friend_phone:w.trim()||null,friend_interest:N,friend_message:T.trim()||null});if(Q)throw Q;l(!0)}catch(Q){ue.error(Q.message||"Could not submit referral")}finally{a(!1)}};return D?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(Fs,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):R||!I||!I.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(Kn,{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 ",($==null?void 0:$.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:m})," personally and treat them like family."]}),e.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[e.jsx(ka,{className:"w-4 h-4"}),"Back to your portal"]})]})}):e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white px-4 pt-10 pb-12 overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),e.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[$!=null&&$.avatar_url?e.jsx("img",{src:$.avatar_url,alt:$.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(ii,{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(ii,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:I.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",($==null?void 0:$.name)||"your agent"," someone you trust."]}),I.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:I.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(he,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ne,{id:"friend_name",value:m,onChange:z=>x(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(he,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(Ne,{id:"friend_email",type:"email",value:y,onChange:z=>v(z.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(Ne,{id:"friend_phone",type:"tel",value:w,onChange:z=>b(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(he,{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:()=>S(z.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${N===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(he,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:T,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(he,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(Ne,{id:"referrer_name",value:o,onChange:z=>c(z.target.value),placeholder:I.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(Ne,{id:"referrer_email",type:"email",value:d,onChange:z=>h(z.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:n,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:[n?e.jsx(es,{className:"w-4 h-4 animate-spin"}):e.jsx(ii,{className:"w-4 h-4"}),n?"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 dBt(){const t=ec().pathname.slice(1).replace(/\/$/,"");if(k.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 r=t.match(/^([^/]+)\/refer$/);return r?e.jsx(Ist,{slug:r[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(Mst,{slug:t})}const Rje="levelup_affiliate_ref",uBt=30,hBt=()=>{const[s]=Ac();k.useEffect(()=>{const t=s.get("ref");if(t){const r={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(Rje,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",t)}},[s])},mBt=()=>{try{const s=localStorage.getItem(Rje);if(!s)return null;const t=JSON.parse(s),r=uBt*24*60*60*1e3;return Date.now()-t.timestamp>r?(localStorage.removeItem(Rje),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},$de="/assets/levelup-logo-header-_ZX7DvlA.png",fBt="/assets/scale-your-team-ku4MPatU.png";function pBt({open:s,onOpenChange:t}){return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ys,{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(Sa,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(gs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Hr,{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 lh={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}},xBt=[{icon:rf,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:on,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Jl,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ln,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:ii,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],gBt=[{icon:pr,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:jr,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Cn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:_h,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ca,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ro,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:ci,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:Ku,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],yBt=[{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."}],vBt=()=>{const{user:s,loading:t}=js(),r=br(),[n]=Ac();k.useEffect(()=>{const R=window.location.host==="listings.relevelup.com",$=window.location.pathname==="/";if(R&&$){r("/public/listings",{replace:!0});return}},[r]);const[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),A=(R,$=!1)=>{o({tier:R,skipTrial:$}),d(!0)};hBt(),k.useEffect(()=>{const R=window.location.host==="listings.relevelup.com",$=location.pathname.startsWith("/public/");!t&&s&&!R&&!$&&r("/dashboard")},[s,t,r,location.pathname]),k.useEffect(()=>{n.get("canceled")==="true"&&ue.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const I=async(R,$=!1)=>{if(!h){ue.error("Please enter your email address");return}if(!x.trim()){ue.error("Please enter your full name");return}N(!0),i(R+($?"_direct":""));const F=mBt();try{const{data:z,error:Q}=await V.functions.invoke("create-checkout",{body:{tier:R,email:h,name:x.trim(),couponCode:v.trim()||void 0,skipTrial:$,referralCode:F}});if(Q)throw Q;if(z!=null&&z.url)window.open(z.url,"_blank","noopener,noreferrer"),ue.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(z){console.error("Checkout error:",z),ue.error(z.message||"Failed to start checkout. Please try again.")}finally{N(!1),i(null),d(!1),o(null)}},D=()=>{l&&I(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:$de,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(G,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var R;return(R=document.getElementById("features"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(G,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(G,{onClick:()=>r("/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(G,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("free-trial"))==null?void 0:R.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(Ha,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(G,{size:"lg",variant:"outline",onClick:()=>{var R;return(R=document.getElementById("features"))==null?void 0:R.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(G,{size:"lg",variant:"outline",onClick:()=>{var R;return(R=document.getElementById("brokerage"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Sa,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(G,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Di,{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:xBt.map((R,$)=>e.jsxs(ke,{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(R.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Dt,{className:"text-xl font-sans",children:R.title})]}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:R.description})})]},$))})]})}),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(jr,{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:gBt.map((R,$)=>e.jsxs(ke,{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(R.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Dt,{className:"text-lg font-semibold text-white",children:R.title})]}),e.jsx(Pe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:R.description})})]},$))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(G,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.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(Ha,{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(Sa,{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((R,$)=>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(Kn,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:R})]},$))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(G,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(va,{className:"ml-2 w-5 h-5"})]}),e.jsxs(G,{size:"lg",variant:"outline",onClick:()=>T(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(on,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:fBt,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:yBt.map((R,$)=>e.jsx(ke,{className:"bg-muted/30 border-0",children:e.jsxs(Pe,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(F=>e.jsx(Xn,{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:['"',R.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:R.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R.role})]})]})},$))})]})}),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(G,{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(Ha,{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(ke,{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(Di,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Dt,{className:"text-xl font-sans",children:lh.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:lh.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:lh.individual_agent.period})]}),e.jsx(Nr,{className:"text-base mt-2",children:lh.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(fn,{className:"w-4 h-4"}),lh.individual_agent.trial]})]}),e.jsx(Pe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:lh.individual_agent.features.map((R,$)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Kn,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},$))})}),e.jsxs(sO,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(G,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("individual_agent"),children:"Start Free Trial"}),e.jsx(G,{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(ke,{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(Sa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-xl font-sans",children:lh.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:lh.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:lh.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:lh.brokerage_under_25.period})]}),e.jsx(Nr,{className:"text-base mt-2",children:lh.brokerage_under_25.description})]}),e.jsx(Pe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:lh.brokerage_under_25.features.map((R,$)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Kn,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},$))})}),e.jsx(sO,{className:"pt-4",children:e.jsx(G,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(ke,{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(Sa,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-xl font-sans",children:lh.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:lh.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:lh.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:lh.brokerage_over_25.period})]}),e.jsx(Nr,{className:"text-base mt-2",children:lh.brokerage_over_25.description})]}),e.jsx(Pe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:lh.brokerage_over_25.features.map((R,$)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Kn,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:R})]},$))})}),e.jsx(sO,{className:"pt-4",children:e.jsx(G,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_over_25"),children:"Get Started"})})]})]})]})}),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(G,{size:"lg",onClick:()=>{var R;return(R=document.getElementById("pricing"))==null?void 0:R.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(Ha,{className:"ml-2 w-5 h-5"})]}),e.jsx(G,{size:"lg",onClick:()=>r("/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:$de,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(pBt,{open:S,onOpenChange:T}),e.jsx(fs,{open:c,onOpenChange:d,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsx(gs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Hr,{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(he,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ne,{id:"dialog-name",type:"text",placeholder:"John Smith",value:x,onChange:R=>y(R.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(Ne,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:h,onChange:R=>m(R.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(Ne,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:v,onChange:R=>w(R.target.value),className:"mt-1"})]})]}),e.jsx(G,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:D,disabled:b,children:b?"Loading...":"Continue to Checkout"})]})})]})},o8e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(nl,{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:"})," We use your information to deliver the services you requested, send transactional and informational messages, and improve your experience."]}),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:"9. 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"})]})]})]})]})})]}),l8e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(nl,{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 Consulting Group, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including but not limited to account notifications, service updates, AI concierge replies, and customer support communications. Message frequency varies. Message and data rates may apply."}),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:["Your mobile phone number and opt-in data will not be shared with or sold to 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"})]})]})]})]})})]}),bBt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(nl,{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"})]})]})]})]})})]}),c8e="I agree to receive recurring SMS/MMS messages from LevelUp Consulting Group, including AI concierge replies, account notifications, service updates, and customer support communications. Message frequency varies. Message & data rates may apply. Reply STOP to opt out at any time, or HELP for assistance.",_Bt=qb({name:io().trim().min(1,"Name is required").max(200),phone:io().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:io().trim().email("Enter a valid email").max(320).optional().or(Vx(""))});function wBt(){const[s,t]=k.useState(""),[r,n]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState(!1),x=async y=>{var b;if(y.preventDefault(),!l){ue.error("Please check the consent box to opt in.");return}const v=_Bt.safeParse({name:s,phone:r,email:a});if(!v.success){ue.error(((b=v.error.issues[0])==null?void 0:b.message)??"Please check your inputs.");return}d(!0);const{error:w}=await V.from("sms_opt_in_consents").insert({name:v.data.name,phone:v.data.phone,email:v.data.email||null,consent_text:c8e,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),w){ue.error("Something went wrong. Please try again.");return}m(!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(nl,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS messages from LevelUp Consulting Group's AI concierge. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://tile-portal.lovable.app/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(xi,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp Consulting Group — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Join the LevelUp SMS Concierge. Text our AI assistant from your phone to get help with social posts, listing info, reminders, and more."})]}),h?e.jsxs(ke,{className:"p-8 text-center",children:[e.jsx(In,{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:["Text our concierge at"," ",e.jsx("span",{className:"font-semibold text-foreground",children:"+1 (888) 593-6381"})," ","from your mobile to get started. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(ke,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:x,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Full Name *"}),e.jsx(Ne,{id:"name",value:s,onChange:y=>t(y.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(Ne,{id:"phone",type:"tel",value:r,onChange:y=>n(y.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email (optional)"}),e.jsx(Ne,{id:"email",type:"email",value:a,onChange:y=>i(y.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Si,{id:"consent",checked:l,onCheckedChange:y=>o(y===!0),className:"mt-0.5"}),e.jsx(he,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:c8e})]})}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["By submitting, you agree to our"," ",e.jsx(Yn,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Yn,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," AI concierge replies, account notifications, 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:"Your mobile phone number and opt-in data will not be shared with or sold to third parties for marketing or promotional purposes."})]}),e.jsx(G,{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(Ey,{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 Consulting Group · Questions? Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})})]})]})}const jBt=qb({email:io().email("Invalid email address"),password:io().min(6,"Password must be at least 6 characters")}),NBt=()=>{const{signIn:s,user:t}=js(),r=br(),[n,a]=k.useState(!1),[i,l]=k.useState({}),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState(!1);k.useEffect(()=>{if(t){const w=sessionStorage.getItem("redirectAfterLogin")||"/dashboard";sessionStorage.removeItem("redirectAfterLogin"),r(w)}},[t,r]);const y=async w=>{w.preventDefault(),l({}),a(!0);const b=new FormData(w.currentTarget),N=b.get("email"),S=b.get("password");try{jBt.parse({email:N,password:S}),await s(N,S)}catch(T){if(T instanceof wv){const A={};T.errors.forEach(I=>{I.path[0]&&(A[I.path[0]]=I.message)}),l(A)}}finally{a(!1)}},v=async()=>{if(!o){ue.error("Please enter your email address");return}h(!0);try{const{error:w}=await V.functions.invoke("send-password-reset",{body:{email:o,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(w)throw w;ue.success("Password reset email sent! Check your inbox."),x(!1),c("")}catch(w){ue.error(w.message||"Failed to send reset email")}finally{h(!1)}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:e.jsxs("div",{className:"absolute inset-0 opacity-30",children:[e.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),e.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[e.jsx("header",{className:"p-6",children:e.jsxs(Yn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Home"]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:HCe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ke,{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(Dt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Nr,{className:"text-gray-600",children:"Sign in to access your dashboard"})]}),e.jsx(Pe,{children:e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(Ne,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),i.email&&e.jsx("p",{className:"text-sm text-red-600",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(Ne,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),i.password&&e.jsx("p",{className:"text-sm text-red-600",children:i.password})]}),e.jsx(G,{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:n,children:n?"Signing in...":"Sign In"}),e.jsxs(fs,{open:m,onOpenChange:x,children:[e.jsx(vi,{asChild:!0,children:e.jsx(G,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(ms,{className:"bg-white",children:[e.jsxs(ys,{children:[e.jsx(gs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Hr,{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(he,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(Ne,{id:"reset-email",type:"email",placeholder:"your@email.com",value:o,onChange:w=>c(w.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(G,{onClick:v,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:d,children:d?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(Yn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},kBt=()=>{const[s]=Ac(),t=s.get("tier"),r=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(ke,{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(di,{className:"w-10 h-10 text-green-500"})}),e.jsx(Dt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Nr,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Pe,{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."})]}),r?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."})})]})]})})},Lst=s=>{const[t,r]=k.useState(null),[n,a]=k.useState(!0);return k.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await V.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=V.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);r(`${c.publicUrl}?t=${Date.now()}`)}else r(null)}catch(o){console.error("Error fetching avatar:",o),r(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:n,refreshAvatar:async()=>{if(s)try{const{data:l}=await V.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=V.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);r(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},Pst=async s=>{const t=new Map;return await Promise.all(s.map(async r=>{try{const{data:n}=await V.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:a}=V.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);t.set(r,a.publicUrl)}}catch{}})),t},SBt=s=>{const[t,r]=k.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return k.useEffect(()=>{if(!s){r(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await V.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),r(m=>({...m,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 m=new Date().getTime(),x=new Date(d).getTime(),y=Math.ceil((x-m)/(1e3*60*60*24)),v=y<=0;r({isTrial:!0,isExpired:v,expiresAt:d,daysLeft:v?0:y,loading:!1})}else r({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),r(i=>({...i,loading:!1}))}})()},[s]),t},Dst=()=>{const{data:s,isLoading:t}=mt({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:a}=await V.from("feature_flags").select("*");if(a)throw a;return n}}),r=n=>{if(!s)return!1;const a=s.find(i=>i.key===n);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:r,isAgentOSEnabled:r("agent_os_enabled"),isInnerCircleEnabled:r("innercircle_enabled"),isMarketplaceEnabled:r("marketplace")}},d8e="community_last_seen_post_at";function CBt(){const{user:s}=js(),t=ec(),[r,n]=k.useState(0),[a,i]=k.useState(null);k.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${d8e}_${s.id}`);i(o)},[s]),k.useEffect(()=>{if(!s)return;(async()=>{let c=V.from("community_posts").select("id",{count:"exact",head:!0});a&&(c=c.gt("created_at",a)),await V.from("profiles").select("brokerage_id").eq("id",s.id).single();const{count:d,error:h}=await c;!h&&d!==null&&n(d)})()},[s,a]),k.useEffect(()=>{if(!s)return;const o=V.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 h=t.pathname==="/community";h||n(w=>w+1);const{data:m}=await V.from("profiles").select("name").eq("id",d.user_id).single(),x=(m==null?void 0:m.name)||"Someone",y=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),v=y.length>50?y.substring(0,50)+"...":y;h||ue("New Community Post",{description:`${x}: ${v}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{V.removeChannel(o)}},[s,t.pathname]);const l=k.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${d8e}_${s.id}`,o),i(o),n(0)},[s]);return k.useEffect(()=>{t.pathname==="/community"&&r>0&&l()},[t.pathname,r,l]),{unreadCount:r,markAsRead:l}}function TBt(){const{isAdmin:s}=js(),{data:t=0}=mt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await V.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(n)throw n;return r||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}var Afe="Collapsible",[EBt,PUs]=pd(Afe),[ABt,q4e]=EBt(Afe),Rst=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,open:n,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Sh({prop:n,defaultProp:a??!1,onChange:l,caller:Afe});return e.jsx(ABt,{scope:r,disabled:i,contentId:Yu(),open:c,onOpenToggle:k.useCallback(()=>d(h=>!h),[d]),children:e.jsx(wn.div,{"data-state":H4e(c),"data-disabled":i?"":void 0,...o,ref:t})})});Rst.displayName=Afe;var Ost="CollapsibleTrigger",Fst=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,...n}=s,a=q4e(Ost,r);return e.jsx(wn.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":H4e(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...n,ref:t,onClick:Vr(s.onClick,a.onOpenToggle)})});Fst.displayName=Ost;var V4e="CollapsibleContent",Bst=k.forwardRef((s,t)=>{const{forceMount:r,...n}=s,a=q4e(V4e,s.__scopeCollapsible);return e.jsx(ru,{present:r||a.open,children:({present:i})=>e.jsx(MBt,{...n,ref:t,present:i})})});Bst.displayName=V4e;var MBt=k.forwardRef((s,t)=>{const{__scopeCollapsible:r,present:n,children:a,...i}=s,l=q4e(V4e,r),[o,c]=k.useState(n),d=k.useRef(null),h=Ga(t,d),m=k.useRef(0),x=m.current,y=k.useRef(0),v=y.current,w=l.open||o,b=k.useRef(w),N=k.useRef(void 0);return k.useEffect(()=>{const S=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(S)},[]),Dd(()=>{const S=d.current;if(S){N.current=N.current||{transitionDuration:S.style.transitionDuration,animationName:S.style.animationName},S.style.transitionDuration="0s",S.style.animationName="none";const T=S.getBoundingClientRect();m.current=T.height,y.current=T.width,b.current||(S.style.transitionDuration=N.current.transitionDuration,S.style.animationName=N.current.animationName),c(n)}},[l.open,n]),e.jsx(wn.div,{"data-state":H4e(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!w,...i,ref:h,style:{"--radix-collapsible-content-height":x?`${x}px`:void 0,"--radix-collapsible-content-width":v?`${v}px`:void 0,...s.style},children:w&&a})});function H4e(s){return s?"open":"closed"}var IBt=Rst;const Gp=IBt,Wp=Fst,Kp=Bst,LBt="/assets/levelup-logo-Eif24dqY.png",PBt="/assets/levelup-logo-icon-C-7iromj.png",DBt="/assets/levelup-logo-mobile-B9skSjUG.png";var cB=s=>s.type==="checkbox",n4=s=>s instanceof Date,sf=s=>s==null;const zst=s=>typeof s=="object";var su=s=>!sf(s)&&!Array.isArray(s)&&zst(s)&&!n4(s),$st=s=>su(s)&&s.target?cB(s.target)?s.target.checked:s.target.value:s,RBt=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,Ust=(s,t)=>s.has(RBt(t)),OBt=s=>{const t=s.constructor&&s.constructor.prototype;return su(t)&&t.hasOwnProperty("isPrototypeOf")},G4e=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Iu(s){let t;const r=Array.isArray(s),n=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(G4e&&(s instanceof Blob||n))&&(r||su(s)))if(t=r?[]:{},!r&&!OBt(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=Iu(s[a]));else return s;return t}var Mfe=s=>/^\w*$/.test(s),Gd=s=>s===void 0,W4e=s=>Array.isArray(s)?s.filter(Boolean):[],K4e=s=>W4e(s.replace(/["|']|\]/g,"").split(/\.|\[/)),Wn=(s,t,r)=>{if(!t||!su(s))return r;const n=(Mfe(t)?[t]:K4e(t)).reduce((a,i)=>sf(a)?a:a[i],s);return Gd(n)||n===s?Gd(s[t])?r:s[t]:n},Ip=s=>typeof s=="boolean",Nl=(s,t,r)=>{let n=-1;const a=Mfe(t)?[t]:K4e(t),i=a.length,l=i-1;for(;++nwt.useContext(Y4e),FBt=s=>{const{children:t,...r}=s;return wt.createElement(Y4e.Provider,{value:r},t)};var qst=(s,t,r,n=!0)=>{const a={defaultValues:t._defaultValues};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==py.all&&(t._proxyFormState[l]=!n||py.all),r&&(r[l]=!0),s[l]}});return a};const Z4e=typeof window<"u"?wt.useLayoutEffect:wt.useEffect;function BBt(s){const t=Ife(),{control:r=t.control,disabled:n,name:a,exact:i}=s||{},[l,o]=wt.useState(r._formState),c=wt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return Z4e(()=>r._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!n&&o({...r._formState,...d})}}),[a,n,i]),wt.useEffect(()=>{c.current.isValid&&r._setValid(!0)},[r]),wt.useMemo(()=>qst(l,r,c.current,!1),[l,r])}var G0=s=>typeof s=="string",Vst=(s,t,r,n,a)=>G0(s)?(n&&t.watch.add(s),Wn(r,s,a)):Array.isArray(s)?s.map(i=>(n&&t.watch.add(i),Wn(r,i))):(n&&(t.watchAll=!0),r),Oje=s=>sf(s)||!zst(s);function J1(s,t,r=new WeakSet){if(Oje(s)||Oje(t))return s===t;if(n4(s)&&n4(t))return s.getTime()===t.getTime();const n=Object.keys(s),a=Object.keys(t);if(n.length!==a.length)return!1;if(r.has(s)||r.has(t))return!0;r.add(s),r.add(t);for(const i of n){const l=s[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(n4(l)&&n4(o)||su(l)&&su(o)||Array.isArray(l)&&Array.isArray(o)?!J1(l,o,r):l!==o)return!1}}return!0}function zBt(s){const t=Ife(),{control:r=t.control,name:n,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=wt.useRef(a),d=wt.useRef(o),h=wt.useRef(void 0);d.current=o;const m=wt.useMemo(()=>r._getWatch(n,c.current),[r,n]),[x,y]=wt.useState(d.current?d.current(m):m);return Z4e(()=>r._subscribe({name:n,formState:{values:!0},exact:l,callback:v=>{if(!i){const w=Vst(n,r._names,v.values||r._formValues,!1,c.current);if(d.current){const b=d.current(w);J1(b,h.current)||(y(b),h.current=b)}else y(w)}}}),[r,i,n,l]),wt.useEffect(()=>r._removeUnmounted()),x}function $Bt(s){const t=Ife(),{name:r,disabled:n,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=Ust(a._names.array,r),c=wt.useMemo(()=>Wn(a._formValues,r,Wn(a._defaultValues,r,l)),[a,r,l]),d=zBt({control:a,name:r,defaultValue:c,exact:!0}),h=BBt({control:a,name:r,exact:!0}),m=wt.useRef(s),x=wt.useRef(a.register(r,{...s.rules,value:d,...Ip(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const y=wt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Wn(h.errors,r)},isDirty:{enumerable:!0,get:()=>!!Wn(h.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!Wn(h.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!Wn(h.validatingFields,r)},error:{enumerable:!0,get:()=>Wn(h.errors,r)}}),[h,r]),v=wt.useCallback(S=>x.current.onChange({target:{value:$st(S),name:r},type:Ude.CHANGE}),[r]),w=wt.useCallback(()=>x.current.onBlur({target:{value:Wn(a._formValues,r),name:r},type:Ude.BLUR}),[r,a._formValues]),b=wt.useCallback(S=>{const T=Wn(a._fields,r);T&&S&&(T._f.ref={focus:()=>S.focus&&S.focus(),select:()=>S.select&&S.select(),setCustomValidity:A=>S.setCustomValidity(A),reportValidity:()=>S.reportValidity()})},[a._fields,r]),N=wt.useMemo(()=>({name:r,value:d,...Ip(n)||h.disabled?{disabled:h.disabled||n}:{},onChange:v,onBlur:w,ref:b}),[r,n,h.disabled,v,w,b,d]);return wt.useEffect(()=>{const S=a._options.shouldUnregister||i;a.register(r,{...m.current.rules,...Ip(m.current.disabled)?{disabled:m.current.disabled}:{}});const T=(A,I)=>{const D=Wn(a._fields,A);D&&D._f&&(D._f.mount=I)};if(T(r,!0),S){const A=Iu(Wn(a._options.defaultValues,r));Nl(a._defaultValues,r,A),Gd(Wn(a._formValues,r))&&Nl(a._formValues,r,A)}return!o&&a.register(r),()=>{(o?S&&!a._state.action:S)?a.unregister(r):T(r,!1)}},[r,a,o,i]),wt.useEffect(()=>{a._setDisabledField({disabled:n,name:r})},[n,r,a]),wt.useMemo(()=>({field:N,formState:h,fieldState:y}),[N,h,y])}const UBt=s=>s.render($Bt(s));var Hst=(s,t,r,n,a)=>t?{...r[s],types:{...r[s]&&r[s].types?r[s].types:{},[n]:a||!0}}:{},dO=s=>Array.isArray(s)?s:[s],u8e=()=>{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=[]}}},Of=s=>su(s)&&!Object.keys(s).length,X4e=s=>s.type==="file",xy=s=>typeof s=="function",qde=s=>{if(!G4e)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Gst=s=>s.type==="select-multiple",Q4e=s=>s.type==="radio",qBt=s=>Q4e(s)||cB(s),Ove=s=>qde(s)&&s.isConnected;function VBt(s,t){const r=t.slice(0,-1).length;let n=0;for(;n{for(const t in s)if(xy(s[t]))return!0;return!1};function Vde(s,t={}){const r=Array.isArray(s);if(su(s)||r)for(const n in s)Array.isArray(s[n])||su(s[n])&&!Wst(s[n])?(t[n]=Array.isArray(s[n])?[]:{},Vde(s[n],t[n])):sf(s[n])||(t[n]=!0);return t}function Kst(s,t,r){const n=Array.isArray(s);if(su(s)||n)for(const a in s)Array.isArray(s[a])||su(s[a])&&!Wst(s[a])?Gd(t)||Oje(r[a])?r[a]=Array.isArray(s[a])?Vde(s[a],[]):{...Vde(s[a])}:Kst(s[a],sf(t)?{}:t[a],r[a]):r[a]=!J1(s[a],t[a]);return r}var Q6=(s,t)=>Kst(s,t,Vde(t));const h8e={value:!1,isValid:!1},m8e={value:!0,isValid:!0};var Yst=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!Gd(s[0].attributes.value)?Gd(s[0].value)||s[0].value===""?m8e:{value:s[0].value,isValid:!0}:m8e:h8e}return h8e},Zst=(s,{valueAsNumber:t,valueAsDate:r,setValueAs:n})=>Gd(s)?s:t?s===""?NaN:s&&+s:r&&G0(s)?new Date(s):n?n(s):s;const f8e={isValid:!1,value:null};var Xst=s=>Array.isArray(s)?s.reduce((t,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:t,f8e):f8e;function p8e(s){const t=s.ref;return X4e(t)?t.files:Q4e(t)?Xst(s.refs).value:Gst(t)?[...t.selectedOptions].map(({value:r})=>r):cB(t)?Yst(s.refs).value:Zst(Gd(t.value)?s.ref.value:t.value,s)}var GBt=(s,t,r,n)=>{const a={};for(const i of s){const l=Wn(t,i);l&&Nl(a,i,l._f)}return{criteriaMode:r,names:[...s],fields:a,shouldUseNativeValidation:n}},Hde=s=>s instanceof RegExp,J6=s=>Gd(s)?s:Hde(s)?s.source:su(s)?Hde(s.value)?s.value.source:s.value:s,x8e=s=>({isOnSubmit:!s||s===py.onSubmit,isOnBlur:s===py.onBlur,isOnChange:s===py.onChange,isOnAll:s===py.all,isOnTouch:s===py.onTouched});const g8e="AsyncFunction";var WBt=s=>!!s&&!!s.validate&&!!(xy(s.validate)&&s.validate.constructor.name===g8e||su(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===g8e)),KBt=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),y8e=(s,t,r)=>!r&&(t.watchAll||t.watch.has(s)||[...t.watch].some(n=>s.startsWith(n)&&/^\.\w+/.test(s.slice(n.length))));const uO=(s,t,r,n)=>{for(const a of r||Object.keys(s)){const i=Wn(s,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!n)return!0;if(l.ref&&t(l.ref,l.name)&&!n)return!0;if(uO(o,t))break}else if(su(o)&&uO(o,t))break}}};function v8e(s,t,r){const n=Wn(s,r);if(n||Mfe(r))return{error:n,name:r};const a=r.split(".");for(;a.length;){const i=a.join("."),l=Wn(t,i),o=Wn(s,i);if(l&&!Array.isArray(l)&&r!==i)return{name:r};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:r}}var YBt=(s,t,r,n)=>{r(s);const{name:a,...i}=s;return Of(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!n||py.all))},ZBt=(s,t,r)=>!s||!t||s===t||dO(s).some(n=>n&&(r?n===t:n.startsWith(t)||t.startsWith(n))),XBt=(s,t,r,n,a)=>a.isOnAll?!1:!r&&a.isOnTouch?!(t||s):(r?n.isOnBlur:a.isOnBlur)?!s:(r?n.isOnChange:a.isOnChange)?s:!0,QBt=(s,t)=>!W4e(Wn(s,t)).length&&du(s,t),JBt=(s,t,r)=>{const n=dO(Wn(s,r));return Nl(n,"root",t[r]),Nl(s,r,n),s},fce=s=>G0(s);function b8e(s,t,r="validate"){if(fce(s)||Array.isArray(s)&&s.every(fce)||Ip(s)&&!s)return{type:r,message:fce(s)?s:"",ref:t}}var YT=s=>su(s)&&!Hde(s)?s:{value:s,message:""},_8e=async(s,t,r,n,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:h,min:m,max:x,pattern:y,validate:v,name:w,valueAsNumber:b,mount:N}=s._f,S=Wn(r,w);if(!N||t.has(w))return{};const T=o?o[0]:l,A=K=>{a&&T.reportValidity&&(T.setCustomValidity(Ip(K)?"":K||""),T.reportValidity())},I={},D=Q4e(l),R=cB(l),$=D||R,F=(b||X4e(l))&&Gd(l.value)&&Gd(S)||qde(l)&&l.value===""||S===""||Array.isArray(S)&&!S.length,z=Hst.bind(null,w,n,I),Q=(K,X,Z,re=C1.maxLength,le=C1.minLength)=>{const oe=K?X:Z;I[w]={type:K?re:le,message:oe,ref:l,...z(K?re:le,oe)}};if(i?!Array.isArray(S)||!S.length:c&&(!$&&(F||sf(S))||Ip(S)&&!S||R&&!Yst(o).isValid||D&&!Xst(o).isValid)){const{value:K,message:X}=fce(c)?{value:!!c,message:c}:YT(c);if(K&&(I[w]={type:C1.required,message:X,ref:T,...z(C1.required,X)},!n))return A(X),I}if(!F&&(!sf(m)||!sf(x))){let K,X;const Z=YT(x),re=YT(m);if(!sf(S)&&!isNaN(S)){const le=l.valueAsNumber||S&&+S;sf(Z.value)||(K=le>Z.value),sf(re.value)||(X=lenew Date(new Date().toDateString()+" "+ye),ne=l.type=="time",ie=l.type=="week";G0(Z.value)&&S&&(K=ne?oe(S)>oe(Z.value):ie?S>Z.value:le>new Date(Z.value)),G0(re.value)&&S&&(X=ne?oe(S)+K.value,re=!sf(X.value)&&S.length<+X.value;if((Z||re)&&(Q(Z,K.message,X.message),!n))return A(I[w].message),I}if(y&&!F&&G0(S)){const{value:K,message:X}=YT(y);if(Hde(K)&&!S.match(K)&&(I[w]={type:C1.pattern,message:X,ref:l,...z(C1.pattern,X)},!n))return A(X),I}if(v){if(xy(v)){const K=await v(S,r),X=b8e(K,T);if(X&&(I[w]={...X,...z(C1.validate,X.message)},!n))return A(X.message),I}else if(su(v)){let K={};for(const X in v){if(!Of(K)&&!n)break;const Z=b8e(await v[X](S,r),T,X);Z&&(K={...Z,...z(X,Z.message)},A(Z.message),n&&(I[w]=K))}if(!Of(K)&&(I[w]={ref:T,...K},!n))return I}}return A(!0),I};const ezt={mode:py.onSubmit,reValidateMode:py.onChange,shouldFocusError:!0};function tzt(s={}){let t={...ezt,...s},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:xy(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},n={},a=su(t.defaultValues)||su(t.values)?Iu(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Iu(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 h={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let m={...h};const x={array:u8e(),state:u8e()},y=t.criteriaMode===py.all,v=Re=>tt=>{clearTimeout(d),d=setTimeout(Re,tt)},w=async Re=>{if(!t.disabled&&(h.isValid||m.isValid||Re)){const tt=t.resolver?Of((await R()).errors):await F(n,!0);tt!==r.isValid&&x.state.next({isValid:tt})}},b=(Re,tt)=>{!t.disabled&&(h.isValidating||h.validatingFields||m.isValidating||m.validatingFields)&&((Re||Array.from(o.mount)).forEach(Ke=>{Ke&&(tt?Nl(r.validatingFields,Ke,tt):du(r.validatingFields,Ke))}),x.state.next({validatingFields:r.validatingFields,isValidating:!Of(r.validatingFields)}))},N=(Re,tt=[],Ke,Ze,lt=!0,xt=!0)=>{if(Ze&&Ke&&!t.disabled){if(l.action=!0,xt&&Array.isArray(Wn(n,Re))){const Xe=Ke(Wn(n,Re),Ze.argA,Ze.argB);lt&&Nl(n,Re,Xe)}if(xt&&Array.isArray(Wn(r.errors,Re))){const Xe=Ke(Wn(r.errors,Re),Ze.argA,Ze.argB);lt&&Nl(r.errors,Re,Xe),QBt(r.errors,Re)}if((h.touchedFields||m.touchedFields)&&xt&&Array.isArray(Wn(r.touchedFields,Re))){const Xe=Ke(Wn(r.touchedFields,Re),Ze.argA,Ze.argB);lt&&Nl(r.touchedFields,Re,Xe)}(h.dirtyFields||m.dirtyFields)&&(r.dirtyFields=Q6(a,i)),x.state.next({name:Re,isDirty:Q(Re,tt),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Nl(i,Re,tt)},S=(Re,tt)=>{Nl(r.errors,Re,tt),x.state.next({errors:r.errors})},T=Re=>{r.errors=Re,x.state.next({errors:r.errors,isValid:!1})},A=(Re,tt,Ke,Ze)=>{const lt=Wn(n,Re);if(lt){const xt=Wn(i,Re,Gd(Ke)?Wn(a,Re):Ke);Gd(xt)||Ze&&Ze.defaultChecked||tt?Nl(i,Re,tt?xt:p8e(lt._f)):Z(Re,xt),l.mount&&w()}},I=(Re,tt,Ke,Ze,lt)=>{let xt=!1,Xe=!1;const Je={name:Re};if(!t.disabled){if(!Ke||Ze){(h.isDirty||m.isDirty)&&(Xe=r.isDirty,r.isDirty=Je.isDirty=Q(),xt=Xe!==Je.isDirty);const jt=J1(Wn(a,Re),tt);Xe=!!Wn(r.dirtyFields,Re),jt?du(r.dirtyFields,Re):Nl(r.dirtyFields,Re,!0),Je.dirtyFields=r.dirtyFields,xt=xt||(h.dirtyFields||m.dirtyFields)&&Xe!==!jt}if(Ke){const jt=Wn(r.touchedFields,Re);jt||(Nl(r.touchedFields,Re,Ke),Je.touchedFields=r.touchedFields,xt=xt||(h.touchedFields||m.touchedFields)&&jt!==Ke)}xt&<&&x.state.next(Je)}return xt?Je:{}},D=(Re,tt,Ke,Ze)=>{const lt=Wn(r.errors,Re),xt=(h.isValid||m.isValid)&&Ip(tt)&&r.isValid!==tt;if(t.delayError&&Ke?(c=v(()=>S(Re,Ke)),c(t.delayError)):(clearTimeout(d),c=null,Ke?Nl(r.errors,Re,Ke):du(r.errors,Re)),(Ke?!J1(lt,Ke):lt)||!Of(Ze)||xt){const Xe={...Ze,...xt&&Ip(tt)?{isValid:tt}:{},errors:r.errors,name:Re};r={...r,...Xe},x.state.next(Xe)}},R=async Re=>{b(Re,!0);const tt=await t.resolver(i,t.context,GBt(Re||o.mount,n,t.criteriaMode,t.shouldUseNativeValidation));return b(Re),tt},$=async Re=>{const{errors:tt}=await R(Re);if(Re)for(const Ke of Re){const Ze=Wn(tt,Ke);Ze?Nl(r.errors,Ke,Ze):du(r.errors,Ke)}else r.errors=tt;return tt},F=async(Re,tt,Ke={valid:!0})=>{for(const Ze in Re){const lt=Re[Ze];if(lt){const{_f:xt,...Xe}=lt;if(xt){const Je=o.array.has(xt.name),jt=lt._f&&WBt(lt._f);jt&&h.validatingFields&&b([Ze],!0);const ns=await _8e(lt,o.disabled,i,y,t.shouldUseNativeValidation&&!tt,Je);if(jt&&h.validatingFields&&b([Ze]),ns[xt.name]&&(Ke.valid=!1,tt))break;!tt&&(Wn(ns,xt.name)?Je?JBt(r.errors,ns,xt.name):Nl(r.errors,xt.name,ns[xt.name]):du(r.errors,xt.name))}!Of(Xe)&&await F(Xe,tt,Ke)}}return Ke.valid},z=()=>{for(const Re of o.unMount){const tt=Wn(n,Re);tt&&(tt._f.refs?tt._f.refs.every(Ke=>!Ove(Ke)):!Ove(tt._f.ref))&&Ae(Re)}o.unMount=new Set},Q=(Re,tt)=>!t.disabled&&(Re&&tt&&Nl(i,Re,tt),!J1(ye(),a)),K=(Re,tt,Ke)=>Vst(Re,o,{...l.mount?i:Gd(tt)?a:G0(Re)?{[Re]:tt}:tt},Ke,tt),X=Re=>W4e(Wn(l.mount?i:a,Re,t.shouldUnregister?Wn(a,Re,[]):[])),Z=(Re,tt,Ke={})=>{const Ze=Wn(n,Re);let lt=tt;if(Ze){const xt=Ze._f;xt&&(!xt.disabled&&Nl(i,Re,Zst(tt,xt)),lt=qde(xt.ref)&&sf(tt)?"":tt,Gst(xt.ref)?[...xt.ref.options].forEach(Xe=>Xe.selected=lt.includes(Xe.value)):xt.refs?cB(xt.ref)?xt.refs.forEach(Xe=>{(!Xe.defaultChecked||!Xe.disabled)&&(Array.isArray(lt)?Xe.checked=!!lt.find(Je=>Je===Xe.value):Xe.checked=lt===Xe.value||!!lt)}):xt.refs.forEach(Xe=>Xe.checked=Xe.value===lt):X4e(xt.ref)?xt.ref.value="":(xt.ref.value=lt,xt.ref.type||x.state.next({name:Re,values:Iu(i)})))}(Ke.shouldDirty||Ke.shouldTouch)&&I(Re,lt,Ke.shouldTouch,Ke.shouldDirty,!0),Ke.shouldValidate&&ie(Re)},re=(Re,tt,Ke)=>{for(const Ze in tt){if(!tt.hasOwnProperty(Ze))return;const lt=tt[Ze],xt=Re+"."+Ze,Xe=Wn(n,xt);(o.array.has(Re)||su(lt)||Xe&&!Xe._f)&&!n4(lt)?re(xt,lt,Ke):Z(xt,lt,Ke)}},le=(Re,tt,Ke={})=>{const Ze=Wn(n,Re),lt=o.array.has(Re),xt=Iu(tt);Nl(i,Re,xt),lt?(x.array.next({name:Re,values:Iu(i)}),(h.isDirty||h.dirtyFields||m.isDirty||m.dirtyFields)&&Ke.shouldDirty&&x.state.next({name:Re,dirtyFields:Q6(a,i),isDirty:Q(Re,xt)})):Ze&&!Ze._f&&!sf(xt)?re(Re,xt,Ke):Z(Re,xt,Ke),y8e(Re,o)&&x.state.next({...r,name:Re}),x.state.next({name:l.mount?Re:void 0,values:Iu(i)})},oe=async Re=>{l.mount=!0;const tt=Re.target;let Ke=tt.name,Ze=!0;const lt=Wn(n,Ke),xt=jt=>{Ze=Number.isNaN(jt)||n4(jt)&&isNaN(jt.getTime())||J1(jt,Wn(i,Ke,jt))},Xe=x8e(t.mode),Je=x8e(t.reValidateMode);if(lt){let jt,ns;const Ns=tt.type?p8e(lt._f):$st(Re),Ys=Re.type===Ude.BLUR||Re.type===Ude.FOCUS_OUT,rs=!KBt(lt._f)&&!t.resolver&&!Wn(r.errors,Ke)&&!lt._f.deps||XBt(Ys,Wn(r.touchedFields,Ke),r.isSubmitted,Je,Xe),bt=y8e(Ke,o,Ys);Nl(i,Ke,Ns),Ys?(lt._f.onBlur&<._f.onBlur(Re),c&&c(0)):lt._f.onChange&<._f.onChange(Re);const cs=I(Ke,Ns,Ys),yt=!Of(cs)||bt;if(!Ys&&x.state.next({name:Ke,type:Re.type,values:Iu(i)}),rs)return(h.isValid||m.isValid)&&(t.mode==="onBlur"?Ys&&w():Ys||w()),yt&&x.state.next({name:Ke,...bt?{}:cs});if(!Ys&&bt&&x.state.next({...r}),t.resolver){const{errors:is}=await R([Ke]);if(xt(Ns),Ze){const Bs=v8e(r.errors,n,Ke),ps=v8e(is,n,Bs.name||Ke);jt=ps.error,Ke=ps.name,ns=Of(is)}}else b([Ke],!0),jt=(await _8e(lt,o.disabled,i,y,t.shouldUseNativeValidation))[Ke],b([Ke]),xt(Ns),Ze&&(jt?ns=!1:(h.isValid||m.isValid)&&(ns=await F(n,!0)));Ze&&(lt._f.deps&&ie(lt._f.deps),D(Ke,ns,jt,cs))}},ne=(Re,tt)=>{if(Wn(r.errors,tt)&&Re.focus)return Re.focus(),1},ie=async(Re,tt={})=>{let Ke,Ze;const lt=dO(Re);if(t.resolver){const xt=await $(Gd(Re)?Re:lt);Ke=Of(xt),Ze=Re?!lt.some(Xe=>Wn(xt,Xe)):Ke}else Re?(Ze=(await Promise.all(lt.map(async xt=>{const Xe=Wn(n,xt);return await F(Xe&&Xe._f?{[xt]:Xe}:Xe)}))).every(Boolean),!(!Ze&&!r.isValid)&&w()):Ze=Ke=await F(n);return x.state.next({...!G0(Re)||(h.isValid||m.isValid)&&Ke!==r.isValid?{}:{name:Re},...t.resolver||!Re?{isValid:Ke}:{},errors:r.errors}),tt.shouldFocus&&!Ze&&uO(n,ne,Re?lt:o.mount),Ze},ye=Re=>{const tt={...l.mount?i:a};return Gd(Re)?tt:G0(Re)?Wn(tt,Re):Re.map(Ke=>Wn(tt,Ke))},ce=(Re,tt)=>({invalid:!!Wn((tt||r).errors,Re),isDirty:!!Wn((tt||r).dirtyFields,Re),error:Wn((tt||r).errors,Re),isValidating:!!Wn(r.validatingFields,Re),isTouched:!!Wn((tt||r).touchedFields,Re)}),ve=Re=>{Re&&dO(Re).forEach(tt=>du(r.errors,tt)),x.state.next({errors:Re?r.errors:{}})},be=(Re,tt,Ke)=>{const Ze=(Wn(n,Re,{_f:{}})._f||{}).ref,lt=Wn(r.errors,Re)||{},{ref:xt,message:Xe,type:Je,...jt}=lt;Nl(r.errors,Re,{...jt,...tt,ref:Ze}),x.state.next({name:Re,errors:r.errors,isValid:!1}),Ke&&Ke.shouldFocus&&Ze&&Ze.focus&&Ze.focus()},Ue=(Re,tt)=>xy(Re)?x.state.subscribe({next:Ke=>"values"in Ke&&Re(K(void 0,tt),Ke)}):K(Re,tt,!0),Be=Re=>x.state.subscribe({next:tt=>{ZBt(Re.name,tt.name,Re.exact)&&YBt(tt,Re.formState||h,Ye,Re.reRenderRoot)&&Re.callback({values:{...i},...r,...tt,defaultValues:a})}}).unsubscribe,De=Re=>(l.mount=!0,m={...m,...Re.formState},Be({...Re,formState:m})),Ae=(Re,tt={})=>{for(const Ke of Re?dO(Re):o.mount)o.mount.delete(Ke),o.array.delete(Ke),tt.keepValue||(du(n,Ke),du(i,Ke)),!tt.keepError&&du(r.errors,Ke),!tt.keepDirty&&du(r.dirtyFields,Ke),!tt.keepTouched&&du(r.touchedFields,Ke),!tt.keepIsValidating&&du(r.validatingFields,Ke),!t.shouldUnregister&&!tt.keepDefaultValue&&du(a,Ke);x.state.next({values:Iu(i)}),x.state.next({...r,...tt.keepDirty?{isDirty:Q()}:{}}),!tt.keepIsValid&&w()},He=({disabled:Re,name:tt})=>{(Ip(Re)&&l.mount||Re||o.disabled.has(tt))&&(Re?o.disabled.add(tt):o.disabled.delete(tt))},Le=(Re,tt={})=>{let Ke=Wn(n,Re);const Ze=Ip(tt.disabled)||Ip(t.disabled);return Nl(n,Re,{...Ke||{},_f:{...Ke&&Ke._f?Ke._f:{ref:{name:Re}},name:Re,mount:!0,...tt}}),o.mount.add(Re),Ke?He({disabled:Ip(tt.disabled)?tt.disabled:t.disabled,name:Re}):A(Re,!0,tt.value),{...Ze?{disabled:tt.disabled||t.disabled}:{},...t.progressive?{required:!!tt.required,min:J6(tt.min),max:J6(tt.max),minLength:J6(tt.minLength),maxLength:J6(tt.maxLength),pattern:J6(tt.pattern)}:{},name:Re,onChange:oe,onBlur:oe,ref:lt=>{if(lt){Le(Re,tt),Ke=Wn(n,Re);const xt=Gd(lt.value)&<.querySelectorAll&<.querySelectorAll("input,select,textarea")[0]||lt,Xe=qBt(xt),Je=Ke._f.refs||[];if(Xe?Je.find(jt=>jt===xt):xt===Ke._f.ref)return;Nl(n,Re,{_f:{...Ke._f,...Xe?{refs:[...Je.filter(Ove),xt,...Array.isArray(Wn(a,Re))?[{}]:[]],ref:{type:xt.type,name:Re}}:{ref:xt}}}),A(Re,!1,void 0,xt)}else Ke=Wn(n,Re,{}),Ke._f&&(Ke._f.mount=!1),(t.shouldUnregister||tt.shouldUnregister)&&!(Ust(o.array,Re)&&l.action)&&o.unMount.add(Re)}}},Ie=()=>t.shouldFocusError&&uO(n,ne,o.mount),Te=Re=>{Ip(Re)&&(x.state.next({disabled:Re}),uO(n,(tt,Ke)=>{const Ze=Wn(n,Ke);Ze&&(tt.disabled=Ze._f.disabled||Re,Array.isArray(Ze._f.refs)&&Ze._f.refs.forEach(lt=>{lt.disabled=Ze._f.disabled||Re}))},0,!1))},xe=(Re,tt)=>async Ke=>{let Ze;Ke&&(Ke.preventDefault&&Ke.preventDefault(),Ke.persist&&Ke.persist());let lt=Iu(i);if(x.state.next({isSubmitting:!0}),t.resolver){const{errors:xt,values:Xe}=await R();r.errors=xt,lt=Iu(Xe)}else await F(n);if(o.disabled.size)for(const xt of o.disabled)du(lt,xt);if(du(r.errors,"root"),Of(r.errors)){x.state.next({errors:{}});try{await Re(lt,Ke)}catch(xt){Ze=xt}}else tt&&await tt({...r.errors},Ke),Ie(),setTimeout(Ie);if(x.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Of(r.errors)&&!Ze,submitCount:r.submitCount+1,errors:r.errors}),Ze)throw Ze},et=(Re,tt={})=>{Wn(n,Re)&&(Gd(tt.defaultValue)?le(Re,Iu(Wn(a,Re))):(le(Re,tt.defaultValue),Nl(a,Re,Iu(tt.defaultValue))),tt.keepTouched||du(r.touchedFields,Re),tt.keepDirty||(du(r.dirtyFields,Re),r.isDirty=tt.defaultValue?Q(Re,Iu(Wn(a,Re))):Q()),tt.keepError||(du(r.errors,Re),h.isValid&&w()),x.state.next({...r}))},fe=(Re,tt={})=>{const Ke=Re?Iu(Re):a,Ze=Iu(Ke),lt=Of(Re),xt=lt?a:Ze;if(tt.keepDefaultValues||(a=Ke),!tt.keepValues){if(tt.keepDirtyValues){const Xe=new Set([...o.mount,...Object.keys(Q6(a,i))]);for(const Je of Array.from(Xe))Wn(r.dirtyFields,Je)?Nl(xt,Je,Wn(i,Je)):le(Je,Wn(xt,Je))}else{if(G4e&&Gd(Re))for(const Xe of o.mount){const Je=Wn(n,Xe);if(Je&&Je._f){const jt=Array.isArray(Je._f.refs)?Je._f.refs[0]:Je._f.ref;if(qde(jt)){const ns=jt.closest("form");if(ns){ns.reset();break}}}}if(tt.keepFieldsRef)for(const Xe of o.mount)le(Xe,Wn(xt,Xe));else n={}}i=t.shouldUnregister?tt.keepDefaultValues?Iu(a):{}:Iu(xt),x.array.next({values:{...xt}}),x.state.next({values:{...xt}})}o={mount:tt.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!h.isValid||!!tt.keepIsValid||!!tt.keepDirtyValues,l.watch=!!t.shouldUnregister,x.state.next({submitCount:tt.keepSubmitCount?r.submitCount:0,isDirty:lt?!1:tt.keepDirty?r.isDirty:!!(tt.keepDefaultValues&&!J1(Re,a)),isSubmitted:tt.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:lt?{}:tt.keepDirtyValues?tt.keepDefaultValues&&i?Q6(a,i):r.dirtyFields:tt.keepDefaultValues&&Re?Q6(a,Re):tt.keepDirty?r.dirtyFields:{},touchedFields:tt.keepTouched?r.touchedFields:{},errors:tt.keepErrors?r.errors:{},isSubmitSuccessful:tt.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},it=(Re,tt)=>fe(xy(Re)?Re(i):Re,tt),Oe=(Re,tt={})=>{const Ke=Wn(n,Re),Ze=Ke&&Ke._f;if(Ze){const lt=Ze.refs?Ze.refs[0]:Ze.ref;lt.focus&&(lt.focus(),tt.shouldSelect&&xy(lt.select)&<.select())}},Ye=Re=>{r={...r,...Re}},_e={control:{register:Le,unregister:Ae,getFieldState:ce,handleSubmit:xe,setError:be,_subscribe:Be,_runSchema:R,_focusError:Ie,_getWatch:K,_getDirty:Q,_setValid:w,_setFieldArray:N,_setDisabledField:He,_setErrors:T,_getFieldArray:X,_reset:fe,_resetDefaultValues:()=>xy(t.defaultValues)&&t.defaultValues().then(Re=>{it(Re,t.resetOptions),x.state.next({isLoading:!1})}),_removeUnmounted:z,_disableForm:Te,_subjects:x,_proxyFormState:h,get _fields(){return n},get _formValues(){return i},get _state(){return l},set _state(Re){l=Re},get _defaultValues(){return a},get _names(){return o},set _names(Re){o=Re},get _formState(){return r},get _options(){return t},set _options(Re){t={...t,...Re}}},subscribe:De,trigger:ie,register:Le,handleSubmit:xe,watch:Ue,setValue:le,getValues:ye,reset:it,resetField:et,clearErrors:ve,unregister:Ae,setError:be,setFocus:Oe,getFieldState:ce};return{..._e,formControl:_e}}function Lfe(s={}){const t=wt.useRef(void 0),r=wt.useRef(void 0),[n,a]=wt.useState({isDirty:!1,isValidating:!1,isLoading:xy(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:xy(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:n},s.defaultValues&&!xy(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=tzt(s);t.current={...o,formState:n}}const i=t.current.control;return i._options=s,Z4e(()=>{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]),wt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),wt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),wt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),wt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),wt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==n.isDirty&&i._subjects.state.next({isDirty:l})}},[i,n.isDirty]),wt.useEffect(()=>{s.values&&!J1(s.values,r.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),r.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),wt.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=qst(n,i),t.current}const w8e=(s,t,r)=>{if(s&&"reportValidity"in s){const n=Wn(r,t);s.setCustomValidity(n&&n.message||""),s.reportValidity()}},Qst=(s,t)=>{for(const r in t.fields){const n=t.fields[r];n&&n.ref&&"reportValidity"in n.ref?w8e(n.ref,r,s):n.refs&&n.refs.forEach(a=>w8e(a,r,s))}},szt=(s,t)=>{t.shouldUseNativeValidation&&Qst(s,t);const r={};for(const n in s){const a=Wn(t.fields,n),i=Object.assign(s[n]||{},{ref:a&&a.ref});if(rzt(t.names||Object.keys(s),n)){const l=Object.assign({},Wn(r,n));Nl(l,"root",i),Nl(r,n,l)}else Nl(r,n,i)}return r},rzt=(s,t)=>s.some(r=>r.startsWith(t+"."));var nzt=function(s,t){for(var r={};s.length;){var n=s[0],a=n.code,i=n.message,l=n.path.join(".");if(!r[l])if("unionErrors"in n){var o=n.unionErrors[0].errors[0];r[l]={message:o.message,type:o.code}}else r[l]={message:i,type:a};if("unionErrors"in n&&n.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return s.push(m)})}),t){var c=r[l].types,d=c&&c[n.code];r[l]=Hst(l,t,r,a,d?[].concat(d,n.message):n.message)}s.shift()}return r},Pfe=function(s,t,r){return r===void 0&&(r={}),function(n,a,i){try{return Promise.resolve(function(l,o){try{var c=Promise.resolve(s[r.mode==="sync"?"parse":"parseAsync"](n,t)).then(function(d){return i.shouldUseNativeValidation&&Qst({},i),{errors:{},values:r.raw?n: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:szt(nzt(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const Dfe=FBt,Jst=k.createContext({}),td=({...s})=>e.jsx(Jst.Provider,{value:{name:s.name},children:e.jsx(UBt,{...s})}),Rfe=()=>{const s=k.useContext(Jst),t=k.useContext(ert),{getFieldState:r,formState:n}=Ife(),a=r(s.name,n);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}},ert=k.createContext({}),Oc=k.forwardRef(({className:s,...t},r)=>{const n=k.useId();return e.jsx(ert.Provider,{value:{id:n},children:e.jsx("div",{ref:r,className:It("space-y-2",s),...t})})});Oc.displayName="FormItem";const Fc=k.forwardRef(({className:s,...t},r)=>{const{error:n,formItemId:a}=Rfe();return e.jsx(he,{ref:r,className:It(n&&"text-destructive",s),htmlFor:a,...t})});Fc.displayName="FormLabel";const Bc=k.forwardRef(({...s},t)=>{const{error:r,formItemId:n,formDescriptionId:a,formMessageId:i}=Rfe();return e.jsx(sCe,{ref:t,id:n,"aria-describedby":r?`${a} ${i}`:`${a}`,"aria-invalid":!!r,...s})});Bc.displayName="FormControl";const pce=k.forwardRef(({className:s,...t},r)=>{const{formDescriptionId:n}=Rfe();return e.jsx("p",{ref:r,id:n,className:It("text-sm text-muted-foreground",s),...t})});pce.displayName="FormDescription";const lf=k.forwardRef(({className:s,children:t,...r},n)=>{const{error:a,formMessageId:i}=Rfe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:n,id:i,className:It("text-sm font-medium text-destructive",s),...r,children:l}):null});lf.displayName="FormMessage";const azt=qb({category:cet(["general","technology","crm","marketing"]),subject:io().min(5,"Subject must be at least 5 characters").max(200),description:io().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),izt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Fje({trigger:s}){const[t,r]=k.useState(!1),[n,a]=k.useState(!1),{user:i}=js(),l=Lfe({resolver:Pfe(azt),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ue.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await V.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await V.functions.invoke("support-ticket-notify",{body:{category:izt[c.category],subject:c.subject}})}catch(h){console.log("Notification send attempted:",h)}ue.success("Support ticket submitted successfully!"),l.reset(),r(!1)}catch(d){console.error("Error submitting ticket:",d),ue.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(fs,{open:t,onOpenChange:r,children:[e.jsx(vi,{asChild:!0,children:s||e.jsxs(G,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(CR,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(ms,{className:"sm:max-w-[500px]",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Need Help?"}),e.jsx(Hr,{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(Cn,{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(Dfe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(td,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Category"}),e.jsxs(Is,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Bc,{children:e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a category"})})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"general",children:"General Support"}),e.jsx(ct,{value:"technology",children:"Technology Support"}),e.jsx(ct,{value:"crm",children:"CRM Support"}),e.jsx(ct,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(lf,{})]})}),e.jsx(td,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Subject"}),e.jsx(Bc,{children:e.jsx(Ne,{placeholder:"Brief description of your issue",...c})}),e.jsx(lf,{})]})}),e.jsx(td,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Description"}),e.jsx(Bc,{children:e.jsx(or,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(lf,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}const ozt=()=>{const{user:s}=js(),t=br(),[r,n]=k.useState([]),[a,i]=k.useState(0),[l,o]=k.useState(!1),[c,d]=k.useState(null);k.useEffect(()=>{if(!s)return;const v=`notification_last_read_${s.id}`;let w=c;if(!w){const S=localStorage.getItem(v);S&&(w=S,d(S))}(async()=>{const{data:S,error:T}=await V.from("push_notifications").select("*").order("created_at",{ascending:!1}).limit(20);if(!T&&S){n(S);const A=w?new Date(w):null,I=S.filter(D=>A?new Date(D.created_at)>A:!0);i(I.length)}})();const N=V.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},S=>{const T=S.new;n(I=>[T,...I].slice(0,20));const A=w?new Date(w):null;(!A||new Date(T.created_at)>A)&&i(I=>I+1),Notification.permission==="granted"&&new Notification(T.title,{body:T.body,icon:"/favicon.ico"})}).subscribe();return()=>{V.removeChannel(N)}},[s,c]);const h=v=>{const w=v.toLowerCase();return w.includes("community")||w.includes("post")?xi:w.includes("academy")||w.includes("video")?Jr:w.includes("template")?fl:w.includes("event")?on:w.includes("newsletter")?iv:w.includes("brokerage")?Gu:w.includes("swag")||w.includes("social")?ii:w.includes("toolbox")||w.includes("tool")?Ay:w.includes("brief")?jr:xi},m=v=>{o(!1),v.url&&v.url!=="/"&&t(v.url)},x=()=>{if(!s)return;const v=new Date().toISOString(),w=`notification_last_read_${s.id}`;localStorage.setItem(w,v),d(v),i(0)},y=v=>{o(v),v&&a>0&&x()};return e.jsxs(Fd,{open:l,onOpenChange:y,children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(_m,{className:"h-5 w-5"}),a>0&&e.jsx(Ge,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:a>9?"9+":a})]})}),e.jsxs(xd,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&e.jsx(G,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:x,children:"Mark all read"})]}),e.jsx(Qa,{className:"h-[300px]",children:r.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(v=>{const w=h(v.title);return e.jsxs(Pa,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(v),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(w,{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:v.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:v.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:rl(new Date(v.created_at),{addSuffix:!0})})]})]},v.id)})})]})]})};var j8e=1,lzt=.9,czt=.8,dzt=.17,Fve=.1,Bve=.999,uzt=.9999,hzt=.99,mzt=/[\\\/_+.#"@\[\(\{&]/,fzt=/[\\\/_+.#"@\[\(\{&]/g,pzt=/[\s-]/,trt=/[\s-]/g;function Bje(s,t,r,n,a,i,l){if(i===t.length)return a===s.length?j8e:hzt;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=n.charAt(i),d=r.indexOf(c,a),h=0,m,x,y,v;d>=0;)m=Bje(s,t,r,n,d+1,i+1,l),m>h&&(d===a?m*=j8e:mzt.test(s.charAt(d-1))?(m*=czt,y=s.slice(a,d-1).match(fzt),y&&a>0&&(m*=Math.pow(Bve,y.length))):pzt.test(s.charAt(d-1))?(m*=lzt,v=s.slice(a,d-1).match(trt),v&&a>0&&(m*=Math.pow(Bve,v.length))):(m*=dzt,a>0&&(m*=Math.pow(Bve,d-a))),s.charAt(d)!==t.charAt(i)&&(m*=uzt)),(mm&&(m=x*Fve)),m>h&&(h=m),d=r.indexOf(c,d+1);return l[o]=h,h}function N8e(s){return s.toLowerCase().replace(trt," ")}function xzt(s,t,r){return s=r&&r.length>0?`${s+" "+r.join(" ")}`:s,Bje(s,t,N8e(s),N8e(t),0,0,{})}var eD='[cmdk-group=""]',zve='[cmdk-group-items=""]',gzt='[cmdk-group-heading=""]',srt='[cmdk-item=""]',k8e=`${srt}:not([aria-disabled="true"])`,zje="cmdk-item-select",_E="data-value",yzt=(s,t,r)=>xzt(s,t,r),rrt=k.createContext(void 0),dB=()=>k.useContext(rrt),nrt=k.createContext(void 0),J4e=()=>k.useContext(nrt),art=k.createContext(void 0),irt=k.forwardRef((s,t)=>{let r=wE(()=>{var ve,be;return{search:"",value:(be=(ve=s.value)!=null?ve:s.defaultValue)!=null?be:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=wE(()=>new Set),a=wE(()=>new Map),i=wE(()=>new Map),l=wE(()=>new Set),o=ort(s),{label:c,children:d,value:h,onValueChange:m,filter:x,shouldFilter:y,loop:v,disablePointerSelection:w=!1,vimBindings:b=!0,...N}=s,S=Yu(),T=Yu(),A=Yu(),I=k.useRef(null),D=Ezt();P3(()=>{if(h!==void 0){let ve=h.trim();r.current.value=ve,R.emit()}},[h]),P3(()=>{D(6,X)},[]);let R=k.useMemo(()=>({subscribe:ve=>(l.current.add(ve),()=>l.current.delete(ve)),snapshot:()=>r.current,setState:(ve,be,Ue)=>{var Be,De,Ae,He;if(!Object.is(r.current[ve],be)){if(r.current[ve]=be,ve==="search")K(),z(),D(1,Q);else if(ve==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Le=document.getElementById(A);Le?Le.focus():(Be=document.getElementById(S))==null||Be.focus()}if(D(7,()=>{var Le;r.current.selectedItemId=(Le=Z())==null?void 0:Le.id,R.emit()}),Ue||D(5,X),((De=o.current)==null?void 0:De.value)!==void 0){let Le=be??"";(He=(Ae=o.current).onValueChange)==null||He.call(Ae,Le);return}}R.emit()}},emit:()=>{l.current.forEach(ve=>ve())}}),[]),$=k.useMemo(()=>({value:(ve,be,Ue)=>{var Be;be!==((Be=i.current.get(ve))==null?void 0:Be.value)&&(i.current.set(ve,{value:be,keywords:Ue}),r.current.filtered.items.set(ve,F(be,Ue)),D(2,()=>{z(),R.emit()}))},item:(ve,be)=>(n.current.add(ve),be&&(a.current.has(be)?a.current.get(be).add(ve):a.current.set(be,new Set([ve]))),D(3,()=>{K(),z(),r.current.value||Q(),R.emit()}),()=>{i.current.delete(ve),n.current.delete(ve),r.current.filtered.items.delete(ve);let Ue=Z();D(4,()=>{K(),(Ue==null?void 0:Ue.getAttribute("id"))===ve&&Q(),R.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:S,inputId:A,labelId:T,listInnerRef:I}),[]);function F(ve,be){var Ue,Be;let De=(Be=(Ue=o.current)==null?void 0:Ue.filter)!=null?Be:yzt;return ve?De(ve,r.current.search,be):0}function z(){if(!r.current.search||o.current.shouldFilter===!1)return;let ve=r.current.filtered.items,be=[];r.current.filtered.groups.forEach(Be=>{let De=a.current.get(Be),Ae=0;De.forEach(He=>{let Le=ve.get(He);Ae=Math.max(Le,Ae)}),be.push([Be,Ae])});let Ue=I.current;re().sort((Be,De)=>{var Ae,He;let Le=Be.getAttribute("id"),Ie=De.getAttribute("id");return((Ae=ve.get(Ie))!=null?Ae:0)-((He=ve.get(Le))!=null?He:0)}).forEach(Be=>{let De=Be.closest(zve);De?De.appendChild(Be.parentElement===De?Be:Be.closest(`${zve} > *`)):Ue.appendChild(Be.parentElement===Ue?Be:Be.closest(`${zve} > *`))}),be.sort((Be,De)=>De[1]-Be[1]).forEach(Be=>{var De;let Ae=(De=I.current)==null?void 0:De.querySelector(`${eD}[${_E}="${encodeURIComponent(Be[0])}"]`);Ae==null||Ae.parentElement.appendChild(Ae)})}function Q(){let ve=re().find(Ue=>Ue.getAttribute("aria-disabled")!=="true"),be=ve==null?void 0:ve.getAttribute(_E);R.setState("value",be||void 0)}function K(){var ve,be,Ue,Be;if(!r.current.search||o.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let De=0;for(let Ae of n.current){let He=(be=(ve=i.current.get(Ae))==null?void 0:ve.value)!=null?be:"",Le=(Be=(Ue=i.current.get(Ae))==null?void 0:Ue.keywords)!=null?Be:[],Ie=F(He,Le);r.current.filtered.items.set(Ae,Ie),Ie>0&&De++}for(let[Ae,He]of a.current)for(let Le of He)if(r.current.filtered.items.get(Le)>0){r.current.filtered.groups.add(Ae);break}r.current.filtered.count=De}function X(){var ve,be,Ue;let Be=Z();Be&&(((ve=Be.parentElement)==null?void 0:ve.firstChild)===Be&&((Ue=(be=Be.closest(eD))==null?void 0:be.querySelector(gzt))==null||Ue.scrollIntoView({block:"nearest"})),Be.scrollIntoView({block:"nearest"}))}function Z(){var ve;return(ve=I.current)==null?void 0:ve.querySelector(`${srt}[aria-selected="true"]`)}function re(){var ve;return Array.from(((ve=I.current)==null?void 0:ve.querySelectorAll(k8e))||[])}function le(ve){let be=re()[ve];be&&R.setState("value",be.getAttribute(_E))}function oe(ve){var be;let Ue=Z(),Be=re(),De=Be.findIndex(He=>He===Ue),Ae=Be[De+ve];(be=o.current)!=null&&be.loop&&(Ae=De+ve<0?Be[Be.length-1]:De+ve===Be.length?Be[0]:Be[De+ve]),Ae&&R.setState("value",Ae.getAttribute(_E))}function ne(ve){let be=Z(),Ue=be==null?void 0:be.closest(eD),Be;for(;Ue&&!Be;)Ue=ve>0?Czt(Ue,eD):Tzt(Ue,eD),Be=Ue==null?void 0:Ue.querySelector(k8e);Be?R.setState("value",Be.getAttribute(_E)):oe(ve)}let ie=()=>le(re().length-1),ye=ve=>{ve.preventDefault(),ve.metaKey?ie():ve.altKey?ne(1):oe(1)},ce=ve=>{ve.preventDefault(),ve.metaKey?le(0):ve.altKey?ne(-1):oe(-1)};return k.createElement(wn.div,{ref:t,tabIndex:-1,...N,"cmdk-root":"",onKeyDown:ve=>{var be;(be=N.onKeyDown)==null||be.call(N,ve);let Ue=ve.nativeEvent.isComposing||ve.keyCode===229;if(!(ve.defaultPrevented||Ue))switch(ve.key){case"n":case"j":{b&&ve.ctrlKey&&ye(ve);break}case"ArrowDown":{ye(ve);break}case"p":case"k":{b&&ve.ctrlKey&&ce(ve);break}case"ArrowUp":{ce(ve);break}case"Home":{ve.preventDefault(),le(0);break}case"End":{ve.preventDefault(),ie();break}case"Enter":{ve.preventDefault();let Be=Z();if(Be){let De=new Event(zje);Be.dispatchEvent(De)}}}}},k.createElement("label",{"cmdk-label":"",htmlFor:$.inputId,id:$.labelId,style:Mzt},c),Ofe(s,ve=>k.createElement(nrt.Provider,{value:R},k.createElement(rrt.Provider,{value:$},ve))))}),vzt=k.forwardRef((s,t)=>{var r,n;let a=Yu(),i=k.useRef(null),l=k.useContext(art),o=dB(),c=ort(s),d=(n=(r=c.current)==null?void 0:r.forceMount)!=null?n:l==null?void 0:l.forceMount;P3(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let h=lrt(a,i,[s.value,s.children,i],s.keywords),m=J4e(),x=Dj(D=>D.value&&D.value===h.current),y=Dj(D=>d||o.filter()===!1?!0:D.search?D.filtered.items.get(a)>0:!0);k.useEffect(()=>{let D=i.current;if(!(!D||s.disabled))return D.addEventListener(zje,v),()=>D.removeEventListener(zje,v)},[y,s.onSelect,s.disabled]);function v(){var D,R;w(),(R=(D=c.current).onSelect)==null||R.call(D,h.current)}function w(){m.setState("value",h.current,!0)}if(!y)return null;let{disabled:b,value:N,onSelect:S,forceMount:T,keywords:A,...I}=s;return k.createElement(wn.div,{ref:Eb(i,t),...I,id:a,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!x,"data-disabled":!!b,"data-selected":!!x,onPointerMove:b||o.getDisablePointerSelection()?void 0:w,onClick:b?void 0:v},s.children)}),bzt=k.forwardRef((s,t)=>{let{heading:r,children:n,forceMount:a,...i}=s,l=Yu(),o=k.useRef(null),c=k.useRef(null),d=Yu(),h=dB(),m=Dj(y=>a||h.filter()===!1?!0:y.search?y.filtered.groups.has(l):!0);P3(()=>h.group(l),[]),lrt(l,o,[s.value,s.heading,c]);let x=k.useMemo(()=>({id:l,forceMount:a}),[a]);return k.createElement(wn.div,{ref:Eb(o,t),...i,"cmdk-group":"",role:"presentation",hidden:m?void 0:!0},r&&k.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},r),Ofe(s,y=>k.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?d:void 0},k.createElement(art.Provider,{value:x},y))))}),_zt=k.forwardRef((s,t)=>{let{alwaysRender:r,...n}=s,a=k.useRef(null),i=Dj(l=>!l.search);return!r&&!i?null:k.createElement(wn.div,{ref:Eb(a,t),...n,"cmdk-separator":"",role:"separator"})}),wzt=k.forwardRef((s,t)=>{let{onValueChange:r,...n}=s,a=s.value!=null,i=J4e(),l=Dj(d=>d.search),o=Dj(d=>d.selectedItemId),c=dB();return k.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),k.createElement(wn.input,{ref:t,...n,"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),r==null||r(d.target.value)}})}),jzt=k.forwardRef((s,t)=>{let{children:r,label:n="Suggestions",...a}=s,i=k.useRef(null),l=k.useRef(null),o=Dj(d=>d.selectedItemId),c=dB();return k.useEffect(()=>{if(l.current&&i.current){let d=l.current,h=i.current,m,x=new ResizeObserver(()=>{m=requestAnimationFrame(()=>{let y=d.offsetHeight;h.style.setProperty("--cmdk-list-height",y.toFixed(1)+"px")})});return x.observe(d),()=>{cancelAnimationFrame(m),x.unobserve(d)}}},[]),k.createElement(wn.div,{ref:Eb(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":n,id:c.listId},Ofe(s,d=>k.createElement("div",{ref:Eb(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Nzt=k.forwardRef((s,t)=>{let{open:r,onOpenChange:n,overlayClassName:a,contentClassName:i,container:l,...o}=s;return k.createElement(afe,{open:r,onOpenChange:n},k.createElement(ife,{container:l},k.createElement(zI,{"cmdk-overlay":"",className:a}),k.createElement($I,{"aria-label":s.label,"cmdk-dialog":"",className:i},k.createElement(irt,{ref:t,...o}))))}),kzt=k.forwardRef((s,t)=>Dj(r=>r.filtered.count===0)?k.createElement(wn.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),Szt=k.forwardRef((s,t)=>{let{progress:r,children:n,label:a="Loading...",...i}=s;return k.createElement(wn.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},Ofe(s,l=>k.createElement("div",{"aria-hidden":!0},l)))}),np=Object.assign(irt,{List:jzt,Item:vzt,Input:wzt,Group:bzt,Separator:_zt,Dialog:Nzt,Empty:kzt,Loading:Szt});function Czt(s,t){let r=s.nextElementSibling;for(;r;){if(r.matches(t))return r;r=r.nextElementSibling}}function Tzt(s,t){let r=s.previousElementSibling;for(;r;){if(r.matches(t))return r;r=r.previousElementSibling}}function ort(s){let t=k.useRef(s);return P3(()=>{t.current=s}),t}var P3=typeof window>"u"?k.useEffect:k.useLayoutEffect;function wE(s){let t=k.useRef();return t.current===void 0&&(t.current=s()),t}function Dj(s){let t=J4e(),r=()=>s(t.snapshot());return k.useSyncExternalStore(t.subscribe,r,r)}function lrt(s,t,r,n=[]){let a=k.useRef(),i=dB();return P3(()=>{var l;let o=(()=>{var d;for(let h of r){if(typeof h=="string")return h.trim();if(typeof h=="object"&&"current"in h)return h.current?(d=h.current.textContent)==null?void 0:d.trim():a.current}})(),c=n.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(_E,o),a.current=o}),a}var Ezt=()=>{let[s,t]=k.useState(),r=wE(()=>new Map);return P3(()=>{r.current.forEach(n=>n()),r.current=new Map},[s]),(n,a)=>{r.current.set(n,a),t({})}};function Azt(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function Ofe({asChild:s,children:t},r){return s&&k.isValidElement(t)?k.cloneElement(Azt(t),{ref:t.ref},r(t.props.children)):r(t)}var Mzt={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const rx=k.forwardRef(({className:s,...t},r)=>e.jsx(np,{ref:r,className:It("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));rx.displayName=np.displayName;const Izt=({children:s,...t})=>e.jsx(fs,{...t,children:e.jsx(ms,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(rx,{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})})}),nx=k.forwardRef(({className:s,...t},r)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(yn,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(np.Input,{ref:r,className:It("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})]}));nx.displayName=np.Input.displayName;const ax=k.forwardRef(({className:s,...t},r)=>e.jsx(np.List,{ref:r,className:It("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));ax.displayName=np.List.displayName;const ix=k.forwardRef((s,t)=>e.jsx(np.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));ix.displayName=np.Empty.displayName;const ox=k.forwardRef(({className:s,...t},r)=>e.jsx(np.Group,{ref:r,className:It("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}));ox.displayName=np.Group.displayName;const Lzt=k.forwardRef(({className:s,...t},r)=>e.jsx(np.Separator,{ref:r,className:It("-mx-1 h-px bg-border",s),...t}));Lzt.displayName=np.Separator.displayName;const cf=k.forwardRef(({className:s,...t},r)=>e.jsx(np.Item,{ref:r,className:It("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}));cf.displayName=np.Item.displayName;const Pzt={event:{label:"Events",icon:hd,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:Md,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:Ay,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:jr,color:"bg-fuchsia-500/10 text-fuchsia-600"}},S8e=()=>{const[s,t]=k.useState(!1),[r,n]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=br();k.useEffect(()=>{const x=y=>{y.key==="k"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),t(v=>!v))};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[]);const d=k.useCallback(async x=>{if(!x.trim()){i([]);return}o(!0);const y=`%${x}%`;try{const[v,w,b,N,S]=await Promise.all([V.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5),V.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${y},description.ilike.${y}`).limit(5),V.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5),V.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${y},description.ilike.${y}`).limit(5),V.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${y},description.ilike.${y}`).limit(5)]),T=[];v.data&&v.data.forEach(A=>{T.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),w.data&&w.data.forEach(A=>{T.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),b.data&&b.data.forEach(A=>{T.push({id:A.id,title:A.title,description:A.description,type:"academy",date:A.publish_date,path:`/academy/${A.id}`})}),N.data&&N.data.forEach(A=>{T.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),S.data&&S.data.forEach(A=>{T.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(T)}catch(v){console.error("Search error:",v)}finally{o(!1)}},[]);k.useEffect(()=>{const x=setTimeout(()=>{d(r)},300);return()=>clearTimeout(x)},[r,d]);const h=x=>{t(!1),n(""),c(x)},m=a.reduce((x,y)=>(x[y.type]||(x[y.type]=[]),x[y.type].push(y),x),{});return e.jsxs(e.Fragment,{children:[e.jsxs(G,{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(yn,{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(Izt,{open:s,onOpenChange:t,children:[e.jsx(nx,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),e.jsxs(ax,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&r&&a.length===0&&e.jsxs(ix,{children:['No results found for "',r,'"']}),!l&&!r&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(m).map(([x,y])=>{const v=Pzt[x],w=v.icon;return e.jsx(ox,{heading:v.label,children:y.map(b=>e.jsxs(cf,{value:`${b.type}-${b.id}-${b.title}`,onSelect:()=>h(b.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${v.color}`,children:e.jsx(w,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:b.title}),b.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:b.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs",children:v.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:rl(new Date(b.date),{addSuffix:!0})})]})]},`${b.type}-${b.id}`))},x)})]})]})]})},Dzt=({expiresAt:s,className:t,showUpgradeButton:r=!0})=>{const[n,a]=k.useState(null),i=br();if(k.useEffect(()=>{const d=()=>{const m=new Date().getTime(),y=new Date(s).getTime()-m;if(y<=0){a({days:0,hours:0,minutes:0});return}const v=Math.floor(y/(1e3*60*60*24)),w=Math.floor(y%(1e3*60*60*24)/(1e3*60*60)),b=Math.floor(y%(1e3*60*60)/(1e3*60));a({days:v,hours:w,minutes:b})};d();const h=setInterval(d,6e4);return()=>clearInterval(h)},[s]),!n)return null;const l=n.days===0&&n.hours===0&&n.minutes===0,o=n.days<=1,c=n.days<=3&&!o;return l?e.jsxs("div",{className:It("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(id,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&e.jsxs(G,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:It("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(fn,{className:It("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:It("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:[n.days>0&&e.jsxs("span",{className:It("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.days,"d"]}),e.jsxs("span",{className:It("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),e.jsxs("span",{className:It("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),e.jsx("span",{className:It("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&e.jsxs(G,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:It("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},Rzt=()=>{const s=br();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(ke,{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(id,{className:"h-8 w-8 text-destructive"})}),e.jsx(Dt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Nr,{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(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(ke,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Pe,{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(pr,{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(G,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(ke,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Pe,{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(Sa,{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(G,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Sa,{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(Cn,{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"})]})]})]})]})]})})},Ozt=({hasUnseenBrief:s,onClick:t,className:r})=>e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"icon",onClick:t,className:It("relative transition-colors",s&&"text-primary hover:text-primary",r),children:[e.jsx(bu,{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(Gl,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var e3e="Radio",[Fzt,crt]=pd(e3e),[Bzt,zzt]=Fzt(e3e),drt=k.forwardRef((s,t)=>{const{__scopeRadio:r,name:n,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...h}=s,[m,x]=k.useState(null),y=Ga(t,b=>x(b)),v=k.useRef(!1),w=m?d||!!m.closest("form"):!0;return e.jsxs(Bzt,{scope:r,checked:a,disabled:l,children:[e.jsx(wn.button,{type:"button",role:"radio","aria-checked":a,"data-state":frt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...h,ref:y,onClick:Vr(s.onClick,b=>{a||c==null||c(),w&&(v.current=b.isPropagationStopped(),v.current||b.stopPropagation())})}),w&&e.jsx(mrt,{control:m,bubbles:!v.current,name:n,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});drt.displayName=e3e;var urt="RadioIndicator",hrt=k.forwardRef((s,t)=>{const{__scopeRadio:r,forceMount:n,...a}=s,i=zzt(urt,r);return e.jsx(ru,{present:n||i.checked,children:e.jsx(wn.span,{"data-state":frt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});hrt.displayName=urt;var $zt="RadioBubbleInput",mrt=k.forwardRef(({__scopeRadio:s,control:t,checked:r,bubbles:n=!0,...a},i)=>{const l=k.useRef(null),o=Ga(l,i),c=sB(r),d=UF(t);return k.useEffect(()=>{const h=l.current;if(!h)return;const m=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(m,"checked").set;if(c!==r&&y){const v=new Event("click",{bubbles:n});y.call(h,r),h.dispatchEvent(v)}},[c,r,n]),e.jsx(wn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});mrt.displayName=$zt;function frt(s){return s?"checked":"unchecked"}var Uzt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Ffe="RadioGroup",[qzt,DUs]=pd(Ffe,[Yj,crt]),prt=Yj(),xrt=crt(),[Vzt,Hzt]=qzt(Ffe),grt=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,name:n,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:h=!0,onValueChange:m,...x}=s,y=prt(r),v=Kj(d),[w,b]=Sh({prop:i,defaultProp:a??null,onChange:m,caller:Ffe});return e.jsx(Vzt,{scope:r,name:n,required:l,disabled:o,value:w,onValueChange:b,children:e.jsx(Xme,{asChild:!0,...y,orientation:c,dir:v,loop:h,children:e.jsx(wn.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:v,...x,ref:t})})})});grt.displayName=Ffe;var yrt="RadioGroupItem",vrt=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,disabled:n,...a}=s,i=Hzt(yrt,r),l=i.disabled||n,o=prt(r),c=xrt(r),d=k.useRef(null),h=Ga(t,d),m=i.value===a.value,x=k.useRef(!1);return k.useEffect(()=>{const y=w=>{Uzt.includes(w.key)&&(x.current=!0)},v=()=>x.current=!1;return document.addEventListener("keydown",y),document.addEventListener("keyup",v),()=>{document.removeEventListener("keydown",y),document.removeEventListener("keyup",v)}},[]),e.jsx(Qme,{asChild:!0,...o,focusable:!l,active:m,children:e.jsx(drt,{disabled:l,required:i.required,checked:m,...c,...a,name:i.name,ref:h,onCheck:()=>i.onValueChange(a.value),onKeyDown:Vr(y=>{y.key==="Enter"&&y.preventDefault()}),onFocus:Vr(a.onFocus,()=>{var y;x.current&&((y=d.current)==null||y.click())})})})});vrt.displayName=yrt;var Gzt="RadioGroupIndicator",brt=k.forwardRef((s,t)=>{const{__scopeRadioGroup:r,...n}=s,a=xrt(r);return e.jsx(hrt,{...a,...n,ref:t})});brt.displayName=Gzt;var _rt=grt,wrt=vrt,Wzt=brt;const ab=k.forwardRef(({className:s,...t},r)=>e.jsx(_rt,{className:It("grid gap-2",s),...t,ref:r}));ab.displayName=_rt.displayName;const Hd=k.forwardRef(({className:s,...t},r)=>e.jsx(wrt,{ref:r,className:It("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(Wzt,{className:"flex items-center justify-center",children:e.jsx(Ld,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Hd.displayName=wrt.displayName;const Kzt=({brief:s,open:t,onClose:r,onDismiss:n})=>{const{user:a}=js(),[i,l]=k.useState({}),[o,c]=k.useState({}),[d,h]=k.useState([]);k.useEffect(()=>{t&&a&&s.polls.length>0&&m()},[t,a,s.polls]);const m=async()=>{if(!a)return;const b=s.polls.map(S=>S.id),{data:N}=await V.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",b);if(N){const S={};N.forEach(T=>{S[T.poll_id]||(S[T.poll_id]=[]),S[T.poll_id].push(T.option_id)}),c(S)}},x=(b,N)=>{l(S=>({...S,[b]:N}))},y=(b,N,S)=>{l(T=>{const A=T[b]||[];return S?{...T,[b]:[...A,N]}:{...T,[b]:A.filter(I=>I!==N)}})},v=async b=>{if(!a)return;const N=i[b];if(!N||Array.isArray(N)&&N.length===0){ue.error("Please select an option");return}h(S=>[...S,b]);try{await V.from("levelup_brief_poll_responses").delete().eq("poll_id",b).eq("user_id",a.id);const S=Array.isArray(N)?N:[N],T=S.map(I=>({poll_id:b,option_id:I,user_id:a.id})),{error:A}=await V.from("levelup_brief_poll_responses").insert(T);if(A)throw A;c(I=>({...I,[b]:S})),ue.success("Response submitted!")}catch(S){console.error("Error submitting poll response:",S),ue.error("Failed to submit response")}finally{h(S=>S.filter(T=>T!==b))}},w=b=>(b.includes("mediadelivery.net")||b.includes("bunny"),b);return e.jsx(fs,{open:t,onOpenChange:b=>!b&&r(),children:e.jsxs(ms,{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:r,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(vr,{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(bu,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Ge,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(gs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Qa,{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:w(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(b=>e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>window.open(b.url,"_blank"),className:"gap-2",children:[e.jsx(Qr,{className:"h-4 w-4"}),b.title]},b.id))})]}),s.polls.map(b=>{var T,A;const N=((T=o[b.id])==null?void 0:T.length)>0,S=d.includes(b.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:b.question}),N&&e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(In,{className:"h-3 w-3"}),"Responded"]})]}),b.poll_type==="single"?e.jsx(ab,{value:i[b.id]||((A=o[b.id])==null?void 0:A[0])||"",onValueChange:I=>x(b.id,I),className:"space-y-2",children:b.options.map(I=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:I.id,id:I.id}),e.jsx(he,{htmlFor:I.id,className:"cursor-pointer",children:I.option_text})]},I.id))}):e.jsx("div",{className:"space-y-2",children:b.options.map(I=>{const R=(i[b.id]||o[b.id]||[]).includes(I.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Si,{id:I.id,checked:R,onCheckedChange:$=>y(b.id,I.id,$)}),e.jsx(he,{htmlFor:I.id,className:"cursor-pointer",children:I.option_text})]},I.id)})}),e.jsx(G,{size:"sm",onClick:()=>v(b.id),disabled:S,children:S?"Submitting...":N?"Update Response":"Submit"})]},b.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(G,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},Yzt=()=>{const{user:s}=js(),[t,r]=k.useState(null),[n,a]=k.useState(!1),[i,l]=k.useState(!0),[o,c]=k.useState(!1),d=k.useCallback(async()=>{if(!s){l(!1);return}try{const{data:v,error:w}=await V.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(w||!v){l(!1);return}const{data:b}=await V.from("levelup_brief_views").select("*").eq("brief_id",v.id).eq("user_id",s.id).maybeSingle(),[N,S]=await Promise.all([V.from("levelup_brief_links").select("*").eq("brief_id",v.id).order("sort_order"),V.from("levelup_brief_polls").select("*").eq("brief_id",v.id).order("sort_order")]),T=[];if(S.data)for(const $ of S.data){const{data:F}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",$.id).order("sort_order");T.push({...$,options:F||[]})}const A={brief:v,links:N.data||[],polls:T};r(A);const I=!!b,D=(b==null?void 0:b.dismissed_at)!=null,R=localStorage.getItem(`brief-dismissed-${v.id}`)==="true";if(D||R)c(!1),a(!1);else if(!I)a(!0),c(!0);else if(v.show_frequency==="every_login")a(!0),c(!0);else if(v.show_frequency==="daily"){const $=new Date(b.viewed_at);(new Date().getTime()-$.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(v){console.error("Error fetching brief:",v)}finally{l(!1)}},[s]);k.useEffect(()=>{d()},[d]);const h=async()=>{if(!(!s||!t))try{const{data:v}=await V.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();v?await V.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",v.id):await V.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(v){console.error("Error marking brief as viewed:",v)}};return{currentBrief:t,shouldShowPopup:n,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),h()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:v,error:w}=await V.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(w&&console.error("Error checking existing brief view:",w),v){const{error:b}=await V.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",v.id).eq("user_id",s.id);b&&console.error("Error updating brief dismiss:",b)}else{const{error:b}=await V.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});b&&console.error("Error inserting brief dismiss:",b)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(v){console.error("Error dismissing brief:",v),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function Zzt(){const[s,t]=k.useState(!1),[r,n]=k.useState(!1),[a,i]=k.useState(null);k.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const m=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(m),t(!0);const x=y=>{y.preventDefault(),i(y)};return window.addEventListener("beforeinstallprompt",x),()=>{window.removeEventListener("beforeinstallprompt",x)}},[]);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(Ya,{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"}),r?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx($R,{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:[!r&&a&&e.jsx(G,{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(vr,{className:"h-4 w-4"})})]})]})}):null}const Xzt=({children:s,onRefresh:t})=>{const[r,n]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(0),h=Xt(),m=80,x=120,y=k.useCallback(S=>{const T=c.current;T&&T.scrollTop<=0&&(d.current=S.touches[0].clientY,n(!0))},[]),v=k.useCallback(S=>{if(!r||l)return;const T=c.current;if(!T||T.scrollTop>0){n(!1),i(0);return}const I=S.touches[0].clientY-d.current;if(I>0){const R=Math.min(I*.5,x);i(R),R>10&&S.preventDefault()}},[r,l]),w=k.useCallback(async()=>{if(r)if(n(!1),a>=m&&!l){o(!0),i(m);try{t?await t():await h.invalidateQueries()}catch(S){console.error("Refresh failed:",S)}finally{o(!1),i(0)}}else i(0)},[r,a,l,t,h]),b=Math.min(a/m,1),N=b*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:y,onTouchMove:v,onTouchEnd:w,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:b},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${N}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Mi,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:r?void 0:"transform 0.2s ease-out"},children:s})]})},jrt=()=>{const{user:s}=js(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(!0);k.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:y}=await V.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(y){a(!0),r(!1),c(!1);return}const{data:v}=await V.from("profiles").select("login_count").eq("id",s.id).single(),w=(v==null?void 0:v.login_count)||0;l(w);const b=sessionStorage.getItem("review-prompt-dismissed");r(w>=4&&!b)}catch(y){console.error("Error checking review eligibility:",y)}finally{c(!1)}})()},[s]);const d=k.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),h=k.useCallback(async(x,y)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:v}=await V.from("membership_reviews").insert({user_id:s.id,rating:x,review_text:y});if(v)throw v;return a(!0),r(!1),{success:!0,pointsAwarded:25}}catch(v){return console.error("Error submitting review:",v),{success:!1,error:v.message}}},[s]),m=k.useCallback(async()=>{if(s)try{await V.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(x){console.error("Error updating Google review status:",x)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:n,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:h,markPostedToGoogle:m}},Qzt="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",Jzt=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:r,submitReview:n,markPostedToGoogle:a}=jrt(),[i,l]=k.useState(!1),[o,c]=k.useState("review"),[d,h]=k.useState(0),[m,x]=k.useState(0),[y,v]=k.useState(""),[w,b]=k.useState(!1),[N,S]=k.useState(!1);if(t||!s&&!N)return null;const T=async()=>{if(d===0){cn({title:"Please select a rating",variant:"destructive"});return}b(!0);const D=await n(d,y);b(!1),D.success?(S(!0),cn({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):cn({title:"Error submitting review",description:D.error,variant:"destructive"})},A=async D=>{D&&(await navigator.clipboard.writeText(y||`${d} star rating for LevelUp!`),cn({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(Qzt,"_blank")),l(!1),r()},I=()=>{l(!1),r()};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(Xn,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(fs,{open:i,onOpenChange:I,children:e.jsx(ms,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(ys,{children:[e.jsx(gs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Hr,{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(D=>e.jsx("button",{type:"button",onClick:()=>h(D),onMouseEnter:()=>x(D),onMouseLeave:()=>x(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Xn,{className:It("h-8 w-8 transition-colors",(m||d)>=D?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},D))}),e.jsx(or,{placeholder:"Tell us about your experience (optional)",value:y,onChange:D=>v(D.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:I,className:"flex-1",children:"Maybe Later"}),e.jsx(G,{onClick:T,disabled:w||d===0,className:"flex-1",children:w?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ys,{children:[e.jsx(gs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Hr,{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(G,{variant:"outline",onClick:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(G,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function e7t(s){const t="=".repeat((4-s.length%4)%4),r=(s+t).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(r),a=new Uint8Array(n.length);for(let i=0;i{if(!m){l(!1);return}(async()=>{try{const w="vapid_public_key";let b=localStorage.getItem(w);if(!b){const{data:T,error:A}=await V.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(b=(T==null?void 0:T.vapidPublicKey)??null,!b)throw new Error("Missing VAPID public key");localStorage.setItem(w,b)}h(b);const N=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(N),r(Notification.permission);const S=await N.pushManager.getSubscription();a(!!S)}catch(w){console.error("Error initializing push notifications:",w)}finally{l(!1)}})()},[m]);const x=k.useCallback(async()=>{if(!m||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ue.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const v=await o.pushManager.getSubscription();if(v){try{await v.unsubscribe()}catch(A){console.warn("Failed to unsubscribe existing push subscription:",A)}const{error:T}=await V.from("push_subscriptions").delete().eq("user_id",s.id);T&&console.warn("Failed to cleanup push_subscriptions rows:",T)}if(Notification.permission!=="granted"){const T=await Notification.requestPermission();if(r(T),T!=="granted")return T==="denied"?ue.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ue.error("Notification permission was dismissed. Please try again."),!1}const w=e7t(d);let b;try{b=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:w})}catch(T){console.error("PushManager.subscribe() failed:",T);const A=(T==null?void 0:T.message)||String(T);return A.includes("permission")?ue.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?ue.error("Push configuration error. Please contact support."):A.includes("AbortError")?ue.error("Push subscription was cancelled. Please try again."):ue.error(`Failed to subscribe: ${A}`),!1}const N=b.toJSON(),{error:S}=await V.from("push_subscriptions").upsert({user_id:s.id,endpoint:N.endpoint,p256dh_key:N.keys.p256dh,auth_key:N.keys.auth},{onConflict:"user_id,endpoint"});if(S)throw console.error("Error saving subscription:",S),ue.error("Failed to save notification preferences. Please try again."),S;return a(!0),ue.success("Push notifications enabled!"),!0}catch(v){if(console.error("Error subscribing to push notifications:",v),!(v instanceof Error&&v.message.includes("toast"))){const w=v instanceof Error?v.message:"Unknown error";ue.error("Failed to enable push notifications: "+w)}return!1}finally{l(!1)}},[m,o,s,d]),y=k.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const v=await o.pushManager.getSubscription();return v&&await v.unsubscribe(),await V.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ue.success("Push notifications disabled"),!0}catch(v){console.error("Error unsubscribing:",v);const w=v instanceof Error?v.message:"Unknown error";return ue.error("Failed to disable push notifications: "+w),!1}finally{l(!1)}},[o,s]);return{isSupported:m,permission:t,isSubscribed:n,isLoading:i,vapidPublicKey:d,subscribe:x,unsubscribe:y}}const $ve="push_notification_prompt_dismissed",t7t=["/dashboard","/admin"],s7t=()=>{const{user:s}=js(),{isSupported:t,isSubscribed:r,isLoading:n,subscribe:a}=Nrt(),i=ec(),[l,o]=k.useState(!1),[c,d]=k.useState(!1),h=t7t.some(y=>i.pathname===y||i.pathname.startsWith(`${y}/`));k.useEffect(()=>{if(h){o(!1);return}if(!s||!t||r||n||localStorage.getItem(`${$ve}_${s.id}`))return;const v=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(v)},[s,t,r,n,h]);const m=async()=>{d(!0);const y=await a();d(!1),y&&(s&&localStorage.setItem(`${$ve}_${s.id}`,"true"),o(!1))},x=()=>{s&&localStorage.setItem(`${$ve}_${s.id}`,"true"),o(!1)};return!t||r||h?null:e.jsx(fs,{open:l,onOpenChange:y=>!y&&x(),children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{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(_m,{className:"h-6 w-6 text-primary"})}),e.jsx(gs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Hr,{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(G,{onClick:m,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(G,{variant:"ghost",onClick:x,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."})]})})},C8e=s=>{let t;const r=new Set,n=(d,h)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const x=t;t=h??(typeof m!="object"||m===null)?m:Object.assign({},t,m),r.forEach(y=>y(t,x))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>c,subscribe:d=>(r.add(d),()=>r.delete(d))},c=t=s(n,a,o);return o},r7t=s=>s?C8e(s):C8e,n7t=s=>s;function a7t(s,t=n7t){const r=wt.useSyncExternalStore(s.subscribe,wt.useCallback(()=>t(s.getState()),[s,t]),wt.useCallback(()=>t(s.getInitialState()),[s,t]));return wt.useDebugValue(r),r}const T8e=s=>{const t=r7t(s),r=n=>a7t(t,n);return Object.assign(r,t),r},i7t=s=>s?T8e(s):T8e;function o7t(s,t){let r;try{r=s()}catch{return}return{getItem:a=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),o=(i=r.getItem(a))!=null?i:null;return o instanceof Promise?o.then(l):l(o)},setItem:(a,i)=>r.setItem(a,JSON.stringify(i,void 0)),removeItem:a=>r.removeItem(a)}}const $je=s=>t=>{try{const r=s(t);return r instanceof Promise?r:{then(n){return $je(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return $je(n)(r)}}}},l7t=(s,t)=>(r,n,a)=>{let i={storage:o7t(()=>window.localStorage),partialize:b=>b,version:0,merge:(b,N)=>({...N,...b}),...t},l=!1,o=0;const c=new Set,d=new Set;let h=i.storage;if(!h)return s((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),r(...b)},n,a);const m=()=>{const b=i.partialize({...n()});return h.setItem(i.name,{state:b,version:i.version})},x=a.setState;a.setState=(b,N)=>(x(b,N),m());const y=s((...b)=>(r(...b),m()),n,a);a.getInitialState=()=>y;let v;const w=()=>{var b,N;if(!h)return;const S=++o;l=!1,c.forEach(A=>{var I;return A((I=n())!=null?I:y)});const T=((N=i.onRehydrateStorage)==null?void 0:N.call(i,(b=n())!=null?b:y))||void 0;return $je(h.getItem.bind(h))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const I=i.migrate(A.state,A.version);return I instanceof Promise?I.then(D=>[!0,D]):[!0,I]}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 I;if(S!==o)return;const[D,R]=A;if(v=i.merge(R,(I=n())!=null?I:y),r(v,!0),D)return m()}).then(()=>{S===o&&(T==null||T(n(),void 0),v=n(),l=!0,d.forEach(A=>A(v)))}).catch(A=>{S===o&&(T==null||T(void 0,A))})};return a.persist={setOptions:b=>{i={...i,...b},b.storage&&(h=b.storage)},clearStorage:()=>{h==null||h.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>w(),hasHydrated:()=>l,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(d.add(b),()=>{d.delete(b)})},i.skipHydration||w(),v||y},c7t=l7t,Bfe=i7t()(c7t((s,t)=>({cartItems:[],addToCart:(r,n,a=1,i)=>{s(l=>{const o=l.cartItems.findIndex(c=>{var d;return c.product.id===r.id&&((d=c.variant)==null?void 0:d.id)===(n==null?void 0:n.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:r,variant:n,quantity:a,artworkUrl:i}]}})},removeFromCart:(r,n)=>{s(a=>({cartItems:a.cartItems.filter(i=>{var l;return!(i.product.id===r&&((l=i.variant)==null?void 0:l.id)===n)})}))},updateQuantity:(r,n,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===r&&((o=l.variant)==null?void 0:o.id)===n?{...l,quantity:Math.max(1,a)}:l})}))},updateArtwork:(r,n,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===r&&((o=l.variant)==null?void 0:o.id)===n?{...l,artworkUrl:a}:l})}))},clearCart:()=>s({cartItems:[]}),getItemPrice:r=>{const n=Number(r.product.base_price),a=r.variant?Number(r.variant.price_adjustment):0;return n+a},getSubtotal:()=>{const{cartItems:r,getItemPrice:n}=t();return r.reduce((a,i)=>a+n(i)*i.quantity,0)},getShippingTotal:()=>{const{cartItems:r}=t();return r.reduce((n,a)=>n+Number(a.product.shipping_fee)*a.quantity,0)},getTotal:()=>{const{getSubtotal:r,getShippingTotal:n}=t();return r()+n()}}),{name:"marketplace-cart",partialize:s=>({cartItems:s.cartItems})}));function _g(){const{user:s}=js(),{data:t,isLoading:r}=mt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:n,error:a}=await V.from("lead_sites").select("id, subdomain_slug, site_title, is_active, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(a)throw a;return n},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:r,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const E8e="dashboard-sidebar-collapsed",ws=({children:s,title:t})=>{var it;const{user:r,signOut:n,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=js(),{isAssistant:c,actingAsAgent:d,hasPermission:h}=MCe(),{isImpersonating:m}=Yme(),y=(c&&!!d?40:0)+(m?40:0),{avatarUrl:v}=Lst(r==null?void 0:r.id),{isTrial:w,isExpired:b,expiresAt:N}=SBt(r==null?void 0:r.id),{isInnerCircleEnabled:S,isMarketplaceEnabled:T}=Dst(),{currentBrief:A,shouldShowPopup:I,hasUnseenBrief:D,openBrief:R,closeBrief:$,dismissBrief:F}=Yzt(),{unreadCount:z}=CBt(),{openCount:Q}=TBt(),{data:K}=yg(),X=!!K,re=Bfe(Oe=>Oe.cartItems).reduce((Oe,Ye)=>Oe+Ye.quantity,0),{leadSite:le,hasLeadSite:oe,siteUrl:ne}=_g(),ie=br(),ye=ec(),[ce,ve]=k.useState(null);k.useEffect(()=>{r!=null&&r.id&&V.from("profiles").select("name").eq("id",r.id).single().then(({data:Oe})=>{Oe!=null&&Oe.name&&ve(Oe.name)})},[r==null?void 0:r.id]);const be=ce||((it=r==null?void 0:r.user_metadata)==null?void 0:it.name)||(r==null?void 0:r.email)||"User",[Ue,Be]=k.useState(()=>typeof window<"u"?localStorage.getItem(E8e)==="true":!1);k.useEffect(()=>{localStorage.setItem(E8e,String(Ue))},[Ue]);const[De,Ae]=k.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),He=Oe=>{Ae(Ye=>({...Ye,[Oe]:!Ye[Oe]}))},Le=Oe=>Oe.split(" ").map(Ye=>Ye[0]).join("").toUpperCase().slice(0,2),Ie=Oe=>ye.pathname===Oe,Te=Oe=>Oe.some(Ye=>ye.pathname===Ye),xe=({path:Oe,icon:Ye,label:We,badgeCount:_e})=>{const Re=e.jsxs(G,{variant:"ghost",size:"sm",className:It("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Ie(Oe)&&"bg-sidebar-accent text-sidebar-accent-foreground",Ue?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>ie(Oe),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ye,{className:"h-4 w-4 shrink-0"}),Ue&&_e!=null&&_e>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!Ue&&We,!Ue&&_e!=null&&_e>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:_e>9?"9+":_e})]});return Ue?e.jsxs(cc,{delayDuration:0,children:[e.jsx(dc,{asChild:!0,children:Re}),e.jsxs(Gl,{side:"right",className:"flex items-center gap-2",children:[We,_e!=null&&_e>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:_e>9?"9+":_e})]})]}):Re},et=({id:Oe,label:Ye,icon:We,children:_e,activePaths:Re,showBetaBadge:tt,defaultPath:Ke,badgeCount:Ze})=>{if(Ue){const lt=Ke||Re[0];return e.jsxs(cc,{delayDuration:0,children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:It("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Te(Re)&&"text-primary"),onClick:()=>ie(lt),children:e.jsxs("div",{className:"relative",children:[e.jsx(We,{className:"h-4 w-4"}),Ze!=null&&Ze>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]})})}),e.jsxs(Gl,{side:"right",className:"flex items-center gap-2",children:[Ye,tt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600",children:"Beta"}),Ze!=null&&Ze>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ze>9?"9+":Ze})]})]})}return e.jsxs(Gp,{open:De[Oe],onOpenChange:()=>He(Oe),children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Te(Re)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(We,{className:"h-4 w-4"}),Ye,tt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[Ze!=null&&Ze>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:Ze>9?"9+":Ze}),e.jsx(Wi,{className:It("h-4 w-4 transition-transform duration-200",De[Oe]&&"rotate-180")})]})]})}),e.jsx(Kp,{className:"pl-4 space-y-1 mt-1",children:_e})]})},fe=({isMobile:Oe=!1})=>{const Ye=Oe?!1:Ue;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:It("p-3 border-b border-sidebar-border",Ye?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[Ye?e.jsx("img",{src:PBt,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:LBt,alt:"LevelUp",className:"h-8 w-auto"}),!Oe&&e.jsxs(cc,{delayDuration:0,children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Be(!Ye),children:e.jsx($o,{className:It("h-4 w-4 transition-transform duration-300",Ye&&"rotate-180")})})}),e.jsx(Gl,{side:"right",children:Ye?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(Qa,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:It("p-3 space-y-1",Ye&&"flex flex-col items-center"),children:[Oe&&w&&!b&&e.jsx("button",{type:"button",onClick:()=>ie("/subscription"),className:It("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(jr,{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?"}),N&&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(N).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(xe,{path:"/dashboard",icon:$4,label:"Dashboard"}),e.jsx(xe,{path:"/apps",icon:Bx,label:"Apps & Tools"}),Ue?e.jsxs(cc,{delayDuration:0,children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/levelup-u"),children:[e.jsx(Md,{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(Gl,{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(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/levelup-u"),children:[e.jsx(Md,{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(xe,{path:"/events",icon:hd,label:"Events"}),e.jsxs(et,{id:"agentos",label:"Agent OS",icon:cA,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"],showBetaBadge:!0,defaultPath:"/mission-control",children:[h("contacts")&&e.jsx(xe,{path:"/mission-control",icon:ci,label:"Mission Control"}),h("contacts")&&!Ye&&e.jsxs(Gp,{open:De.contacts,onOpenChange:()=>He("contacts"),children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Te(["/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(pr,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(Wi,{className:It("h-3.5 w-3.5 transition-transform duration-200",De.contacts&&"rotate-180")})]})}),e.jsxs(Kp,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(xe,{path:"/mission-control/contacts",icon:pr,label:"All Contacts"}),e.jsx(xe,{path:"/mission-control/relationship-scorecard",icon:vh,label:"Relationship Report"}),e.jsx(xe,{path:"/mission-control/sphere-gaps",icon:BR,label:"Sphere Gaps"}),e.jsx(xe,{path:"/mission-control/sent-emails",icon:en,label:"Sent Emails"}),e.jsx(xe,{path:"/mission-control/connect-page",icon:tl,label:"Connect Page"})]})]}),h("contacts")&&Ye&&e.jsx(xe,{path:"/mission-control/contacts",icon:pr,label:"Contacts"}),h("contacts")&&e.jsx(xe,{path:"/mission-control/plans",icon:hd,label:"TouchPlans"}),h("pipeline")&&e.jsx(xe,{path:"/mission-control/pipeline",icon:nv,label:"Deal Pipeline"}),h("pipeline")&&e.jsx(xe,{path:"/mission-control/tasks",icon:Z1,label:"Tasks"}),h("popbys")&&e.jsx(xe,{path:"/mission-control/popbys",icon:ii,label:"Popbys"}),h("videos")&&e.jsx(xe,{path:"/mission-control/video-library",icon:Jr,label:"Video Library"}),h("scorecard")&&e.jsx(xe,{path:"/mission-control/scorecard",icon:ro,label:"Scorecard"}),h("listings")&&e.jsx(xe,{path:"/mission-control/listings",icon:Sa,label:"Listing Exchange"}),e.jsx(xe,{path:"/mission-control/client-portals",icon:jr,label:"Client Portals"}),e.jsx(xe,{path:"/mission-control/signals",icon:jA,label:"Signals"}),!Ye&&e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/mission-control/smart-drips"),children:[e.jsx(Ku,{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"})]}),Ye&&e.jsx(xe,{path:"/mission-control/smart-drips",icon:Ku,label:"Smart Drips"})]}),oe&&le&&e.jsxs(et,{id:"website",label:"My Website",icon:fc,activePaths:[`/admin/lead-sites/${le.id}/edit`],defaultPath:`/admin/lead-sites/${le.id}/edit`,children:[Ye?e.jsxs(cc,{delayDuration:0,children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{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(ne||"#","_blank"),children:e.jsx(bn,{className:"h-4 w-4"})})}),e.jsx(Gl,{side:"right",children:"View Site"})]}):e.jsxs(G,{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(ne||"#","_blank"),children:[e.jsx(bn,{className:"h-4 w-4"}),"View Site",e.jsx(Qr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(xe,{path:`/my-website/${le.id}/edit`,icon:Ea,label:"Edit Website"}),e.jsx(xe,{path:"/my-website/mls-listings",icon:En,label:"MLS Listings"}),e.jsx(xe,{path:"/my-website/market-report",icon:ro,label:"Market Reports"}),e.jsx(xe,{path:"/mission-control/website-activity",icon:vh,label:"Website Activity"}),e.jsx(xe,{path:"/m",icon:ig,label:"Mobile Command"})]}),e.jsxs(et,{id:"marketing",label:"Marketing",icon:bu,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps"],defaultPath:"/templates",children:[e.jsx(xe,{path:"/templates",icon:fl,label:"Templates"}),e.jsx(xe,{path:"/social-swag-2",icon:ig,label:"Social Swag"}),Ue?e.jsxs(cc,{delayDuration:0,children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/newsletters"),children:[e.jsx(iv,{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(Gl,{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(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/newsletters"),children:[e.jsx(iv,{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(xe,{path:"/website-apps",icon:jr,label:"Website Apps"})]}),e.jsxs(et,{id:"learning",label:"Learning",icon:bh,activePaths:["/academy","/toolbox"],defaultPath:"/academy",children:[e.jsx(xe,{path:"/academy",icon:Md,label:"Academy"}),e.jsx(xe,{path:"/toolbox",icon:Ay,label:"Toolbox"})]}),e.jsxs(et,{id:"community",label:"Community",icon:xi,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:z,children:[e.jsx(xe,{path:"/community",icon:pr,label:"Community",badgeCount:z}),e.jsx(xe,{path:"/wishlist",icon:sj,label:"Wishlist",badgeCount:Q}),!Ye&&e.jsxs(G,{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(Qr,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(et,{id:"goods",label:"The Goods",icon:Hf,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[T&&!Ye&&e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ye.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/marketplace"),children:[e.jsx(Hf,{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"})]}),T&&Ye&&e.jsx(xe,{path:"/marketplace",icon:Hf,label:"Marketplace"}),e.jsx(xe,{path:"/reward-store",icon:Gi,label:"Reward Store"}),e.jsx(xe,{path:"/refer-friends",icon:ii,label:"Refer & Earn"})]}),e.jsxs(et,{id:"help",label:"Help & Services",icon:G1,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(xe,{path:"/support",icon:yA,label:"Support"}),e.jsx(xe,{path:"/additional-services",icon:jr,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(xe,{path:"/coaching",icon:Md,label:"Coaching"})}),e.jsx(d7t,{}),a&&e.jsxs(e.Fragment,{children:[!Ye&&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"})}),Ye?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(xe,{path:"/admin",icon:Hc,label:"Admin Dashboard"})}):e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ye.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/admin"),children:[e.jsx(Hc,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!Ye&&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"})}),Ye?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(xe,{path:"/my-brokerage",icon:Sa,label:"My Brokerage"}),e.jsx(xe,{path:"/brokerage/help-board",icon:fy,label:"Help Board"}),e.jsx(xe,{path:"/brokerage-content",icon:bh,label:"Brokerage Content"})]}),X&&!i&&e.jsx(xe,{path:"/my-team",icon:pr,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(xe,{path:"/brokerage/dashboard",icon:oo,label:"Manage Brokerages"}),e.jsx(xe,{path:"/brokerage/teams",icon:pr,label:"Teams"}),e.jsx(xe,{path:"/brokerage/recruiting",icon:bu,label:"Recruiting"}),e.jsx(xe,{path:"/brokerage/vendors",icon:Qw,label:"Vendors"}),e.jsx(xe,{path:"/brokerage-resources",icon:Gu,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/my-brokerage"),children:[e.jsx(Sa,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage/help-board"),children:[e.jsx(fy,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage-content"),children:[e.jsx(bh,{className:"h-4 w-4"}),"Brokerage Content"]})]}),X&&!i&&e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/my-team"),children:[e.jsx(pr,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage/dashboard"),children:[e.jsx(oo,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage/teams"),children:[e.jsx(pr,{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(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage/recruiting"),children:[e.jsx(bu,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage/vendors"),children:[e.jsx(Qw,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/brokerage-resources"),children:[e.jsx(Gu,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:It("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ie("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ie("/profile"),children:[e.jsx(Di,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:n,children:[e.jsx(bA,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(Ub,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[w&&b&&ye.pathname!=="/subscription"&&e.jsx(Rzt,{}),typeof document<"u"&&Vf.createPortal(e.jsx("aside",{className:It("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",Ue?"w-16":"w-56"),style:{top:`${y}px`,height:`calc(100vh - ${y}px)`},children:e.jsx(fe,{})}),document.body),e.jsxs("div",{className:It("flex-1 flex flex-col overflow-hidden transition-all duration-300",Ue?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${y}px)`,marginTop:`${y}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(Jj,{children:[e.jsx(o4e,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(G4,{className:"h-5 w-5"})})}),e.jsx(Vb,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(fe,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:DBt,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(S8e,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[w&&!b&&N&&e.jsx(Dzt,{expiresAt:N,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(S8e,{})}),A&&e.jsx(Ozt,{hasUnseenBrief:D,onClick:R}),T&&e.jsxs(G,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ie("/marketplace/cart"),children:[e.jsx(Hf,{className:"h-5 w-5"}),re>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:re>99?"99+":re})]}),e.jsx(ozt,{}),e.jsx(Fje,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",be.split(" ")[0],"!"]}),e.jsxs(Fd,{children:[e.jsx(Bd,{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(Nn,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(ya,{src:v||void 0}),e.jsx(kn,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Le(be)})]})})}),e.jsxs(xd,{align:"end",className:"w-48",children:[e.jsxs(Pa,{onClick:()=>ie("/profile"),className:"cursor-pointer",children:[e.jsx(Di,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Pa,{onClick:()=>ie("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(Z4,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Pa,{onClick:()=>ie("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(Z4,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(_v,{}),e.jsxs(Pa,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(bA,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(Xzt,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),A&&e.jsx(Kzt,{brief:A,open:I,onClose:$,onDismiss:F}),e.jsx(Zzt,{}),e.jsx(Jzt,{}),e.jsx(s7t,{})]})]})})};function d7t(){const{user:s}=js(),t=ec(),r=br(),{data:n}=mt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await V.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!n)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(G,{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:()=>r("/my-coach"),children:[e.jsx(Md,{className:"h-4 w-4"}),"My Coach"]})})}const u7t=()=>{const{user:s}=js(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(""),o=async m=>{var x;if(!(s!=null&&s.email)){ue.error("Please sign in to upgrade");return}r(!0),a(m);try{const{data:y,error:v}=await V.functions.invoke("create-checkout",{body:{tier:m,email:s.email,name:((x=s.user_metadata)==null?void 0:x.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(v)throw v;if(y!=null&&y.url)window.open(y.url,"_blank","noopener,noreferrer"),ue.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(y){console.error("Checkout error:",y),ue.error(y.message||"Failed to start checkout. Please try again.")}finally{r(!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"],h=["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(ws,{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(he,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(Ne,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:m=>l(m.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(ke,{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(pr,{className:"h-7 w-7 text-primary"})}),e.jsx(Dt,{className:"text-xl",children:"Individual Agent"}),e.jsx(Nr,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Pe,{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((m,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Kn,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},x))}),e.jsxs(G,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&n==="individual_agent"?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ke,{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(Sa,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Dt,{className:"text-xl",children:"Brokerage"}),e.jsx(Nr,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Pe,{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((m,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Kn,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},x))}),e.jsxs(G,{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&&n==="brokerage_under_25"?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(ke,{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(Sa,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Dt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Nr,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Pe,{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:h.map((m,x)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Kn,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:m})]},x))}),e.jsxs(G,{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&&n==="brokerage_over_25"?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(ke,{className:"bg-muted/50",children:e.jsxs(Pe,{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(Cn,{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"})]})]})]})})]})})},h7t=()=>{const{user:s,loading:t,isBrokerageManager:r,brokerageId:n}=js(),a=br(),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(!1);k.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),k.useEffect(()=>{!t&&s&&n&&a("/profile?setup=true")},[s,t,n,a]);const m=async()=>{if(!i.trim()){ue.error("Please enter a brokerage name");return}const{data:x}=await V.auth.getSession(),y=x.session;if(!s||!y){ue.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!y,userId:s==null?void 0:s.id});const{data:v,error:w}=await V.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:v,error:w}),w)throw w;if(!(v!=null&&v.ok))throw new Error((v==null?void 0:v.error)||"Failed to create brokerage");c(!1),h(!0),ue.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(v){console.error("Error creating brokerage:",v),ue.error(v.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(ke,{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(es,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Dt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Nr,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(di,{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(es,{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(ke,{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(Sa,{className:"w-10 h-10 text-primary"})}),e.jsx(Dt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Nr,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(Ne,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:x=>l(x.target.value),onKeyDown:x=>x.key==="Enter"&&m()}),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(pr,{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(di,{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(di,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(di,{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(di,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(G,{onClick:m,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(Ha,{className:"w-4 h-4 ml-2"})]})]})]})})},A8e=()=>{const s=br(),[t,r]=k.useState("verifying"),[n,a]=k.useState("");k.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await V.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await V.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"),r("already_claimed");return}console.log("User logged in successfully:",o.user.email),r("success");try{await V.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(h){console.log("Trial claim hook (non-critical):",h)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{r("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),r("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(ke,{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(Dt,{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(Nr,{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"&&n]})]}),(t==="already_claimed"||t==="error")&&e.jsx(Pe,{children:e.jsx(G,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},m7t=()=>{const[s,t]=k.useState(!1),r=k.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),n=k.useMemo(()=>{if(!r)return!1;try{const i=new URL(r);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);k.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!n||!r||(t(!0),window.location.href=r)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:HCe,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(ke,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx(Dt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Nr,{className:"text-gray-600 pt-2",children:n?"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(Pe,{className:"space-y-4",children:[n?e.jsx(G,{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(G,{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."})]})]})]})})]})},f7t=()=>{const s=br(),[t]=Ac(),[r,n]=k.useState(t.get("code")||""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(!1),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(null),[A,I]=k.useState(null),[D,R]=k.useState(null),[$,F]=k.useState(null);k.useEffect(()=>{const X=t.get("code");X&&(n(X),z(X))},[t]);const z=async X=>{w(!0);const{data:Z,error:re}=await V.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",X.toUpperCase().trim()).single();if(re||!Z){ue.error("Invalid invite code"),w(!1);return}if(!Z.is_active){ue.error("This invite code is no longer active"),w(!1);return}if(Z.max_uses&&Z.uses_count>=Z.max_uses){ue.error("This invite code has reached its maximum uses"),w(!1);return}if(Z.expires_at&&new Date(Z.expires_at){X.preventDefault(),z(r)},K=async X=>{var Z;if(X.preventDefault(),!c.trim()){ue.error("Please enter your name");return}if(l.length<6){ue.error("Password must be at least 6 characters");return}y(!0);try{const re=`${window.location.origin}/`,{data:le,error:oe}=await V.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:re,data:{name:c.trim()}}});if(oe){oe.message.includes("already registered")?ue.error("This email is already registered. Please sign in instead."):ue.error(oe.message);return}le.user&&(await V.rpc("add_default_signup_tag",{user_id:le.user.id}),A?await V.functions.invoke("assign-brokerage",{body:{userId:le.user.id,brokerageId:A}}):$?await V.functions.invoke("assign-brokerage",{body:{userId:le.user.id,trialDays:$}}):await V.functions.invoke("assign-brokerage",{body:{userId:le.user.id,grandfathered:!0}}),S&&await V.from("invite_codes").update({uses_count:((Z=(await V.from("invite_codes").select("uses_count").eq("id",S).single()).data)==null?void 0:Z.uses_count)+1}).eq("id",S),ue.success("Account created! You can now access the dashboard."),s("/dashboard"))}catch(re){console.error("Signup error:",re),ue.error("An unexpected error occurred")}finally{y(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsx(Dt,{className:"text-2xl font-bold text-primary",children:D?`Join ${D}`:"Join LevelUp"}),e.jsx(Nr,{children:b?D?`Create your account to join ${D}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Pe,{children:b?e.jsxs("form",{onSubmit:K,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Full Name"}),e.jsx(Ne,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:X=>d(X.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:X=>i(X.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{id:"password",type:h?"text":"password",placeholder:"••••••••",value:l,onChange:X=>o(X.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:()=>m(!h),children:h?e.jsx(Xh,{className:"h-4 w-4"}):e.jsx(bn,{className:"h-4 w-4"})})]})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:Q,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(Ne,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:r,onChange:X=>n(X.target.value),required:!0,autoFocus:!0})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},zfe=()=>{const{user:s,isCoach:t}=js();return mt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:r,error:n}=await V.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return r}})},p7t=()=>{const{data:s}=zfe();return mt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(r)throw r;const n=t||[];if(n.length===0)return[];const a=n.map(o=>o.agent_id),{data:i}=await V.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return n.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},x7t=()=>{const{user:s}=js();return mt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(r)throw r;const n=(t||[])[0];if(!n)return null;const{data:a}=await V.from("coaches").select("*").eq("id",n.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await V.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...n,coach:a,coachProfile:i}}})},g7t=s=>mt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return null;const{data:n}=await V.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:n}}}),krt=s=>mt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(r)throw r;return t||[]}}),Srt=s=>mt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:r}=await V.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(r)throw r;return t||[]}}),y7t=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function v7t(){const s=br(),{data:t,isLoading:r}=zfe(),{data:n=[],isLoading:a}=p7t();if(r)return e.jsx(ws,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(ws,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Md,{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."})]})});y7t.map(l=>({...l,items:n.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=n.filter(l=>l.status==="active").length;return e.jsx(ws,{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(jr,{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(Uve,{icon:Md,label:"Active agents",value:i}),e.jsx(Uve,{icon:hd,label:"This month",value:"—"}),e.jsx(Uve,{icon:mc,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(G,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):n.length===0?e.jsx(ke,{children:e.jsx(Pe,{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:n.map(l=>{var o,c,d,h;return e.jsx(ke,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Pe,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Nn,{className:"h-14 w-14",children:[e.jsx(ya,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(kn,{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(Ha,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(h=l.agent)==null?void 0:h.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(Ge,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",rl(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function Uve({icon:s,label:t,value:r}){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:r}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}var $fe="Tabs",[b7t,RUs]=pd($fe,[Yj]),Crt=Yj(),[_7t,t3e]=b7t($fe),Trt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,h=Kj(o),[m,x]=Sh({prop:n,onChange:a,defaultProp:i??"",caller:$fe});return e.jsx(_7t,{scope:r,baseId:Yu(),value:m,onValueChange:x,orientation:l,dir:h,activationMode:c,children:e.jsx(wn.div,{dir:h,"data-orientation":l,...d,ref:t})})});Trt.displayName=$fe;var Ert="TabsList",Art=k.forwardRef((s,t)=>{const{__scopeTabs:r,loop:n=!0,...a}=s,i=t3e(Ert,r),l=Crt(r);return e.jsx(Xme,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:n,children:e.jsx(wn.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});Art.displayName=Ert;var Mrt="TabsTrigger",Irt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,disabled:a=!1,...i}=s,l=t3e(Mrt,r),o=Crt(r),c=Drt(l.baseId,n),d=Rrt(l.baseId,n),h=n===l.value;return e.jsx(Qme,{asChild:!0,...o,focusable:!a,active:h,children:e.jsx(wn.button,{type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:Vr(s.onMouseDown,m=>{!a&&m.button===0&&m.ctrlKey===!1?l.onValueChange(n):m.preventDefault()}),onKeyDown:Vr(s.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&l.onValueChange(n)}),onFocus:Vr(s.onFocus,()=>{const m=l.activationMode!=="manual";!h&&!a&&m&&l.onValueChange(n)})})})});Irt.displayName=Mrt;var Lrt="TabsContent",Prt=k.forwardRef((s,t)=>{const{__scopeTabs:r,value:n,forceMount:a,children:i,...l}=s,o=t3e(Lrt,r),c=Drt(o.baseId,n),d=Rrt(o.baseId,n),h=n===o.value,m=k.useRef(h);return k.useEffect(()=>{const x=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(x)},[]),e.jsx(ru,{present:a||h,children:({present:x})=>e.jsx(wn.div,{"data-state":h?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!x,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:m.current?"0s":void 0},children:x&&i})})});Prt.displayName=Lrt;function Drt(s,t){return`${s}-trigger-${t}`}function Rrt(s,t){return`${s}-content-${t}`}var w7t=Trt,Ort=Art,Frt=Irt,Brt=Prt;const On=w7t,Rn=k.forwardRef(({className:s,...t},r)=>e.jsx(Ort,{ref:r,className:It("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Rn.displayName=Ort.displayName;const Kt=k.forwardRef(({className:s,...t},r)=>e.jsx(Frt,{ref:r,className:It("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=Frt.displayName;const ts=k.forwardRef(({className:s,...t},r)=>e.jsx(Brt,{ref:r,className:It("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));ts.displayName=Brt.displayName;function zrt({assignmentId:s}){const{user:t}=js(),r=Xt(),[n,a]=k.useState(""),[i,l]=k.useState(!1),o=k.useRef(null),{data:c=[]}=mt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await V.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(m)throw m;return h||[]}});k.useEffect(()=>{if(!s)return;const h=V.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>r.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{V.removeChannel(h)}},[s,r]),k.useEffect(()=>{var h;(h=o.current)==null||h.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const h=n.trim();if(!h||!t)return;l(!0);const{error:m}=await V.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:h});l(!1),m||a("")};return e.jsxs(ke,{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(h=>{const m=h.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:It("flex gap-2",m?"justify-end":"justify-start"),children:[!m&&e.jsx(Nn,{className:"h-8 w-8 mt-1",children:e.jsx(kn,{className:"text-xs",children:(h.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:It("max-w-[75%] rounded-2xl px-3 py-2 text-sm",m?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:h.body}),e.jsx("p",{className:It("text-[10px] mt-1",m?"text-white/70":"text-muted-foreground"),children:rl(new Date(h.created_at),{addSuffix:!0})})]})]},h.id)})}),e.jsx(Pe,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(or,{value:n,onChange:h=>a(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx(G,{onClick:d,disabled:i||!n.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(en,{className:"h-4 w-4"})})]})})]})}var s3e="Progress",r3e=100,[j7t,OUs]=pd(s3e),[N7t,k7t]=j7t(s3e),$rt=k.forwardRef((s,t)=>{const{__scopeProgress:r,value:n=null,max:a,getValueLabel:i=S7t,...l}=s;(a||a===0)&&!M8e(a)&&console.error(C7t(`${a}`,"Progress"));const o=M8e(a)?a:r3e;n!==null&&!I8e(n,o)&&console.error(T7t(`${n}`,"Progress"));const c=I8e(n,o)?n:null,d=Gde(c)?i(c,o):void 0;return e.jsx(N7t,{scope:r,value:c,max:o,children:e.jsx(wn.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":Gde(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":Vrt(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});$rt.displayName=s3e;var Urt="ProgressIndicator",qrt=k.forwardRef((s,t)=>{const{__scopeProgress:r,...n}=s,a=k7t(Urt,r);return e.jsx(wn.div,{"data-state":Vrt(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...n,ref:t})});qrt.displayName=Urt;function S7t(s,t){return`${Math.round(s/t*100)}%`}function Vrt(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function Gde(s){return typeof s=="number"}function M8e(s){return Gde(s)&&!isNaN(s)&&s>0}function I8e(s,t){return Gde(s)&&!isNaN(s)&&s<=t&&s>=0}function C7t(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${r3e}\`.`}function T7t(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 ${r3e} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var Hrt=$rt,E7t=qrt;const ei=k.forwardRef(({className:s,value:t,...r},n)=>e.jsx(Hrt,{ref:n,className:It("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...r,children:e.jsx(E7t,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ei.displayName=Hrt.displayName;function Grt({agentUserId:s}){const t=new Date().getFullYear(),r=`${t}-01-01`,n=`${t}-12-31`,{data:a=[]}=mt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:w,error:b}=await V.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",r).lte("close_date",n);if(b)throw b;return w||[]}}),{data:i}=mt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:w}=await V.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return w}}),l=a.filter(w=>w.is_win),o=l.length,c=l.reduce((w,b)=>w+(Number(b.sale_price)||0),0),d=l.reduce((w,b)=>w+(Number(b.commission_amount)||0),0),h=i,m=(h==null?void 0:h.transactions_goal)||0,x=(h==null?void 0:h.volume_goal)||0,y=(h==null?void 0:h.gci_goal)||0,v=w=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(w);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(bo,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(qve,{icon:Yl,label:"Transactions",value:o.toString(),goal:m,current:o,suffix:m?`/ ${m}`:""}),e.jsx(qve,{icon:bo,label:"Volume",value:v(c),goal:x,current:c,suffix:x?`of ${v(x)}`:""}),e.jsx(qve,{icon:wl,label:"GCI",value:v(d),goal:y,current:d,suffix:y?`of ${v(y)}`:""})]}),o===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function qve({icon:s,label:t,value:r,goal:n,current:a,suffix:i}){const l=n>0?Math.min(100,a/n*100):0;return e.jsx(ke,{children:e.jsxs(Pe,{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:r}),n>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(ei,{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 Wrt({assignmentId:s,canEdit:t}){const r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState(null),{data:o=[]}=mt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:h}=await V.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(h)throw h;return d||[]}}),c=()=>r.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(Pd,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(G,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const h=Number(d.target_value||0),m=Number(d.current_value||0),x=h>0?Math.min(100,m/h*100):0;return e.jsx(ke,{children:e.jsxs(Pe,{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(Ge,{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(G,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})})]}),h>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:[m.toLocaleString()," / ",h.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[x.toFixed(0),"%"]})]}),e.jsx(ei,{value:x})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",_s(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(A7t,{open:n,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function A7t({open:s,onOpenChange:t,assignmentId:r,goal:n,onSaved:a}){var A,I;const[i,l]=k.useState((n==null?void 0:n.title)||""),[o,c]=k.useState((n==null?void 0:n.description)||""),[d,h]=k.useState((n==null?void 0:n.target_metric)||""),[m,x]=k.useState(((A=n==null?void 0:n.target_value)==null?void 0:A.toString())||""),[y,v]=k.useState(((I=n==null?void 0:n.current_value)==null?void 0:I.toString())||"0"),[w,b]=k.useState((n==null?void 0:n.due_date)||""),[N,S]=k.useState(!1);k.useState(()=>{var D,R;l((n==null?void 0:n.title)||""),c((n==null?void 0:n.description)||""),h((n==null?void 0:n.target_metric)||""),x(((D=n==null?void 0:n.target_value)==null?void 0:D.toString())||""),v(((R=n==null?void 0:n.current_value)==null?void 0:R.toString())||"0"),b((n==null?void 0:n.due_date)||"")});const T=async()=>{if(!i.trim())return;S(!0);const D={assignment_id:r,title:i,description:o||null,target_metric:d||null,target_value:m?Number(m):null,current_value:y?Number(y):0,due_date:w||null},{error:R}=n!=null&&n.id?await V.from("coaching_goals").update(D).eq("id",n.id):await V.from("coaching_goals").insert(D);if(S(!1),R)return ue.error(R.message);ue.success(n!=null&&n.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:n!=null&&n.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{placeholder:"Title",value:i,onChange:D=>l(D.target.value)}),e.jsx(or,{placeholder:"Description (optional)",rows:2,value:o,onChange:D=>c(D.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(Ne,{placeholder:"transactions",value:d,onChange:D=>h(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(Ne,{type:"number",value:m,onChange:D=>x(D.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(Ne,{type:"number",value:y,onChange:D=>v(D.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(Ne,{type:"date",value:w,onChange:D=>b(D.target.value)})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:T,disabled:N,children:n!=null&&n.id?"Save":"Create"})]})]})})}function Krt({assignmentId:s}){const t=Xt(),{user:r}=js(),n=k.useRef(null),[a,i]=k.useState(!1),{data:l=[]}=mt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:m,error:x}=await V.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(x)throw x;return m||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async m=>{var y;const x=(y=m.target.files)==null?void 0:y[0];if(!(!x||!r)){i(!0);try{const v=`${s}/${Date.now()}-${x.name}`,{error:w}=await V.storage.from("coaching-files").upload(v,x);if(w)throw w;const{error:b}=await V.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:r.id,file_url:v,file_name:x.name,file_size_bytes:x.size,mime_type:x.type});if(b)throw b;ue.success("File uploaded"),o()}catch(v){ue.error(v.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}}},d=async m=>{const{data:x,error:y}=await V.storage.from("coaching-files").createSignedUrl(m.file_url,60);if(y||!x)return ue.error("Could not get download link");window.open(x.signedUrl,"_blank")},h=async m=>{confirm("Delete this file?")&&(await V.storage.from("coaching-files").remove([m.file_url]),await V.from("coaching_shared_files").delete().eq("id",m.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(G,{size:"sm",onClick:()=>{var m;return(m=n.current)==null?void 0:m.click()},disabled:a,children:[e.jsx(da,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:n,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(m=>e.jsx(ke,{children:e.jsxs(Pe,{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(ln,{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:m.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.file_size_bytes?`${(m.file_size_bytes/1024).toFixed(0)} KB · `:"",_s(new Date(m.created_at),"PP")]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>d(m),children:e.jsx(Ya,{className:"h-4 w-4"})}),m.uploaded_by===(r==null?void 0:r.id)&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h(m),children:e.jsx(yr,{className:"h-4 w-4"})})]})},m.id))})]})}function M7t(){var x,y,v,w;const{id:s}=Ki(),t=br(),r=Xt(),{data:n,isLoading:a}=g7t(s),{data:i=[]}=krt(s),{data:l=[]}=Srt(s),[o,c]=k.useState(!1),[d,h]=k.useState(!1);if(a)return e.jsx(ws,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!n)return e.jsx(ws,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const m=n;return e.jsxs(ws,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Pe,{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(Nn,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(ya,{src:((x=m.agent)==null?void 0:x.avatar_url)||void 0}),e.jsx(kn,{className:"text-2xl",children:(((y=m.agent)==null?void 0:y.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((v=m.agent)==null?void 0:v.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(w=m.agent)==null?void 0:w.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Ge,{variant:"secondary",className:"capitalize",children:(m.pipeline_stage||"active").replace("_"," ")}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:m.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(I7t,{value:m.pipeline_stage||"active",onChange:async b=>{await V.from("coaching_assignments").update({pipeline_stage:b}).eq("id",m.id),r.invalidateQueries({queryKey:["coaching-assignment",m.id]}),r.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs(On,{defaultValue:"sessions",children:[e.jsxs(Rn,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Kt,{value:"sessions",children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Kt,{value:"actions",children:[e.jsx(pb,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Kt,{value:"goals",children:[e.jsx(Pd,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Kt,{value:"kpis",children:[e.jsx(bo,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Kt,{value:"messages",children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Kt,{value:"files",children:[e.jsx(Qh,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Kt,{value:"notes",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(ts,{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(G,{size:"sm",onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(b=>e.jsx(ke,{children:e.jsx(Pe,{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:_s(new Date(b.scheduled_at),"PPp")}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:b.status}),b.template&&e.jsx(Ge,{variant:"secondary",children:b.template})]}),b.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:b.summary}),b.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(Hc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:b.private_notes})]})]})})})},b.id))})]}),e.jsxs(ts,{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(G,{size:"sm",onClick:()=>h(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(b=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 flex items-center gap-3",children:[e.jsx(Si,{checked:b.status==="done",onCheckedChange:async N=>{await V.from("coaching_action_items").update({status:N?"done":"open",completed_at:N?new Date().toISOString():null}).eq("id",b.id),r.invalidateQueries({queryKey:["coaching-action-items",m.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx(Ge,{variant:"outline",children:_s(new Date(b.due_date),"MMM d")}),e.jsx(Ge,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))})]}),e.jsx(ts,{value:"goals",children:e.jsx(Wrt,{assignmentId:m.id,canEdit:!0})}),e.jsx(ts,{value:"kpis",children:m.agent_id&&e.jsx(Grt,{agentUserId:m.agent_id})}),e.jsx(ts,{value:"messages",children:e.jsx(zrt,{assignmentId:m.id})}),e.jsx(ts,{value:"files",children:e.jsx(Krt,{assignmentId:m.id})}),e.jsx(ts,{value:"notes",className:"space-y-4",children:e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(L7t,{open:o,onOpenChange:c,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-sessions",m.id]})}),e.jsx(P7t,{open:d,onOpenChange:h,assignmentId:m.id,onSaved:()=>r.invalidateQueries({queryKey:["coaching-action-items",m.id]})})]})}function I7t({value:s,onChange:t}){return e.jsxs(Is,{value:s,onValueChange:t,children:[e.jsx(As,{className:"w-40",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"onboarding",children:"Onboarding"}),e.jsx(ct,{value:"active",children:"Active"}),e.jsx(ct,{value:"thriving",children:"Thriving"}),e.jsx(ct,{value:"at_risk",children:"At Risk"}),e.jsx(ct,{value:"graduated",children:"Graduated"})]})]})}function L7t({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=k.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=k.useState(60),[c,d]=k.useState("weekly_1on1"),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(!1),[b,N]=k.useState(!0),[S,T]=k.useState(null),[A,I]=k.useState(!1),D=async()=>{I(!0);const{data:$,error:F}=await V.functions.invoke("coaching-prep-brief",{body:{assignmentId:r}});if(I(!1),F||$!=null&&$.error)return ue.error(($==null?void 0:$.error)||(F==null?void 0:F.message)||"Failed to generate brief");T($.brief||"No brief returned.")},R=async()=>{w(!0);const{data:$,error:F}=await V.from("coaching_sessions").insert({assignment_id:r,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:h,private_notes:x,status:"completed"}).select("id").maybeSingle();if(F)return w(!1),ue.error(F.message);if(ue.success("Session saved"),b&&h.trim()&&($!=null&&$.id)){const{error:z}=await V.functions.invoke("coaching-send-recap",{body:{sessionId:$.id}});z?ue.error("Saved, but recap email failed: "+z.message):ue.success("Recap emailed to agent")}w(!1),n==null||n(),t(!1),m(""),y(""),T(null)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(gs,{children:"New Session"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:D,disabled:A,children:[A?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[S&&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(jr,{className:"h-3 w-3"})," AI Brief"]}),S]}),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(Ne,{type:"datetime-local",value:a,onChange:$=>i($.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(Ne,{type:"number",value:l,onChange:$=>o(Number($.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(Is,{value:c,onValueChange:d,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(ct,{value:"grow",children:"GROW Model"}),e.jsx(ct,{value:"goal_review",children:"Goal Review"}),e.jsx(ct,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(or,{rows:4,value:h,onChange:$=>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(Hc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(or,{rows:3,value:x,onChange:$=>y($.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(Si,{checked:b,onCheckedChange:$=>N(!!$)}),e.jsx(en,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:R,disabled:v,children:[e.jsx(Bl,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function P7t({open:s,onOpenChange:t,assignmentId:r,onSaved:n}){const[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState("medium"),[x,y]=k.useState(!1),v=async()=>{if(!a.trim())return;y(!0);const{error:w}=await V.from("coaching_action_items").insert({assignment_id:r,title:a,description:l||null,due_date:c||null,priority:h});if(y(!1),w)return ue.error(w.message);ue.success("Action item added"),n==null||n(),t(!1),i(""),o(""),d("")};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{placeholder:"Title",value:a,onChange:w=>i(w.target.value)}),e.jsx(or,{rows:3,placeholder:"Description (optional)",value:l,onChange:w=>o(w.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(Ne,{type:"date",value:c,onChange:w=>d(w.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(Is,{value:h,onValueChange:m,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"low",children:"Low"}),e.jsx(ct,{value:"medium",children:"Medium"}),e.jsx(ct,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:v,disabled:x,children:"Add"})]})]})})}function Uje({value:s,size:t=16,onChange:r}){return e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(n),disabled:!r,className:r?"cursor-pointer":"cursor-default",children:e.jsx(Xn,{style:{width:t,height:t},className:n<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},n))})}function D7t({coachId:s}){const[t,r]=k.useState([]),[n,a]=k.useState(!0);k.useEffect(()=>{(async()=>{const{data:l}=await V.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(m=>m.agent_id),{data:d}=await V.from("profiles").select("id, name, avatar_url").in("id",c),h=new Map((d||[]).map(m=>[m.id,m]));o.forEach(m=>m.profile=h.get(m.agent_id))}r(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return n||!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(Uje,{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(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Nn,{className:"h-9 w-9",children:[e.jsx(ya,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(kn,{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(Uje,{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 R7t({coachId:s,assignmentId:t}){const{user:r}=js(),[n,a]=k.useState(null),[i,l]=k.useState(0),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(!1);k.useEffect(()=>{r&&(async()=>{const{data:v}=await V.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",r.id).maybeSingle();v&&(a(v),l(v.rating),c(v.title||""),h(v.body||""))})()},[r,s]);const y=async()=>{if(!r)return;if(!i)return ue.error("Pick a rating");x(!0);const v={coach_id:s,agent_id:r.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:w}=n?await V.from("coaching_reviews").update(v).eq("id",n.id):await V.from("coaching_reviews").insert(v);if(x(!1),w)return ue.error(w.message);ue.success("Thanks for your review!"),a({...v,id:n==null?void 0:n.id})};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:n?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx(Uje,{value:i,size:28,onChange:l}),e.jsx(Ne,{placeholder:"Title (optional)",value:o,onChange:v=>c(v.target.value)}),e.jsx(or,{rows:4,placeholder:"What was your experience like?",value:d,onChange:v=>h(v.target.value)}),e.jsx(G,{onClick:y,disabled:m,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:m?"Saving…":n?"Update review":"Submit review"})]})})}function O7t(){var m,x,y,v,w,b;const{user:s}=js(),{data:t,isLoading:r,refetch:n}=x7t(),a=Xt(),i=t==null?void 0:t.id,{data:l=[]}=krt(i),{data:o=[]}=Srt(i);if(k.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&V.functions.invoke("coaching-verify-checkout").then(()=>{n(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[n,a]),r)return e.jsx(ws,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(ws,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Md,{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(N=>N.status!=="done"),h=o.length-d.length;return e.jsx(ws,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(ke,{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(Nn,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(ya,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(kn,{className:"text-2xl bg-white/20 text-white",children:(((x=c.coachProfile)==null?void 0:x.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(jr,{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:((y=c.coachProfile)==null?void 0:y.name)||"Your Coach"}),((v=c.coach)==null?void 0:v.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((w=c.coach)==null?void 0:w.is_certified)&&e.jsx(Ge,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Ge,{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(Vve,{icon:pb,label:"Open action items",value:d.length}),e.jsx(Vve,{icon:Pd,label:"Completed",value:h}),e.jsx(Vve,{icon:on,label:"Sessions",value:l.length})]}),((b=c.coach)==null?void 0:b.id)&&e.jsx(R7t,{coachId:c.coach.id,assignmentId:i}),e.jsxs(On,{defaultValue:"actions",children:[e.jsxs(Rn,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Kt,{value:"actions",children:[e.jsx(pb,{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(on,{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(Pd,{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(bo,{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(xi,{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(Qh,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(ts,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(N=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 flex items-center gap-3",children:[e.jsx(Si,{checked:N.status==="done",onCheckedChange:async S=>{await V.from("coaching_action_items").update({status:S?"done":"open",completed_at:S?new Date().toISOString():null}).eq("id",N.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:N.status==="done"?"line-through text-muted-foreground":"font-medium",children:N.title}),N.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:N.description})]}),N.due_date&&e.jsx(Ge,{variant:"outline",children:_s(new Date(N.due_date),"MMM d")}),e.jsx(Ge,{variant:"secondary",className:"capitalize",children:N.priority})]})},N.id))}),e.jsx(ts,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(N=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:_s(new Date(N.scheduled_at),"PPp")}),e.jsx(Ge,{variant:"outline",className:"capitalize",children:N.status})]}),N.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},N.id))}),e.jsx(ts,{value:"goals",children:e.jsx(Wrt,{assignmentId:i,canEdit:!1})}),e.jsx(ts,{value:"kpis",children:s&&e.jsx(Grt,{agentUserId:s.id})}),e.jsx(ts,{value:"messages",children:e.jsx(zrt,{assignmentId:i})}),e.jsx(ts,{value:"files",children:e.jsx(Krt,{assignmentId:i})})]})]})})}function Vve({icon:s,label:t,value:r}){return e.jsx(ke,{children:e.jsxs(Pe,{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:r}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}function F7t(){const s=Xt(),[t,r]=k.useState(""),[n,a]=k.useState([]),[i,l]=k.useState(null),{data:o=[],isLoading:c}=mt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:m,error:x}=await V.from("coaches").select("*").order("created_at",{ascending:!1});if(x)throw x;if(!(m!=null&&m.length))return[];const y=m.map(b=>b.user_id),{data:v}=await V.from("profiles").select("id, name, email, avatar_url").in("id",y),w=new Map((v||[]).map(b=>[b.id,b]));return m.map(b=>({...b,profile:w.get(b.user_id)}))}});k.useEffect(()=>{const m=t.trim();if(m.length<2){a([]);return}const x=setTimeout(async()=>{const{data:y}=await V.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${m}%,name.ilike.%${m}%`).limit(10);a(y||[])},250);return()=>clearTimeout(x)},[t]);const d=async m=>{const{error:x}=await V.functions.invoke("manage-user-roles",{body:{userId:m.id,role:"coach",action:"add"}});if(x)return ue.error(x.message);const{error:y}=await V.from("coaches").insert({user_id:m.id});if(y&&!String(y.message).includes("duplicate"))return ue.error(y.message);ue.success(`${m.name||m.email} is now a coach`),r(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},h=async(m,x)=>{const{error:y}=await V.from("coaches").update({is_certified:x}).eq("id",m);if(y)return ue.error(y.message);ue.success(x?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(ws,{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(Md,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(B7t,{}),e.jsx($7t,{}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsx(Ne,{placeholder:"Search by user email or name…",value:t,onChange:m=>r(m.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:n.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):n.map(m=>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:m.name||m.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:m.email})]}),e.jsxs(G,{size:"sm",onClick:()=>d(m),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},m.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(ke,{children:e.jsx(Pe,{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(m=>{var x,y,v;return e.jsx(ke,{children:e.jsxs(Pe,{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:((x=m.profile)==null?void 0:x.name)||((y=m.profile)==null?void 0:y.email)||m.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(v=m.profile)==null?void 0:v.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[m.is_certified&&e.jsxs(Ge,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Certified"]}),m.accepting_clients&&e.jsx(Ge,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>l(m.id),children:[e.jsx(sl,{className:"h-4 w-4 mr-1"})," Assign"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm pt-2 border-t",children:[e.jsx("span",{className:"text-muted-foreground",children:"LevelUp Certified"}),e.jsx(_r,{checked:m.is_certified,onCheckedChange:w=>h(m.id,w)})]})]})},m.id)})})]})]}),e.jsx(z7t,{coachId:i,onClose:()=>l(null)})]})}function B7t(){const[s,t]=k.useState("1500"),[r,n]=k.useState(!1),[a,i]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:c}=await V.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 ue.error("Enter a value between 0 and 5000 bps (0–50%)");n(!0);const{error:d}=await V.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(n(!1),d)return ue.error(d.message);ue.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y4,{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(he,{children:"Fee (bps)"}),e.jsx(Ne,{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(G,{onClick:l,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:r?"Saving…":"Save"})]})]})})}function z7t({coachId:s,onClose:t}){const[r,n]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=Xt();k.useEffect(()=>{if(!s){n(""),i([]);return}},[s]),k.useEffect(()=>{const h=r.trim();if(h.length<2){i([]);return}o(!0);const m=setTimeout(async()=>{const{data:x}=await V.from("profiles").select("id, name, email").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(15);i(x||[]),o(!1)},250);return()=>clearTimeout(m)},[r]);const d=async h=>{const{error:m}=await V.from("coaching_assignments").insert({coach_id:s,agent_id:h,status:"active",source:"admin",pipeline_stage:"onboarding"});if(m)return ue.error(m.message);ue.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(fs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Assign Agent"})}),e.jsx(Ne,{placeholder:"Search agents by name or email…",value:r,onChange:h=>n(h.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:r.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(h=>e.jsxs("button",{onClick:()=>d(h.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]},h.id))}),e.jsx(an,{children:e.jsx(G,{variant:"outline",onClick:t,children:"Close"})})]})})}function $7t(){const s=Xt(),[t,r]=k.useState("pending"),[n,a]=k.useState(null),{data:i=[],isLoading:l}=mt({queryKey:["coach-applications",t],queryFn:async()=>{let h=V.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(h=h.eq("status",t));const{data:m,error:x}=await h;if(x)throw x;return m||[]}}),{data:o=0}=mt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:h}=await V.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return h||0}}),c=async(h,m)=>{const{error:x}=await V.from("coach_applications").update({status:m,reviewed_at:new Date().toISOString()}).eq("id",h);if(x)return ue.error(x.message);ue.success(`Marked ${m}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=h=>h==="approved"?e.jsxs(Ge,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(Kn,{className:"h-3 w-3 mr-1"}),"Approved"]}):h==="rejected"?e.jsxs(Ge,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Ge,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(fn,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(ke,{children:[e.jsxs(Pe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(ej,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Ge,{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(h=>e.jsx(G,{size:"sm",variant:t===h?"default":"outline",onClick:()=>r(h),className:t===h?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:h.charAt(0).toUpperCase()+h.slice(1)},h))})]}),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(h=>e.jsx("button",{onClick:()=>a(h),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:h.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"}),h.email]}),h.brokerage&&e.jsxs("span",{children:["· ",h.brokerage]}),h.years_experience&&e.jsxs("span",{children:["· ",h.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(h.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(h.created_at).toLocaleDateString()})]})]})},h.id))})]}),e.jsx(fs,{open:!!n,onOpenChange:h=>!h&&a(null),children:e.jsx(ms,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:n&&e.jsxs(e.Fragment,{children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-3",children:[n.full_name,d(n.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(ZT,{icon:Vs,label:"Email",value:n.email,link:`mailto:${n.email}`}),n.phone&&e.jsx(ZT,{icon:Cn,label:"Phone",value:n.phone,link:`tel:${n.phone}`}),n.brokerage&&e.jsx(ZT,{label:"Brokerage",value:n.brokerage}),n.years_experience&&e.jsx(ZT,{label:"Years",value:n.years_experience}),n.website_url&&e.jsx(ZT,{icon:Qr,label:"Website",value:n.website_url,link:n.website_url}),n.linkedin_url&&e.jsx(ZT,{icon:Qr,label:"LinkedIn",value:n.linkedin_url,link:n.linkedin_url})]}),n.specialties&&e.jsx(Hve,{label:"Specialties",children:n.specialties}),e.jsx(Hve,{label:"Why they want to coach",children:n.why_coach}),n.results_story&&e.jsx(Hve,{label:"Results story",children:n.results_story}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(or,{defaultValue:n.admin_notes||"",rows:3,onBlur:async h=>{const m=h.target.value;m!==(n.admin_notes||"")&&(await V.from("coach_applications").update({admin_notes:m}).eq("id",n.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(an,{className:"gap-2 flex-wrap",children:[n.status!=="rejected"&&e.jsxs(G,{variant:"outline",onClick:()=>c(n.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(vr,{className:"h-4 w-4 mr-1"})," Reject"]}),n.status!=="pending"&&e.jsxs(G,{variant:"outline",onClick:()=>c(n.id,"pending"),children:[e.jsx(fn,{className:"h-4 w-4 mr-1"})," Move to pending"]}),n.status!=="approved"&&e.jsxs(G,{onClick:()=>c(n.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Kn,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function ZT({icon:s,label:t,value:r,link:n}){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"}),r]});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:n?e.jsx("a",{href:n,target:"_blank",rel:"noreferrer",className:"text-[#406E71] hover:underline break-all",children:a}):a})]})}function Hve({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 U7t(){const s=br(),{data:t}=zfe(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),{data:d,refetch:h}=mt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await V.functions.invoke("coach-stripe-status");return b}}),{data:m=[]}=mt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b}=await V.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return b||[]}});k.useEffect(()=>{const b=new URLSearchParams(window.location.search);(b.get("onboarded")||b.get("refresh"))&&h()},[h]);const x=async()=>{var T,A;a(!0);const{data:b,error:N}=await V.functions.invoke("coach-stripe-connect");a(!1);let S=b==null?void 0:b.error;if(!S&&N)try{const I=await((A=(T=N==null?void 0:N.context)==null?void 0:T.json)==null?void 0:A.call(T));S=(I==null?void 0:I.error)||N.message}catch{S=N.message}if(S)return ue.error(S,{duration:1e4});b!=null&&b.url&&(window.location.href=b.url)},y=d||{},v=!!(t!=null&&t.use_platform_stripe),w=v||y.connected&&y.charges_enabled;return e.jsx(ws,{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(G,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(ke,{children:e.jsxs(Pe,{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(Vp,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v?"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."})]}),w?e.jsxs(Ge,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(In,{className:"h-3 w-3"})," ",v?"Using LevelUp billing":"Connected"]}):y.connected?e.jsxs(Ge,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Oi,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Ge,{variant:"outline",children:"Not connected"})]}),!v&&e.jsxs(G,{onClick:x,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[w?"Update Stripe details":y.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Qr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{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(G,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!w,children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!w&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),m.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:m.map(b=>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:[b.name,b.is_active&&b.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:["$",(b.price_cents/100).toFixed(0)," / ",b.billing_interval,!b.is_active&&" · Inactive"]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{c(b),l(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await V.from("coaching_packages").delete().eq("id",b.id),r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(yr,{className:"h-4 w-4"})})]},b.id))})]})}),e.jsx(q7t,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>r.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function q7t({open:s,onOpenChange:t,coachId:r,pkg:n,onSaved:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState("month"),[y,v]=k.useState(!0),[w,b]=k.useState(!0),[N,S]=k.useState(!1);k.useEffect(()=>{s&&(l((n==null?void 0:n.name)||""),c((n==null?void 0:n.description)||""),h(n?(n.price_cents/100).toString():""),x((n==null?void 0:n.billing_interval)||"month"),v((n==null?void 0:n.is_active)??!0),b((n==null?void 0:n.accepting_clients)??!0))},[s,n]);const T=async()=>{if(!i.trim()||!d)return ue.error("Name and price required");S(!0);const A={coach_id:r,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:m,is_active:y,accepting_clients:w},{error:I}=n!=null&&n.id?await V.from("coaching_packages").update(A).eq("id",n.id):await V.from("coaching_packages").insert(A);if(S(!1),I)return ue.error(I.message);ue.success("Saved"),a==null||a(),t(!1)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:n!=null&&n.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ne,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:A=>l(A.target.value)}),e.jsx(or,{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(Ne,{type:"number",value:d,onChange:A=>h(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(Is,{value:m,onValueChange:x,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"month",children:"Monthly"}),e.jsx(ct,{value:"year",children:"Yearly"}),e.jsx(ct,{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:y,onChange:A=>v(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:w,onChange:A=>b(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(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:T,disabled:N,children:n!=null&&n.id?"Save":"Create"})]})]})})}function L8e({kind:s,value:t,onChange:r}){const n=k.useRef(null),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),h=k.useRef(null),m=k.useRef(null),x=k.useRef(null),y=k.useRef([]),[v,w]=k.useState(!1),b=s==="photo"?"image/*":"video/*",N=s==="photo"?10*1024*1024:200*1024*1024,S=async($,F)=>{var re;const{data:z}=await V.auth.getUser(),Q=(re=z.user)==null?void 0:re.id;if(!Q)return ue.error("Not signed in");if($.size>N)return ue.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const K=`${Q}/${s}-${Date.now()}.${F}`,{error:X}=await V.storage.from("coach-media").upload(K,$,{upsert:!0,contentType:$.type||(s==="photo"?"image/jpeg":"video/webm")});if(X)return i(!1),ue.error(X.message);const{data:Z}=await V.storage.from("coach-media").createSignedUrl(K,60*60*24*365*10);i(!1),Z!=null&&Z.signedUrl&&(r(Z.signedUrl),ue.success("Uploaded"),d(null))},T=async $=>{const F=$.name.split(".").pop()||(s==="photo"?"jpg":"webm");await S($,F)},A=async()=>{try{const $=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});m.current=$,w(!0),setTimeout(()=>{h.current&&(h.current.srcObject=$,h.current.play())},50);const F=new MediaRecorder($,{mimeType:"video/webm"});y.current=[],F.ondataavailable=z=>z.data.size>0&&y.current.push(z.data),F.onstop=()=>{const z=new Blob(y.current,{type:"video/webm"});d(z),$.getTracks().forEach(Q=>Q.stop())},x.current=F,F.start(),o(!0)}catch($){ue.error($.message||"Could not access camera")}},I=()=>{var $;($=x.current)==null||$.stop(),o(!1)},D=()=>{var $;($=m.current)==null||$.getTracks().forEach(F=>F.stop()),w(!1),o(!1),d(null)},R=async()=>{c&&(await S(c,"webm"),D())};return k.useEffect(()=>()=>{var $;return($=m.current)==null?void 0:$.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:n,type:"file",accept:b,className:"hidden",onChange:$=>{var z;const F=(z=$.target.files)==null?void 0:z[0];F&&T(F),$.target.value=""}}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var $;return($=n.current)==null?void 0:$.click()},children:[a?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||v,children:[e.jsx(Qf,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(""),children:[e.jsx(yr,{className:"h-4 w-4 mr-1"})," Remove"]})]}),v&&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:h,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(G,{type:"button",size:"sm",onClick:I,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(og,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(G,{type:"button",size:"sm",onClick:()=>{var $;return($=x.current)==null?void 0:$.start()},children:[e.jsx(Jr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{type:"button",size:"sm",onClick:R,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:D,children:"Cancel"})]})]})]})}function V7t(){const s=br(),{data:t,isLoading:r}=zfe(),n=Xt(),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(!1),[b,N]=k.useState([]),[S,T]=k.useState(""),[A,I]=k.useState(!1);k.useEffect(()=>{if(!t)return;const z=t;i(z.slug||""),o(z.headline||""),d(z.bio||""),m(z.photo_url||""),y(z.intro_video_url||""),w(!!z.accepting_clients),N(z.specialties||[])},[t]);const D=async()=>{if(!t)return;I(!0);const{error:z}=await V.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:h||null,intro_video_url:x||null,accepting_clients:v,specialties:b}).eq("id",t.id);if(I(!1),z)return ue.error(z.message);ue.success("Profile saved"),n.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const z=S.trim();if(z){if(b.includes(z))return T("");N([...b,z]),T("")}};if(r)return e.jsx(ws,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(ws,{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 $=t,F=$.slug?`${window.location.origin}/coaches/${$.slug}`:null;return e.jsx(ws,{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(G,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[F&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>window.open(F,"_blank"),children:[e.jsx(Qr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(G,{onClick:D,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Bl,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),$.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(ke,{children:e.jsxs(Pe,{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(_r,{checked:v,onCheckedChange:w})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:a,onChange:z=>i(z.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Headline"}),e.jsx(Ne,{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(he,{children:"Bio"}),e.jsx(or,{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(he,{children:"Profile photo"}),e.jsx(L8e,{kind:"photo",value:h,onChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Intro video"}),e.jsx(L8e,{kind:"video",value:x,onChange:y})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:b.map(z=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[z,e.jsx("button",{onClick:()=>N(b.filter(Q=>Q!==z)),children:e.jsx(vr,{className:"h-3 w-3"})})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:S,onChange:z=>T(z.target.value),placeholder:"Add a specialty…",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),R())}}),e.jsx(G,{type:"button",variant:"outline",onClick:R,children:e.jsx($s,{className:"h-4 w-4"})})]})]})]})}),e.jsx(ke,{children:e.jsx(Pe,{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(G,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(H7t,{coachId:$.id})]})})}function H7t({coachId:s}){const[t,r]=k.useState("");Xt();const{data:n=[],refetch:a}=mt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await V.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 ue.error("Email required");const{error:d}=await V.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ue.error(d.message);r(""),ue.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ue.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await V.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(ke,{children:e.jsxs(Pe,{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(po,{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(Ne,{placeholder:"agent@email.com",value:t,onChange:c=>r(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(G,{onClick:i,children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.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(G,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(yr,{className:"h-4 w-4"})})]},c.id)),n.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}function G7t(){const{data:s=[],isLoading:t}=mt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:r,error:n}=await V.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(n)throw n;const a=(r||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await V.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(r||[]).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(jr,{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(In,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{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(r=>{var i,l;const n=((i=r.profile)==null?void 0:i.name)||"Coach",a=r.photo_url||((l=r.profile)==null?void 0:l.avatar_url);return e.jsx(Yn,{to:`/coaches/${r.slug||r.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:n,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:n.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:[r.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(jr,{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 ${r.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 ${r.accepting_clients?"bg-white":"bg-amber-500"}`}),r.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:n}),r.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:r.headline}),r.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:r.bio}),r.specialties&&r.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:r.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(Ha,{className:"h-4 w-4"})})]})]})]})})},r.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(jr,{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(In,{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(In,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(In,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Yn,{to:"/coaches/apply",className:"inline-flex items-center gap-2 bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-bold px-7 py-4 rounded-xl shadow-lg shadow-yellow-300/20 transition-all hover:-translate-y-0.5",children:["Apply to coach ",e.jsx(Ha,{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."})]})]})]})]})]})}function W7t(){var y;const{slug:s}=Ki(),t=br(),{user:r}=js(),[n,a]=k.useState(null),{data:i,isLoading:l}=mt({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||""),w=V.from("coaches").select("*"),{data:b}=v?await w.eq("id",s).maybeSingle():await w.eq("slug",s).maybeSingle();if(!b)return null;const[{data:N},{data:S}]=await Promise.all([V.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),V.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:N,packages:S||[]}}}),o=async v=>{if(!r){ue.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:w,error:b}=await V.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),b||w!=null&&w.error){ue.error((w==null?void 0:w.error)||(b==null?void 0:b.message)||"Checkout failed");return}w!=null&&w.url&&(window.location.href=w.url)};if(l)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(i!=null&&i.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:c,profile:d,packages:h}=i,m=c,x=(v,w)=>{const b=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return w==="one_time"?b:`${b} / ${w}`};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(G,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," All Coaches"]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:items-center",children:[e.jsxs(Nn,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(ya,{src:m.photo_url||(d==null?void 0:d.avatar_url)}),e.jsx(kn,{className:"text-3xl bg-white/20",children:((d==null?void 0:d.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[m.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(jr,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(d==null?void 0:d.name)||"Coach"}),m.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:m.headline}),((y=m.specialties)==null?void 0:y.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:m.specialties.map(v=>e.jsx(Ge,{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:[m.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:m.intro_video_url,controls:!0,className:"w-full h-full"})}),m.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:m.bio})]}),e.jsx(D7t,{coachId:m.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"}),h.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):h.map(v=>{const w=v.accepting_clients===!1;return e.jsx(ke,{className:`border-2 transition-colors ${w?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Pe,{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}),w&&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:x(v.price_cents,v.billing_interval)}),w?e.jsx("div",{className:"mt-4 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. Check back soon."}):e.jsxs(G,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>o(v.id),disabled:n===v.id,children:[n===v.id?"Loading…":"Get Started",e.jsx(Kn,{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."})]})]})]})}const K7t=qb({full_name:io().trim().min(2,"Please enter your full name").max(100),email:io().trim().email("Enter a valid email").max(255),phone:io().trim().max(40).optional().or(Vx("")),brokerage:io().trim().max(150).optional().or(Vx("")),years_experience:io().trim().max(40).optional().or(Vx("")),specialties:io().trim().max(500).optional().or(Vx("")),why_coach:io().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:io().trim().max(2e3).optional().or(Vx("")),website_url:io().trim().max(300).optional().or(Vx("")),linkedin_url:io().trim().max(300).optional().or(Vx(""))});function Y7t(){const s=br(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,h)=>l(m=>({...m,[d]:h})),c=async d=>{var x;d.preventDefault();const h=K7t.safeParse(i);if(!h.success){const y=(x=Object.values(h.error.flatten().fieldErrors)[0])==null?void 0:x[0];return ue.error(y||"Please check the form and try again")}r(!0);const{error:m}=await V.from("coach_applications").insert(h.data);if(r(!1),m)return ue.error(m.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return n?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(In,{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(G,{onClick:()=>s("/coaches"),className:"bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-semibold",children:"Browse our coaches"})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-5xl mx-auto px-4 py-16 md:py-20",children:[e.jsxs(Yn,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to coaches"]}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(jr,{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(pr,{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(bo,{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(Yl,{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(In,{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(Gi,{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(Xn,{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(g0,{label:"Full name *",children:e.jsx(Ne,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(g0,{label:"Email *",children:e.jsx(Ne,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(g0,{label:"Phone",children:e.jsx(Ne,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(g0,{label:"Current brokerage",children:e.jsx(Ne,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(g0,{label:"Years in real estate",children:e.jsx(Ne,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(g0,{label:"Coaching specialties",children:e.jsx(Ne,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(g0,{label:"Website",children:e.jsx(Ne,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(g0,{label:"LinkedIn",children:e.jsx(Ne,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(g0,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(or,{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(g0,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(or,{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(G,{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 g0({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const Z7t="/assets/testimonial-avatar-1-BsCQFauB.jpg",X7t="/assets/testimonial-avatar-2-B6VPVc2t.jpg",Q7t="/assets/testimonial-avatar-3-GuEFwYUE.jpg",J7t="/assets/testimonial-avatar-4-98iKMtkB.jpg",e9t="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",t9t=[Z7t,X7t,Q7t,J7t,e9t],s9t=qb({name:io().trim().min(2,"Name must be at least 2 characters").max(100),email:io().trim().email("Please enter a valid email address").max(255),phone:io().trim().min(10,"Please enter a valid phone number").max(20).optional().or(Vx("")),brokerage:io().trim().max(200).optional().or(Vx(""))}),r9t=[{icon:rf,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:on,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Jl,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ln,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:ii,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],n9t=[{icon:pr,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:jr,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Cn,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:_h,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Ca,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ro,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:ci,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:Ku,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],a9t=[{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."}],i9t=()=>{const s=br(),[t,r]=k.useState(!1),[n,a]=k.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=k.useState({}),o=async c=>{var h,m;c.preventDefault(),l({});const d=s9t.safeParse(n);if(!d.success){const x={};d.error.errors.forEach(y=>{y.path[0]&&(x[y.path[0]]=y.message)}),l(x);return}r(!0);try{const x=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:y,error:v}=await V.functions.invoke("create-trial-signup",{body:{name:n.name.trim(),email:n.email.trim().toLowerCase(),phone:((h=n.phone)==null?void 0:h.trim())||void 0,brokerage:((m=n.brokerage)==null?void 0:m.trim())||void 0,referral_code:x}});if(v){console.error("Trial signup error:",v),ue.error(v.message||"Something went wrong. Please try again.");return}if(y!=null&&y.error){ue.error(y.error);return}ue.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),s("/trial/success")}catch(x){console.error("Trial signup error:",x),ue.error("Something went wrong. Please try again.")}finally{r(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(nl,{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.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:$de,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(G,{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(G,{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(jr,{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(In,{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(In,{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:t9t.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(Xn,{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(ke,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Pe,{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(lv,{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(he,{htmlFor:"name",children:"Full Name *"}),e.jsx(Ne,{id:"name",type:"text",placeholder:"John Smith",value:n.name,onChange:c=>a({...n,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(he,{htmlFor:"email",children:"Email Address *"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"john@example.com",value:n.email,onChange:c=>a({...n,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(he,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Ne,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:n.phone,onChange:c=>a({...n,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(he,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(Ne,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:n.brokerage,onChange:c=>a({...n,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(G,{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(es,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Ha,{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:r9t.map((c,d)=>e.jsxs(ke,{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(Dt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Pe,{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(jr,{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:n9t.map((c,d)=>e.jsxs(ke,{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(Dt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Pe,{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:a9t.map((c,d)=>e.jsx(ke,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Pe,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(Xn,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},h))}),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(Wu,{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(Ku,{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(pr,{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(ke,{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(Pe,{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(G,{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(Ha,{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:GCe,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."})]})})})]})]})},o9t=()=>{const s=br();return e.jsxs(e.Fragment,{children:[e.jsx(nl,{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:$de,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(G,{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(ke,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Pe,{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(In,{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(eu,{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(G,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(Ha,{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:GCe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},l9t=qb({viewerName:io().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:io().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:io().max(20,"Phone must be less than 20 characters").optional(),message:io().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function c9t({shareToken:s,agentName:t,hasContact:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),d=Lfe({resolver:Pfe(l9t),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),h=async m=>{a(!0),c(null);try{const{data:x,error:y}=await V.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:m.viewerName,viewerEmail:m.viewerEmail,viewerPhone:m.viewerPhone||void 0,message:m.message}});if(y)throw new Error(y.message);if(!(x!=null&&x.success))throw new Error((x==null?void 0:x.error)||"Failed to send reply");l(!0)}catch(x){console.error("Failed to submit reply:",x),c(x.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(ke,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Pe,{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(In,{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(ke,{children:[e.jsxs(Mt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Jl,{className:"h-5 w-5 text-primary"}),e.jsx(Dt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Nr,{children:r?`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(Pe,{children:e.jsx(Dfe,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(h),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(td,{control:d.control,name:"viewerName",render:({field:m})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Your Name *"}),e.jsx(Bc,{children:e.jsx(Ne,{placeholder:"John Smith",...m})}),e.jsx(lf,{})]})}),e.jsx(td,{control:d.control,name:"viewerEmail",render:({field:m})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Email *"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"email",placeholder:"john@example.com",...m})}),e.jsx(lf,{})]})})]}),!r&&e.jsx(td,{control:d.control,name:"viewerPhone",render:({field:m})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Phone (optional)"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"tel",placeholder:"(555) 123-4567",...m})}),e.jsx(lf,{})]})}),e.jsx(td,{control:d.control,name:"message",render:({field:m})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Message *"}),e.jsx(Bc,{children:e.jsx(or,{placeholder:r?"Thanks for the video! I had a question about...":"I'm interested in learning more about...",className:"min-h-[100px] resize-none",...m})}),e.jsx(lf,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(G,{type:"submit",className:"w-full gap-2",disabled:n,children:n?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const d9t=()=>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(Xn,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Xn,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Xn,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Xn,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Xn,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(fb,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),u9t=()=>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(jr,{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(Xn,{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(jr,{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(Xn,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Xn,{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(fb,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),h9t=()=>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(vy,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(vy,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(vy,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(vy,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(ci,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(ci,{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(ci,{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"})]}),m9t=()=>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(Yl,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Xn,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Yl,{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(Xn,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Xn,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),f9t=()=>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(vy,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(vy,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(mA,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),p9t=()=>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(F4,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(F4,{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(jr,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(jr,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),x9t=()=>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(lj,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(lj,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(lj,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(H0,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(H0,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(H0,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(H0,{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(Xn,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),g9t=()=>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(ci,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(ci,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),y9t=()=>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(Xn,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Xn,{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(Xn,{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(Xn,{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(jr,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(eu,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(eu,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),v9t=()=>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(Xn,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(jr,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(jr,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),b9t=()=>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(nb,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(nb,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(nb,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(nb,{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"})]})]})]}),_9t=()=>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(Xn,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Xn,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Yl,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Yl,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(fb,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),w9t=()=>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(_h,{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(eu,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(ii,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),j9t=()=>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(ci,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(ci,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(ci,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(ci,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(ci,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(ci,{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(ci,{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(ci,{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"})]}),N9t=()=>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(jr,{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"})]}),k9t=()=>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(En,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(En,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(ep,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(ep,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(ci,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(ci,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(jr,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(eu,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),S9t=()=>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(eu,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(eu,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(ep,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(En,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(jr,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(jr,{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"})]}),C9t=()=>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(ep,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(ep,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(ep,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(En,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(eu,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(jr,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Xn,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),T9t=()=>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(En,{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(ep,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(ci,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(jr,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(sv,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),P8e=()=>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"})]}),E9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ci,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(ci,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(ci,{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(ci,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),A9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(sv,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(jr,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(En,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),M9t=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(D4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(wA,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(D4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),tD=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(jr,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(eu,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(jr,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),D8e=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(En,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(jr,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(En,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),qje=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(jr,{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(ci,{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(E9t,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(oR,{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(tD,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(D4,{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(M9t,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(ro,{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(pr,{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(tD,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Yl,{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(P8e,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Ca,{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(D8e,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(wA,{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(tD,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(_h,{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(w9t,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(ci,{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(j9t,{})},{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(N9t,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Xn,{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(y9t,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(mA,{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(f9t,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(vy,{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(h9t,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Yl,{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(m9t,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(fb,{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(d9t,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(mc,{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(u9t,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Yl,{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(_9t,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(F4,{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(p9t,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(ci,{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(g9t,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(lj,{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(x9t,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(jr,{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(v9t,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(nb,{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(b9t,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(En,{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(k9t,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(eu,{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(S9t,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(on,{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(D8e,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(wl,{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(tD,{})},{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(sv,{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(A9t,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(ep,{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(C9t,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(En,{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(T9t,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(jh,{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(tD,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Yl,{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(P8e,{})}],I9t=[{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 L9t(s){return qje.filter(t=>t.category===s)}function RA(s){return qje.find(t=>t.id===s)||qje[0]}function R8e(){const{shareToken:s,recipientToken:t}=Ki(),[r,n]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!0),[h,m]=k.useState(null),[x,y]=k.useState(!0),v=k.useRef(null),w=k.useRef(0),b=k.useRef(0),N=(()=>{const K=new URLSearchParams(window.location.search);return t||K.get("rt")||null})(),S=k.useCallback((K,X=!1)=>{if(!N||K<=0)return;const Z=Math.max(1,Math.round(K));if(Z<=b.current)return;const le=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(N)}&e=watch&ws=${Z}`;X&&navigator.sendBeacon?navigator.sendBeacon(le):fetch(le,{method:"GET",keepalive:X}).catch(()=>{}),b.current=Math.max(b.current,Z)},[N]);k.useEffect(()=>{var ne;if(!x||!(r!=null&&r.playback_url)||!N)return;let K=!1;const X=()=>{w.current>0&&S(w.current,!0)},Z=()=>{document.visibilityState==="hidden"&&X()},re=()=>{X()},le=()=>{var ye;if(K||!v.current||!((ye=window.playerjs)!=null&&ye.Player))return;const ie=new window.playerjs.Player(v.current);ie.on("timeupdate",ce=>{const ve=Math.floor(Number((ce==null?void 0:ce.seconds)??0));!Number.isFinite(ve)||ve<=0||(w.current=Math.max(w.current,ve))}),ie.on("pause",()=>{w.current>0&&S(w.current)}),ie.on("ended",()=>{w.current>0&&S(w.current,!0)})},oe=document.querySelector('script[data-bunny-playerjs="true"]');if((ne=window.playerjs)!=null&&ne.Player)le();else if(oe)oe.addEventListener("load",le,{once:!0});else{const ie=document.createElement("script");ie.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ie.async=!0,ie.defer=!0,ie.dataset.bunnyPlayerjs="true",ie.onload=le,document.body.appendChild(ie)}return document.addEventListener("visibilitychange",Z),window.addEventListener("beforeunload",re),()=>{K=!0,document.removeEventListener("visibilitychange",Z),window.removeEventListener("beforeunload",re),X()}},[x,r==null?void 0:r.playback_url,N,S]),k.useEffect(()=>{w.current=0,b.current=0},[N,s]),k.useEffect(()=>{const K=()=>{['[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(le=>{document.querySelectorAll(le).forEach(oe=>{oe.style.display="none"})})};K();const X=[setTimeout(K,500),setTimeout(K,1500),setTimeout(K,3e3)],Z=new MutationObserver(K);return Z.observe(document.body,{childList:!0,subtree:!0}),()=>{X.forEach(clearTimeout),Z.disconnect()}},[]),k.useEffect(()=>{(async()=>{if(!s){m("Invalid share link"),d(!1);return}const{data:X,error:Z}=await V.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(Z||!X){m("Video not found or has been removed"),d(!1);return}n(X);try{await V.rpc("log_video_view",{p_video_id:X.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(re){console.warn("Failed to log video view:",re)}if(X.owner_user_id){const{data:re}=await V.from("profiles").select("id, name, email, phone").eq("id",X.owner_user_id).single();if(re){i(re);try{const{data:le}=await V.storage.from("avatars").list(`${X.owner_user_id}`);if(le&&le.length>0){const{data:oe}=V.storage.from("avatars").getPublicUrl(`${X.owner_user_id}/${le[0].name}`);o(oe.publicUrl)}}catch{}}}d(!1)})()},[s]);const T=K=>{if(!K)return"0:00";const X=Math.floor(K/60),Z=K%60;return`${X}:${Z.toString().padStart(2,"0")}`},A=K=>K.includes("iframe.mediadelivery.net/play/")?K.replace("/play/","/embed/")+"?autoplay=true&responsive=true":K,I=K=>{if(!K)return"?";const X=K.split(" ");return X.length>=2?`${X[0][0]}${X[1][0]}`.toUpperCase():K.substring(0,2).toUpperCase()},D=RA((r==null?void 0:r.page_template)||"default"),R=(r==null?void 0:r.recipient_name)||null,$=D.headerText(R),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(es,{className:"h-8 w-8 animate-spin text-primary"})});if(h||!r)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(ke,{className:"max-w-md w-full",children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Jr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:h||"This video is no longer available."})]})})});const Q=D.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(nl,{children:[e.jsx("title",{children:$}),e.jsx("meta",{name:"description",content:D.subText}),e.jsx("meta",{property:"og:title",content:$}),e.jsx("meta",{property:"og:description",content:D.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:z}),r.preview_url&&e.jsx("meta",{property:"og:image",content:r.preview_url}),!r.preview_url&&r.thumbnail_url&&e.jsx("meta",{property:"og:image",content:r.thumbnail_url}),r.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:r.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:$}),e.jsx("meta",{name:"twitter:description",content:D.subText}),r.preview_url&&e.jsx("meta",{name:"twitter:image",content:r.preview_url}),r.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:r.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:It("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",D.gradientClasses),children:[Q&&D.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[Q&&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:It("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",D.accentColor==="primary"&&"bg-primary/10 text-primary",D.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",D.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",D.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",D.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",D.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",D.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",D.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",D.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",D.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",D.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",D.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",D.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:D.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:$}),e.jsx("p",{className:"text-muted-foreground",children:D.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(Nn,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(ya,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(kn,{className:"bg-primary/10 text-primary font-semibold",children:I(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:Q?"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(G,{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(Cn,{className:"h-4 w-4"})})}),a.email&&e.jsx(G,{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(ke,{className:"overflow-hidden shadow-lg",children:x&&r.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:v,src:A(r.playback_url),title:r.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:()=>y(!0),children:[r.preview_url||r.thumbnail_url?e.jsx("img",{src:r.preview_url||r.thumbnail_url||"",alt:r.title?`${r.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:K=>{var Z;K.currentTarget.style.display="none";const X=(Z=K.currentTarget.parentElement)==null?void 0:Z.querySelector(".video-fallback");X&&(X.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:r.preview_url||r.thumbnail_url?"none":"flex"},children:e.jsx(Jr,{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(Uo,{className:"h-10 w-10 text-primary ml-1"})})}),r.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:T(r.duration_seconds)})]})}),!Q&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:x?"Enjoy the video!":"Click to play the video"})]}),!x&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(G,{size:"lg",onClick:()=>y(!0),className:"gap-2",children:[e.jsx(Uo,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(c9t,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!r.contact_id})]})]})]})}function P9t(){return k.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(nCt,{})}function D9t(){const{token:s}=Ki();return k.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(es,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const R9t={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"},O9t={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},XT={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function F9t(){var Ue,Be,De,Ae;const{slugOrId:s}=Ki(),[t]=Ac(),{data:r,isLoading:n}=SJe(s||""),a=CJe(),i=$At(),l=t.get("ref"),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[I,D]=k.useState("in_person"),[R,$]=k.useState("info"),[F,z]=k.useState(!1),[Q,K]=k.useState(!1),[X,Z]=k.useState(null),[re,le]=k.useState(!1);k.useEffect(()=>{l&&i.mutate(l)},[l]);const oe=He=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(He),ne=async He=>{if(He.preventDefault(),!o.trim()||!m.trim()||!r)return;const Le=R==="showing";if(Le&&!N){ue.error("Please pick a preferred date for your showing");return}z(!0);try{await a.mutateAsync({listingId:r.id,agentId:r.agent_id,firstName:o.trim(),lastName:d.trim(),email:m.trim(),phone:y.trim(),shareToken:l,leadType:Le?"showing_request":"info_request",preferredDate:Le?N:null,preferredTime:Le&&T||null,showingMode:Le?I:null,message:w.trim()||null}),K(!0),ue.success(Le?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Ie){console.error("Lead submission error:",Ie),ue.error(`Failed to submit: ${Ie.message||"Please try again"}`)}finally{z(!1)}},ie=(r==null?void 0:r.photos)||[],ye=ie.find(He=>He.is_primary)||ie[0],ce=()=>{X!==null&&Z(X===0?ie.length-1:X-1)},ve=()=>{X!==null&&Z(X===ie.length-1?0:X+1)};if(n)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(Fs,{className:"h-8 w-32"})})}),e.jsxs("div",{className:"container mx-auto px-4 py-8",children:[e.jsx(Fs,{className:"h-10 w-48 mb-6"}),e.jsx(Fs,{className:"aspect-video mb-6"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-4",children:[e.jsx(Fs,{className:"h-12 w-48"}),e.jsx(Fs,{className:"h-6 w-full"}),e.jsx(Fs,{className:"h-6 w-3/4"})]}),e.jsx(Fs,{className:"h-64"})]})]})]});if(!r)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(Yn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:wde,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-16 text-center",children:[e.jsx(En,{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-4",children:"This listing may no longer be available."}),e.jsx(G,{asChild:!0,children:e.jsx(Yn,{to:"/public/listings",children:"Browse All Listings"})})]})]});const be=r.property_address?`${r.property_address} - ${r.city}, ${r.state}`:`${r.city}, ${r.state} Home for Sale`;return e.jsxs(e.Fragment,{children:[e.jsxs(nl,{children:[e.jsxs("title",{children:[be," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${oe(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA ${r.square_footage?r.square_footage.toLocaleString()+" sqft":""} ${XT[r.property_type]} in ${r.city}, ${r.state}. ${((Ue=r.description)==null?void 0:Ue.slice(0,150))||""}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${r.slug||r.id}`}),e.jsx("meta",{property:"og:title",content:be}),e.jsx("meta",{property:"og:description",content:`${oe(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA ${XT[r.property_type]} in ${r.city}, ${r.state}. View photos, details, and contact the listing agent.`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${r.slug||r.id}`}),ye&&e.jsx("meta",{property:"og:image",content:ye.photo_url}),ye&&e.jsx("meta",{property:"og:image:alt",content:`${r.property_address||r.city} - ${XT[r.property_type]} for sale`}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{property:"og:locale",content:"en_US"}),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:`${oe(r.price)} - ${r.bedrooms||""}BD ${r.bathrooms||""}BA in ${r.city}, ${r.state}`}),ye&&e.jsx("meta",{name:"twitter:image",content:ye.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("meta",{name:"geo.region",content:`US-${r.state}`}),e.jsx("meta",{name:"geo.placename",content:r.city}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:r.property_address||`${r.city}, ${r.state} Home`,description:r.description||`${XT[r.property_type]} for sale in ${r.city}, ${r.state}`,url:`https://listings.relevelup.com/${r.slug||r.id}`,datePosted:r.created_at,image:ie.map(He=>He.photo_url),address:{"@type":"PostalAddress",streetAddress:r.property_address||void 0,addressLocality:r.city,addressRegion:r.state,addressCountry:"US"},geo:r.neighborhood?{"@type":"GeoCoordinates",name:r.neighborhood}:void 0,offers:{"@type":"Offer",price:r.price,priceCurrency:"USD",availability:r.status==="sold"?"https://schema.org/SoldOut":r.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:r.bedrooms||void 0,numberOfBathroomsTotal:r.bathrooms||void 0,floorSize:r.square_footage?{"@type":"QuantitativeValue",value:r.square_footage,unitCode:"FTK"}:void 0,yearBuilt:r.year_built||void 0,broker:r.agent?{"@type":"RealEstateAgent",name:r.agent.name,email:r.agent.email,worksFor:(Be=r.agent.brokerage)!=null&&Be.name?{"@type":"RealEstateAgent",name:r.agent.brokerage.name}:void 0}:void 0})})]}),e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card sticky top-0 z-50",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Yn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:wde,alt:"LevelUp",className:"h-8"})})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-6",children:[e.jsxs(Yn,{to:"/public/listings",className:"inline-flex items-center text-muted-foreground hover:text-foreground mb-6",children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),ie.length>0&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-8",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:()=>Z(0),children:e.jsx("img",{src:ye==null?void 0:ye.photo_url,alt:`${r.property_address||r.city+", "+r.state} - ${XT[r.property_type]} main photo`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:ie.slice(1,5).map((He,Le)=>e.jsxs("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer relative",onClick:()=>Z(Le+1),children:[e.jsx("img",{src:He.photo_url,alt:`${r.property_address||r.city} - Photo ${Le+2} of ${ie.length}`,className:"w-full h-full object-cover hover:scale-105 transition-transform duration-300"}),Le===3&&ie.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center text-white font-semibold",children:["+",ie.length-5," more"]})]},He.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsx(Ge,{className:`${R9t[r.status]} text-white border-0`,children:O9t[r.status]})}),e.jsx("h1",{className:"text-4xl font-bold text-primary mb-2",children:oe(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(Ca,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),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(Ny,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Xf,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(og,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(on,{className:"h-6 w-6 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"text-xl font-semibold",children:r.year_built}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),XT[r.property_type]]}),r.lot_size&&e.jsxs(Ge,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(Ge,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"About This Property"}),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("h2",{className:"text-lg font-semibold mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.mls_link&&e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[r.video&&r.video.playback_url&&e.jsx(ke,{className:"overflow-hidden bg-gradient-to-br from-primary/5 to-primary/10 border-primary/20",children:e.jsxs(Pe,{className:"p-0",children:[e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>le(!0),children:[r.video.thumbnail_url?e.jsx("img",{src:r.video.thumbnail_url,alt:"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-gradient-to-br from-primary/20 to-primary/30",children:e.jsx(Jr,{className:"h-12 w-12 text-primary"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 group-hover:bg-black/40 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/90 group-hover:bg-white flex items-center justify-center transition-colors shadow-lg",children:e.jsx(Uo,{className:"h-8 w-8 text-primary fill-primary ml-1"})})})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs(G,{onClick:()=>le(!0),className:"w-full gap-2",size:"lg",children:[e.jsx(Uo,{className:"h-4 w-4"}),"Watch Video Tour"]}),r.video.title&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 text-center truncate",children:r.video.title})]})]})}),r.agent&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Di,{className:"h-5 w-5"}),"Listing Agent"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"font-semibold text-lg",children:r.agent.name}),((De=r.agent.brokerage)==null?void 0:De.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),e.jsxs(ke,{className:"border-primary",children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Dt,{className:"text-lg",children:"Interested in this property?"})}),e.jsx(Pe,{children:Q?e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3",children:e.jsx(Vs,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"font-medium",children:R==="showing"?"Showing request sent!":"Thanks for your interest!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:R==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you soon."})]}):e.jsxs(On,{value:R,onValueChange:He=>$(He),children:[e.jsxs(Rn,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Kt,{value:"info",className:"gap-1.5",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Get Info"]}),e.jsxs(Kt,{value:"showing",className:"gap-1.5",children:[e.jsx(tv,{className:"h-3.5 w-3.5"}),"Request Tour"]})]}),e.jsxs("form",{onSubmit:ne,className:"space-y-3",children:[e.jsxs(ts,{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(he,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(Ne,{id:"preferredDate",type:"date",value:N,onChange:He=>S(He.target.value),min:new Date().toISOString().split("T")[0],required:R==="showing"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(Is,{value:T,onValueChange:A,children:[e.jsx(As,{id:"preferredTime",children:e.jsx(Ls,{placeholder:"Any time"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(ct,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(ct,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(Is,{value:I,onValueChange:He=>D(He),children:[e.jsx(As,{id:"showingMode",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(ct,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(ct,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"firstName",children:"First Name *"}),e.jsx(Ne,{id:"firstName",type:"text",placeholder:"John",value:o,onChange:He=>c(He.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"lastName",children:"Last Name"}),e.jsx(Ne,{id:"lastName",type:"text",placeholder:"Doe",value:d,onChange:He=>h(He.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email *"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"you@example.com",value:m,onChange:He=>x(He.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(he,{htmlFor:"phone",children:["Phone ",R==="showing"&&"*"]}),e.jsx(Ne,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:y,onChange:He=>v(He.target.value),required:R==="showing"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"message",children:R==="showing"?"Anything else?":"Message (optional)"}),e.jsx(or,{id:"message",placeholder:R==="showing"?"e.g. I have flexibility on weekends":"Any specific questions about the property?",value:w,onChange:He=>b(He.target.value),rows:2})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:F,children:F?"Submitting...":R==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"The listing agent will reach out to you directly."})]})]})})]})]})]})]}),e.jsx(fs,{open:X!==null,onOpenChange:()=>Z(null),children:e.jsxs(ms,{className:"max-w-5xl p-0 bg-black/95",children:[e.jsx(ys,{className:"sr-only",children:e.jsx(gs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Z(null),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(vr,{className:"h-5 w-5"})}),X!==null&&ie[X]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:ie[X].photo_url,alt:`Photo ${X+1}`,className:"w-full max-h-[80vh] object-contain"}),ie.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:ce,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx($o,{className:"h-6 w-6"})}),e.jsx("button",{onClick:ve,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(va,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/50 px-3 py-1 rounded-full text-sm",children:[X+1," / ",ie.length]})]})]})]})}),e.jsx(fs,{open:re,onOpenChange:le,children:e.jsxs(ms,{className:"max-w-4xl p-0 bg-black overflow-hidden",children:[e.jsx(ys,{className:"sr-only",children:e.jsx(gs,{children:"Video Tour"})}),e.jsx("button",{onClick:()=>le(!1),className:"absolute right-4 top-4 z-50 rounded-full bg-black/50 p-2 text-white hover:bg-black/70",children:e.jsx(vr,{className:"h-5 w-5"})}),((Ae=r==null?void 0:r.video)==null?void 0:Ae.playback_url)&&e.jsx("div",{className:"aspect-video w-full",children:e.jsx("iframe",{src:r.video.playback_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]})}),e.jsx("footer",{className:"border-t py-8 mt-16",children:e.jsxs("div",{className:"container mx-auto px-4 text-center text-sm text-muted-foreground",children:[e.jsxs("p",{children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("p",{className:"mt-2",children:e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground",children:"relevelup.com"})})]})})]})]})}function B9t(){var i;const{slug:s}=Ki(),{data:t,isLoading:r,error:n}=MJe(s);if(k.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),k.useEffect(()=>{t!=null&&t.id&&mo(t.id,"card_view")},[t==null?void 0:t.id]),r)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(Fs,{className:"h-28 w-28 rounded-full"}),e.jsx(Fs,{className:"h-6 w-48"}),e.jsx(Fs,{className:"h-4 w-36"})]}),e.jsx(Fs,{className:"h-12 w-full"}),e.jsx(Fs,{className:"h-12 w-full"})]})});if(n||!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(nl,{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(KCe,{card:t})]})}function Yrt({slugOverride:s}={}){var We;const{slug:t}=Ki(),r=s||t,[n]=Ac(),a=n.get("t"),[i,l]=k.useState(!0),[o,c]=k.useState(null),[d,h]=k.useState(null),m=k.useRef(null),x=k.useRef(null),[y,v]=k.useState(null),[w,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[I,D]=k.useState(0),[R,$]=k.useState(!1),[F,z]=k.useState(""),[Q,K]=k.useState(""),[X,Z]=k.useState(""),[re,le]=k.useState(""),[oe,ne]=k.useState(""),[ie,ye]=k.useState(""),[ce,ve]=k.useState(""),[be,Ue]=k.useState(""),[Be,De]=k.useState(""),[Ae,He]=k.useState(""),[Le,Ie]=k.useState(""),[Te,xe]=k.useState("");k.useEffect(()=>{et()},[r,a]);const et=async()=>{if(!r)return;l(!0);const{data:_e,error:Re}=await V.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if(Re||!_e){$(!0),l(!1);return}h(_e),x.current=_e;const{data:tt}=await V.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",_e.user_id).single();if(tt){let Ke;if(tt.brokerage_id){const{data:xt}=await V.from("brokerages").select("name").eq("id",tt.brokerage_id).single();Ke=(xt==null?void 0:xt.name)||void 0}let Ze=tt.avatar_url||null;if(!Ze){const{data:xt}=V.storage.from("avatars").getPublicUrl(`${_e.user_id}/avatar.jpg`);xt!=null&&xt.publicUrl&&(Ze=`${xt.publicUrl}?t=${Date.now()}`)}const lt={...tt,avatar_url:Ze,brokerage_name:Ke};c(lt),m.current=lt}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",_e.id);const{data:Ke,error:Ze}=await V.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:_e.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:Ke,resolveErr:Ze}),!Ze&&(Ke!=null&&Ke.contact_id)){b(Ke.contact_id);const lt=Ke.contact;lt&&(v(lt),z(lt.first_name||""),K(lt.last_name||""),Z(lt.email||""),le(lt.phone||""),ne(lt.address||""),ye(lt.city||""),ve(lt.state||""),Ue(lt.zip||""),De(lt.birthday||""),He(lt.home_anniversary||""))}}catch(Ke){console.error("Failed to resolve token:",Ke)}l(!1)},fe=async()=>{var _e,Re;if(!F.trim()){ue.error("Please enter your first name");return}if(!r){ue.error("Invalid page. Please refresh.");return}A(!0);try{let tt=(_e=x.current)==null?void 0:_e.id,Ke=(Re=x.current)==null?void 0:Re.user_id;if(!tt||!Ke){const{data:lt}=await V.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!lt){ue.error("This page is no longer active. Please contact the agent directly."),A(!1);return}tt=lt.id,Ke=lt.user_id}const{error:Ze}=await V.from("contact_intake_submissions").insert({intake_page_id:tt,agent_user_id:Ke,existing_contact_id:w,first_name:F.trim(),last_name:Q.trim()||null,email:X.trim()||null,phone:re.trim()||null,address:oe.trim()||null,city:ie.trim()||null,state:ce.trim()||null,zip:be.trim()||null,birthday:Be||null,home_anniversary:Ae||null,real_estate_interest:Le||null,message:Te.trim()||null});if(console.log("[ConnectPage] Insert result:",{error:Ze}),Ze)throw Ze;a&&await V.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const lt=[F.trim(),Q.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:Ke,contactName:lt,contactEmail:X.trim()||null,contactPhone:re.trim()||null,slug:r})})}catch(lt){console.warn("Connect page notification failed (non-blocking):",lt)}S(!0)}catch(tt){console.error(tt),ue.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(es,{className:"h-8 w-8 animate-spin text-slate-400"})});if(R)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(N)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(nl,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Sr.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[e.jsx(Sr.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:e.jsx(In,{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(ci,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const it=!!a&&!!y,Oe=3,Ye=[{title:it?"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 text-slate-600 mb-1.5",children:"First Name *"}),e.jsx("input",{type:"text",value:F,onChange:_e=>z(_e.target.value),placeholder:"Jane",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Last Name"}),e.jsx("input",{type:"text",value:Q,onChange:_e=>K(_e.target.value),placeholder:"Smith",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Email"}),e.jsx("input",{type:"email",value:X,onChange:_e=>Z(_e.target.value),placeholder:"jane@email.com",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Phone"}),e.jsx("input",{type:"tel",value:re,onChange:_e=>le(_e.target.value),placeholder:"(555) 123-4567",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]})},{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 text-slate-600 mb-1.5",children:"Street Address"}),e.jsx("input",{type:"text",value:oe,onChange:_e=>ne(_e.target.value),placeholder:"123 Main St",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),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 text-slate-600 mb-1.5",children:"City"}),e.jsx("input",{type:"text",value:ie,onChange:_e=>ye(_e.target.value),placeholder:"Austin",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"State"}),e.jsx("input",{type:"text",value:ce,onChange:_e=>ve(_e.target.value),placeholder:"TX",maxLength:2,className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Zip"}),e.jsx("input",{type:"text",value:be,onChange:_e=>Ue(_e.target.value),placeholder:"78701",className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Birthday"}),e.jsx("input",{type:"date",value:Be,onChange:_e=>De(_e.target.value),className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:"Home Anniversary"}),e.jsx("input",{type:"date",value:Ae,onChange:_e=>He(_e.target.value),className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all"})]})]})]})},{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(_e=>e.jsxs("button",{type:"button",onClick:()=>Ie(Le===_e.value?"":_e.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Le===_e.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:_e.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:_e.desc})]},_e.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-1.5",children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:Te,onChange:_e=>xe(_e.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-400 transition-all resize-none"})]})]})}];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50",children:[e.jsxs(nl,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-8 sm:py-12",children:[e.jsxs(Sr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"text-center mb-8",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 mb-4 ring-4 ring-white shadow-lg"}):e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 mx-auto mb-4 flex items-center justify-center ring-4 ring-white shadow-lg",children:e.jsx("span",{className:"text-3xl font-bold text-white",children:((We=o==null?void 0:o.name)==null?void 0:We.charAt(0))||"?"})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:o==null?void 0:o.name}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-slate-500 mt-0.5",children:o.title}),(o==null?void 0:o.brokerage_name)&&e.jsx("p",{className:"text-sm text-slate-400",children:o.brokerage_name}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-3 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 bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors","aria-label":"Call agent",children:e.jsx(Cn,{className:"h-4.5 w-4.5"})}),(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 bg-blue-50 hover:bg-blue-100 text-blue-600 transition-colors","aria-label":"Email agent",children:e.jsx(Vs,{className:"h-4.5 w-4.5"})})]})]}),e.jsx(Sr.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.2},className:"text-center text-slate-600 mb-8 px-4 leading-relaxed",children:(d==null?void 0:d.welcome_message)||"I'd love to stay connected! Fill in your info below."}),e.jsx("div",{className:"flex gap-2 mb-8 px-2",children:Array.from({length:Oe}).map((_e,Re)=>e.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-all duration-500 ${Re<=I?"bg-blue-500":"bg-slate-200"}`},Re))}),e.jsxs(Sr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"bg-white rounded-2xl shadow-lg shadow-slate-200/50 border border-slate-100 p-6 sm:p-8",children:[e.jsx(z4e,{mode:"wait",children:e.jsxs(Sr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(jr,{className:"h-5 w-5 text-blue-500"}),e.jsx("h2",{className:"text-lg font-semibold text-slate-800",children:Ye[I].title})]}),Ye[I].fields]},I)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[I>0?e.jsx("button",{type:"button",onClick:()=>D(_e=>_e-1),className:"px-5 py-2.5 text-sm font-medium text-slate-600 hover:text-slate-800 transition-colors",children:"Back"}):e.jsx("div",{}),I{if(I===0&&!F.trim()){ue.error("Please enter your first name");return}D(_e=>_e+1)},className:"px-6 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-sm",children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>fe(),disabled:T,className:"px-6 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50 flex items-center gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),I>0&&ID(_e=>_e+1),className:"text-xs text-slate-400 hover:text-slate-500 transition-colors",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 text-slate-400",children:[e.jsx(ci,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const GI=()=>({trackEngagement:k.useCallback(async(t,r,n,a="view")=>{try{const{data:{user:i}}=await V.auth.getUser();if(!i)return;await V.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:r,resource_title:n,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function sD({banners:s,autoPlayInterval:t=5e3,className:r}){const[n,a]=k.useState(0),[i,l]=k.useState(!1),{trackEngagement:o}=GI(),c=k.useCallback(y=>{o("newsletter",y.id,y.title,"click_link")},[o]),d=k.useCallback(()=>{a(y=>(y+1)%s.length)},[s.length]),h=k.useCallback(()=>{a(y=>(y-1+s.length)%s.length)},[s.length]),m=k.useCallback(y=>{a(y)},[]);if(k.useEffect(()=>{if(s.length<=1||i)return;const y=setInterval(d,t);return()=>clearInterval(y)},[s.length,i,t,d]),!s||s.length===0)return null;const x=s[n];return e.jsxs("div",{className:It("relative w-full overflow-hidden rounded-xl",r),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:x.image_url,alt:x.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",className:It("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:h,children:e.jsx($o,{className:"h-6 w-6"})}),e.jsx(G,{variant:"ghost",size:"icon",className:It("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(va,{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((y,v)=>e.jsx("button",{onClick:()=>m(v),className:It("w-2 h-2 rounded-full transition-all duration-300",v===n?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${v+1}`},v))})]}),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:x.title}),x.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:x.description})]}),x.link_url&&e.jsx("a",{href:x.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(x),children:e.jsx(G,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:x.link_text||"Learn More"})})]})]})}function z9t(s){return"EST"}function _8(s){const r=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),n=z9t();return`${r} ${n}`}function OA(s){const t=new Date,r=new Date(s),n=$E(r,-15),a=$E(r,30);return t>a?"ended":dy(t,{start:r,end:a})?"live":dy(t,{start:n,end:r})?"starting_soon":"upcoming"}function n3e(s){const t=OA(s);return t==="starting_soon"||t==="live"}const O8e=n3e,$9t=({events:s,registrations:t,onNavigateToEvents:r})=>{const[n,a]=k.useState(new Date);k.useEffect(()=>{const y=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(y)},[]);const i=s.filter(y=>n3e(y.event_date));if(i.length===0)return null;const l=i[0],o=OA(l.event_date),c=t.find(y=>y.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,h=!!c,m=o==="live",x=m?{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 ${x.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${x.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 ${x.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${x.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${x.text} font-bold text-sm uppercase tracking-wider`,children:m?e.jsxs(e.Fragment,{children:[e.jsx(gb,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(fn,{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:m?`Started at ${_8(new Date(l.event_date))}`:`Starts at ${_8(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:h?e.jsxs(G,{onClick:()=>window.open(d,"_blank"),className:`${x.button} text-white gap-2`,children:[e.jsx(Qr,{className:"h-4 w-4"}),m?"Join Now":"Join When Live"]}):e.jsxs(G,{variant:"outline",onClick:r,className:`${x.outlineButton} gap-2`,children:[e.jsx(pr,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function U9t(){const{user:s,isBrokerageManager:t}=js(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState(!1),[c,d]=k.useState(!0),h=t?"brokerage_manager":"agent";k.useEffect(()=>{if(!(s!=null&&s.id)){d(!1);return}m()},[s==null?void 0:s.id,h]);const m=async()=>{if(s!=null&&s.id)try{const{data:A,error:I}=await V.from("onboarding_checklist_items").select("*").eq("target_role",h).eq("is_active",!0).order("sort_order");if(I)throw I;const{data:D,error:R}=await V.from("onboarding_checklist_progress").select("item_id, completed_at").eq("user_id",s.id);if(R)throw R;const{data:$,error:F}=await V.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle();if(F)throw F;n(A||[]),i(D||[]),o(!!$),A&&A.length>0&&await x(A,D||[])}catch(A){console.error("Error fetching checklist data:",A)}finally{d(!1)}},x=async(A,I)=>{var He,Le;if(!(s!=null&&s.id))return;const D=I.map(Ie=>Ie.item_id),R=A.filter(Ie=>!D.includes(Ie.id));if(R.length===0)return;const[$,F,z,Q,K,X,Z,re,le,oe,ne,ie,ye,ce,ve]=await Promise.all([V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle(),V.from("resource_shares").select("id",{count:"exact",head:!0}).eq("sender_id",s.id),V.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","template"),V.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","academy_video"),V.from("content_engagement_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("resource_type","toolbox"),V.from("activity_logs").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("agent_videos").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("contact_touch_logs").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("scorecard_transactions").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",s.id),V.from("innercircle_contacts").select("id").eq("owner_user_id",s.id),V.from("deal_pipeline").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id)]),be={},Ue=(He=$.data)==null?void 0:He.brokerage_id;be.share_resource=(F.count||0)>0,be.post_community=(z.count||0)>0,be.register_event=(Q.count||0)>0,be.view_template=(K.count||0)>0,be.watch_academy=(X.count||0)>0,be.use_toolbox=(Z.count||0)>0,be.launch_app=(re.count||0)>0,be.add_contact=(le.count||0)>0,be.create_video=(oe.count||0)>0,be.complete_touch=(ne.count||0)>0,be.add_transaction=(ie.count||0)>0,be.add_listing=(ye.count||0)>0,be.add_deal=(ve.count||0)>0;const Be=((Le=ce.data)==null?void 0:Le.map(Ie=>Ie.id))||[],De=[];Ue?De.push(V.from("profiles").select("id").eq("brokerage_id",Ue).neq("id",s.id).then(Ie=>{var Te;be.add_agent=(((Te=Ie.data)==null?void 0:Te.length)||0)>0})):be.add_agent=!1,Be.length>0?(De.push(V.from("contact_plan_cycles").select("id",{count:"exact",head:!0}).in("contact_id",Be).then(Ie=>{be.add_plan=(Ie.count||0)>0})),De.push(V.from("contact_popby_settings").select("id",{count:"exact",head:!0}).in("contact_id",Be).then(Ie=>{be.schedule_popby=(Ie.count||0)>0}))):(be.add_plan=!1,be.schedule_popby=!1),await Promise.all(De);const Ae=R.filter(Ie=>be[Ie.action_type]);if(Ae.length>0){const Ie=Ae.map(xe=>({user_id:s.id,item_id:xe.id})),{error:Te}=await V.from("onboarding_checklist_progress").upsert(Ie,{onConflict:"user_id,item_id",ignoreDuplicates:!0});if(!Te){const xe=Ae.map(et=>({item_id:et.id,completed_at:new Date().toISOString()}));i(et=>[...et,...xe])}}},y=async A=>{if(s!=null&&s.id)try{const{error:I}=await V.from("onboarding_checklist_progress").insert({user_id:s.id,item_id:A});if(I)throw I;i(D=>[...D,{item_id:A,completed_at:new Date().toISOString()}])}catch(I){console.error("Error marking item complete:",I)}},v=async()=>{if(s!=null&&s.id)try{const{error:A}=await V.from("onboarding_checklist_dismissed").insert({user_id:s.id});if(A)throw A;o(!0)}catch(A){console.error("Error dismissing checklist:",A)}},w=a.length,b=r.length,N=b>0&&w>=b,S=b>0?w/b*100:0;return{items:r,progress:a,isDismissed:l,loading:c,completedCount:w,totalCount:b,isComplete:N,progressPercentage:S,isItemComplete:A=>a.some(I=>I.item_id===A),markComplete:y,dismiss:v,refetch:m}}const q9t={add_agent:e.jsx(pr,{className:"h-4 w-4"}),share_resource:e.jsx(Ec,{className:"h-4 w-4"}),post_community:e.jsx(xi,{className:"h-4 w-4"}),register_event:e.jsx(on,{className:"h-4 w-4"}),view_template:e.jsx(Y1,{className:"h-4 w-4"}),watch_academy:e.jsx(Md,{className:"h-4 w-4"}),use_toolbox:e.jsx(Ay,{className:"h-4 w-4"}),launch_app:e.jsx(tR,{className:"h-4 w-4"}),add_deal:e.jsx(nv,{className:"h-4 w-4"}),add_listing:e.jsx(En,{className:"h-4 w-4"})},V9t={add_deal:"/mission-control/pipeline",add_listing:"/mission-control/listings/new",post_community:"/community",add_contact:"/mission-control/contacts"};function H9t(){const{items:s,isDismissed:t,loading:r,completedCount:n,totalCount:a,isComplete:i,progressPercentage:l,isItemComplete:o,markComplete:c,dismiss:d}=U9t(),h=br(),[m,x]=k.useState(!0);return r||t||a===0||i?null:e.jsxs(ke,{className:"mb-6 border-primary/20 bg-gradient-to-r from-primary/5 to-transparent",children:[e.jsxs(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:"p-2 bg-primary/10 rounded-lg",children:e.jsx(lv,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Get Started with LevelUp"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Complete these steps to make the most of your membership"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>x(!m),className:"h-8 w-8 p-0",children:m?e.jsx(Jf,{className:"h-4 w-4"}):e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0 text-muted-foreground hover:text-foreground",children:e.jsx(vr,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Progress"}),e.jsxs("span",{className:"font-medium",children:[n," of ",a," complete"]})]}),e.jsx(ei,{value:l,className:"h-2"})]})]}),m&&e.jsx(Pe,{className:"pt-0",children:e.jsx("div",{className:"space-y-3",children:s.map(y=>{const v=o(y.id);return e.jsxs("div",{className:It("flex items-start gap-3 p-3 rounded-lg transition-colors",v?"bg-muted/50":"bg-background hover:bg-muted/30 cursor-pointer"),onClick:()=>{if(v)return;const w=V9t[y.action_type];w?h(w):c(y.id)},children:[e.jsx("div",{className:"mt-0.5",children:v?e.jsx(In,{className:"h-5 w-5 text-primary"}):e.jsx(Ld,{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.jsx("span",{className:"text-muted-foreground",children:q9t[y.action_type]||e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("span",{className:It("font-medium",v&&"line-through text-muted-foreground"),children:y.title})]}),y.description&&e.jsx("p",{className:It("text-sm text-muted-foreground mt-1",v&&"line-through"),children:y.description})]})]},y.id)})})})]})}const fx=()=>mt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await V.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),Sm=s=>{const t=sa(),r=1e3,n=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+r-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=V.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 n(a)},enabled:!!t})},G9t=s=>mt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s}),Zrt=()=>{const s=sa();return mt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:r}=await V.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(r)throw r;const n={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{n[l.relationship_type_id]=(n[l.relationship_type_id]||0)+1})}),n},enabled:!!s})},Ufe=()=>{const s=Xt(),t=sa();return Ct({mutationFn:async r=>{const{tagIds:n,...a}=r,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,owner_user_id:t},{data:l,error:o}=await V.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(n&&n.length>0){const{error:c}=await V.from("innercircle_contact_tags").insert(n.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"]}),cn({title:"Contact created successfully"})},onError:r=>{cn({title:"Error creating contact",description:r.message,variant:"destructive"})}})},a3e=()=>{const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{tagIds:n,tags:a,...i}=r,l={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null},{data:o,error:c}=await V.from("innercircle_contacts").update(l).eq("id",t).select().single();if(c)throw c;if(n!==void 0&&(await V.from("innercircle_contact_tags").delete().eq("contact_id",t),n.length>0)){const{error:d}=await V.from("innercircle_contact_tags").insert(n.map(h=>({contact_id:t,relationship_type_id:h})));if(d)throw d}return o},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),cn({title:"Contact updated successfully"})},onError:t=>{cn({title:"Error updating contact",description:t.message,variant:"destructive"})}})},Xrt=()=>{const s=Xt();return Ct({mutationFn:async({contactId:t,spouseContactId:r})=>{if(r){const{error:n}=await V.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",t);if(n)throw n;const{error:a}=await V.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",r);if(a)throw a}else{const{data:n}=await V.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=n==null?void 0:n.spouse_contact_id,{error:i}=await V.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await V.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"]}),cn({title:"Spouse link updated"})},onError:t=>{cn({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},i3e=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("innercircle_contacts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),cn({title:"Contact deleted successfully"})},onError:t=>{cn({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},uB=()=>mt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await V.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),W9t=s=>mt({queryKey:["action-scripts",s],queryFn:async()=>{let t=V.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await t;if(n)throw n;return r}}),K9t=()=>mt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await V.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),Y9t=()=>{const s=Xt(),t=sa();return Ct({mutationFn:async({name:r,description:n})=>{const{data:a,error:i}=await V.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),cn({title:"Plan created successfully"})},onError:r=>{cn({title:"Error creating plan",description:r.message,variant:"destructive"})}})},Z9t=()=>{const s=Xt(),t=sa();return Ct({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:a,error:i}=await V.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",r).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await V.from("touchpoint_plans").insert({name:n,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(h=>({plan_id:l.id,month_number:h.month_number,action_type_id:h.action_type_id,default_script_id:h.default_script_id,notes:h.notes})),{error:d}=await V.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),cn({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{cn({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},X9t=()=>{const s=Xt();return Ct({mutationFn:async({id:t,name:r,description:n})=>{const{data:a,error:i}=await V.from("touchpoint_plans").update({name:r,description:n}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),cn({title:"Plan updated successfully"})}})},Q9t=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("touchpoint_plans").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),cn({title:"Plan deleted successfully"})}})},J9t=()=>{const s=Xt();return Ct({mutationFn:async({planId:t,items:r})=>{if(await V.from("touchpoint_plan_items").delete().eq("plan_id",t),r.length>0){const{error:n}=await V.from("touchpoint_plan_items").insert(r.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(n)throw n}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),cn({title:"Plan schedule updated"})}})},e$t=()=>{const s=Xt();return Ct({mutationFn:async({actionTypeId:t,title:r,scriptBody:n,emailSubject:a,tone:i})=>{const{data:{user:l}}=await V.auth.getUser(),{data:o,error:c}=await V.from("action_scripts").insert({action_type_id:t,title:r,script_body:n,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"]}),cn({title:"Script created successfully"})},onError:t=>{cn({title:"Error creating script",description:t.message,variant:"destructive"})}})},t$t=()=>{const s=sa();return mt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:r}=await V.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return t},enabled:!!s})},s$t=()=>{const s=Xt(),t=sa();return Ct({mutationFn:async({planId:r,relationshipTypeId:n,active:a})=>{const{data:i}=await V.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(i){const{error:l}=await V.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await V.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:r,relationship_type_id:n,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),cn({title:"Plan enrollment updated"})}})},hB=(s=7)=>{const t=sa();return mt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-s);const{data:n,error:a}=await V.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",r.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return n},enabled:!!t})},Qrt=()=>{const s=sa();return mt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(r)throw r;const n={};return t==null||t.forEach(a=>{n[a.contact_id]||(n[a.contact_id]=a.completed_at)}),n},enabled:!!s})},r$t=(s=90)=>{const{data:t}=Sm(),{data:r}=Qrt();if(!t||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-s);const a=t.filter(i=>{const l=r[i.id];return l?new Date(l){const s=Xt(),t=sa();return Ct({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await V.from("contact_touch_logs").insert({owner_user_id:t,contact_id:r,action_type_id:n,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(r,n)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),cn({title:"Action completed!"});try{const[l,o]=await Promise.all([V.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),V.from("action_types").select("name").eq("id",n.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";c&&V.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},Jrt="agentos_weekly_touch_goal",F8e=20,Wde=()=>{if(typeof window>"u")return F8e;const s=localStorage.getItem(Jrt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return F8e},ent=s=>{localStorage.setItem(Jrt,s.toString())},o3e=()=>{const{data:s}=hB(7),t=new Date;t.setHours(0,0,0,0);const r=new Date(t);r.setDate(t.getDate()-t.getDay());const n=(s==null?void 0:s.filter(l=>new Date(l.completed_at)>=r).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=Wde();return{actionsThisWeek:n,weeklyGoal:i,streak:a,progress:Math.min(n/i*100,100)}},n$t=()=>{const s=sa();return mt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(r)throw r;return t},enabled:!!s})},a$t=()=>{const s=Xt();return sa(),Ct({mutationFn:async()=>{const{data:t}=await V.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:r}=await V.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(!r)return;const{data:n}=await V.from("contact_plan_cycles").select("contact_id, plan_id"),a=new Set((n==null?void 0:n.map(l=>`${l.contact_id}-${l.plan_id}`))||[]),i=[];for(const l of r)for(const o of l.tags||[]){const c=t.find(d=>d.relationship_type_id===o.relationship_type_id);c&&!a.has(`${l.id}-${c.plan_id}`)&&i.push({contact_id:l.id,plan_id:c.plan_id,relationship_type_id:o.relationship_type_id})}if(i.length>0){const{error:l}=await V.from("contact_plan_cycles").insert(i);if(l)throw l}return i.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&cn({title:`${t} contact(s) enrolled in plans`})}})},tnt=()=>{const s=sa(),{data:t}=n$t(),{data:r}=hB(30);return mt({queryKey:["today-actions",s,t==null?void 0:t.length,r==null?void 0:r.length],queryFn:async()=>{var v;if(!t||t.length===0)return[];const{data:n}=await V.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((n==null?void 0:n.map(w=>w.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((r==null?void 0:r.filter(w=>new Date(w.completed_at)>=o).map(w=>`${w.contact_id}-${w.action_type_id}`))||[]);for(const w of t){if(!((v=w.plan)!=null&&v.items)||w.plan.items.length===0||!w.contact||a.has(w.contact_id))continue;const b=new Date(w.cycle_start_date),S=Math.floor((i.getTime()-b.getTime())/(30.44*24*60*60*1e3))%12+1,T=w.plan.items.find(A=>A.month_number===S);if(T&&T.action_type){const A=`${w.contact_id}-${T.action_type_id}`;if(!c.has(A)){const{data:I}=await V.from("relationship_types").select("name").eq("id",w.relationship_type_id).single();l.push({contact:w.contact,actionType:T.action_type,script:T.default_script||void 0,planName:w.plan.name,relationshipTypeName:(I==null?void 0:I.name)||"",monthNumber:S})}}}const d=5,h=i.getDate(),m=l.sort((w,b)=>w.contact.first_name.localeCompare(b.contact.first_name)),x=(h-1)%Math.max(1,m.length);return[...m.slice(x),...m.slice(0,x)].slice(0,d)},enabled:!!s&&!!t})};function i$t(){const s=br(),{data:t,isLoading:r}=tnt(),{data:n}=Sm(),a=o3e(),[i,l]=k.useState(Wde()),[o,c]=k.useState(""),[d,h]=k.useState(!1);k.useEffect(()=>{l(Wde())},[]);const m=()=>{const D=parseInt(o,10);if(isNaN(D)||D<1){cn({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(D),ent(D),h(!1),cn({title:"Goal updated",description:`Weekly touch goal set to ${D}`})},x=()=>{c(i.toString()),h(!0)},y=yf(new Date),v=Vl(y,7),w=D=>{if(!D)return null;const R=D.split(/[-/T]/);if(R.length<3)return null;const $=parseInt(R[1],10)-1,F=parseInt(R[2],10);return isNaN($)||isNaN(F)?null:new Date(y.getFullYear(),$,F)},b=(n==null?void 0:n.map(D=>{const R=w(D.birthday),$=w(D.home_anniversary),F=[];return R&&R>=y&&R<=v&&F.push({contact:D,type:"birthday",date:R,isToday:Ol(R,y)}),$&&$>=y&&$<=v&&F.push({contact:D,type:"anniversary",date:$,isToday:Ol($,y)}),F}).flat().sort((D,R)=>D.date.getTime()-R.date.getTime()).slice(0,3))||[],N=(n==null?void 0:n.filter(D=>{const R=w(D.birthday),$=w(D.home_anniversary);return R&&Ol(R,y)||$&&Ol($,y)}).length)||0,S=(t==null?void 0:t.length)||0,T=N+S,A=(a==null?void 0:a.actionsThisWeek)||0,I=(a==null?void 0:a.streak)||0;return r?e.jsx(ke,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Pe,{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(ke,{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(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:I>0&&e.jsxs(Ge,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(mc,{className:"h-3 w-3"}),I," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[T," 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(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(sl,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control")},children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:D=>{D.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:D=>{D.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:D=>{D.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(nv,{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(Pd,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(fs,{open:d,onOpenChange:h,children:[e.jsx(vi,{asChild:!0,children:e.jsx("button",{onClick:x,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(oo,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(ms,{className:"sm:max-w-[360px]",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Set Weekly Goal"}),e.jsx(Hr,{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(he,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(Ne,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:D=>c(D.target.value),placeholder:"20",onKeyDown:D=>{D.key==="Enter"&&m()}})]}),e.jsx(G,{onClick:m,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(ei,{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"]})]}),b.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(_h,{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:b.map((D,R)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${D.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:$=>{$.stopPropagation(),s(`/mission-control/contacts/${D.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[D.type==="birthday"?e.jsx(_h,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(En,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[D.contact.first_name," ",D.contact.last_name]}),D.isToday&&e.jsx(Ge,{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:D.isToday?D.type==="birthday"?"🎂":"🏠":_s(D.date,"EEE, MMM d")}),e.jsx(va,{className:"h-3 w-3"})]})]},`${D.contact.id}-${D.type}-${R}`))})]}),e.jsxs(G,{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(Ha,{className:"h-4 w-4"})]})]})]})}function o$t(s){return mt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(r)throw r;return t},enabled:!!s})}function l$t(s,t){return mt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let r=V.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(r=r.eq("category_id",t));const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!s})}function c$t(s,t=4){return mt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:r,error:n}=await V.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(n)throw n;return r},enabled:!!s})}function d$t(s){const t=Xt();return Ct({mutationFn:async r=>{const{data:n,error:a}=await V.from("brokerage_content").insert(r).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function u$t(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("brokerage_content").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function h$t(s){const t=Xt();return Ct({mutationFn:async r=>{const{data:n,error:a}=await V.from("brokerage_content_categories").insert({...r,brokerage_id:s}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function m$t(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("brokerage_content_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function f$t(s){const t=Xt();return Ct({mutationFn:async()=>{const r=[{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:n}=await V.from("brokerage_content_categories").upsert(r,{onConflict:"brokerage_id,name"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const p$t={video:Uo,pdf:ln,link:tl,event:on,graphic:fl},x$t={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 g$t(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function y$t(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 v$t({item:s}){const t=br(),r=p$t[s.content_type]||tl,n=x$t[s.content_type]||"",[a,i]=k.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?g$t(s.url):null);k.useEffect(()=>{l||!s.url||s.content_type!=="video"||!y$t(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(ke,{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(r,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Pe,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Ge,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${n}`,children:[e.jsx(r,{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:_s(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function b$t(){const{brokerageId:s}=js(),t=br(),{data:r=[],isLoading:n}=c$t(s,4);return!s||n||r.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(Sa,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:r.map(a=>e.jsx(v$t,{item:a},a.id))})]})}const snt=()=>mt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await V.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),rnt=s=>{const{user:t,brokerageId:r}=js();return mt({queryKey:["listings",s,r],queryFn:async()=>{let n=V.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&&(n=n.eq("status",s.status)),s!=null&&s.propertyType&&(n=n.eq("property_type",s.propertyType)),s!=null&&s.city&&(n=n.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(n=n.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(n=n.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(n=n.eq("open_to_referrals",!0));const{data:a,error:i}=await n;if(i)throw i;let l=a||[];if(r){const{data:o}=await V.from("profiles").select("id").eq("brokerage_id",r);if(o&&o.length>0){const c=o.map(m=>m.id);let d=V.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:h}=await d;if(h){const m=new Set(l.map(y=>y.id)),x=h.filter(y=>!m.has(y.id));l=[...l,...x]}}}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}})},nnt=()=>{const{user:s}=js();return mt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})},ant=s=>{const{user:t}=js();return mt({queryKey:["listing",s],queryFn:async()=>{const{data:r,error:n}=await V.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(n)throw n;return t&&await V.from("listing_views").insert({listing_id:s,viewer_id:t.id}),r},enabled:!!s})},_$t=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("listings").insert({...r,agent_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},w$t=()=>{const s=Xt();return Ct({mutationFn:async({agentId:t,...r})=>{const{data:n,error:a}=await V.from("listings").insert({...r,agent_id:t}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},j$t=()=>{const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("listings").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},int=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("listings").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},N$t=()=>{const s=Xt();return Ct({mutationFn:async({listingId:t,photoUrl:r,isPrimary:n=!1})=>{const{data:a,error:i}=await V.from("listing_photos").insert({listing_id:t,photo_url:r,is_primary:n}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},k$t=()=>{const s=Xt();return Ct({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await V.from("listing_photos").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},S$t=()=>{const s=Xt();return Ct({mutationFn:async({photos:t})=>{var i;const r=t.map(l=>V.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(r)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},C$t=()=>{const s=Xt();return Ct({mutationFn:async({photoId:t,listingId:r})=>{const{error:n}=await V.from("listing_photos").update({is_primary:!1}).eq("listing_id",r);if(n)throw n;const{error:a}=await V.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},T$t=()=>{const{user:s}=js();return mt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})},ont=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await V.from("listing_saves").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await V.from("listing_saves").delete().eq("id",n.id),{saved:!1}):(await V.from("listing_saves").insert({listing_id:r,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},lnt=s=>{const{user:t}=js();return mt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await V.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},E$t=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n}=await V.from("listing_follows").select("id").eq("listing_id",r).eq("agent_id",t.id).maybeSingle();return n?(await V.from("listing_follows").delete().eq("id",n.id),{following:!1}):(await V.from("listing_follows").insert({listing_id:r,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},A$t=s=>{const{user:t}=js();return mt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:r}=await V.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!r},enabled:!!t&&!!s})},M$t=()=>{const{user:s}=js();return Ct({mutationFn:async({listingId:t,shareType:r})=>{if(!s)throw new Error("Not authenticated");const{error:n}=await V.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:r});if(n)throw n}})},I$t=()=>{const{user:s}=js();return mt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,r]=await Promise.all([V.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),V.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:r.data||[]}},enabled:!!s})},L$t=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async({listingId:r,listingAgentId:n,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await V.from("listing_referrals").insert({listing_id:r,sender_agent_id:t.id,listing_agent_id:n,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},P$t=()=>mt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await V.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 r=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:n}=await V.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;n==null||n.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:r,topListers:i}}}),D$t=()=>{const{user:s,brokerageId:t}=js();return mt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:r}=await V.from("profiles").select("id").eq("brokerage_id",t);if(!r||r.length===0)return[];const n=r.map(l=>l.id),{data:a,error:i}=await V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",n).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},cnt=({className:s,variant:t="default"})=>e.jsx(Ge,{variant:"outline",className:It("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"}),R$t={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"},O$t={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function F$t(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function B$t(){const s=br(),{data:t,isLoading:r}=snt(),{data:n,isLoading:a}=rnt({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(n==null?void 0:n.filter(h=>h.is_approved&&h.is_public))||[],l=i.filter(h=>h.is_featured),o=i.filter(h=>!h.is_featured),c=[...l,...o].slice(0,6),d=r||a;return!d&&!t?null:d?e.jsx(ke,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Pe,{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(cnt,{})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(En,{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(G,{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(h=>{var x,y;const m=((x=h.photos)==null?void 0:x.find(v=>v.is_primary))||((y=h.photos)==null?void 0:y[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${h.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:[m!=null&&m.photo_url?e.jsx("img",{src:m.photo_url,alt:`${h.city}, ${h.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(En,{className:"h-8 w-8 text-muted-foreground/50"})}),h.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(Ge,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Xn,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Ge,{className:`text-[10px] px-1.5 py-0.5 ${R$t[h.status]}`,children:O$t[h.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:F$t(h.price)}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[h.city,", ",h.state]}),(h.bedrooms||h.bathrooms)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[h.bedrooms&&`${h.bedrooms} bed`,h.bedrooms&&h.bathrooms&&" · ",h.bathrooms&&`${h.bathrooms} bath`]})]})]},h.id)})})]})}function dnt(s=10,t){return mt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:r}=await V.from("user_roles").select("user_id").eq("role","admin"),n=new Set((r==null?void 0:r.map(x=>x.user_id))||[]);let a=null;if(t){const{data:x}=await V.from("profiles").select("id").eq("brokerage_id",t);a=new Set((x==null?void 0:x.map(y=>y.id))||[])}const{data:i,error:l}=await V.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+n.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(x=>!n.has(x.user_id));a&&(o=o.filter(x=>a.has(x.user_id)));const c=o.slice(0,s),d=c.map(x=>x.user_id),{data:h}=await V.from("profiles").select("id, name").in("id",d),m=new Map((h==null?void 0:h.map(x=>[x.id,{name:x.name}]))||[]);return c.map(x=>({user_id:x.user_id,total_points:x.total_points,total_events_attended:x.total_events_attended,current_streak:x.current_streak,profile:m.get(x.user_id)||null}))}})}function unt(s){return mt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return t},enabled:!!s})}function hnt(s){return mt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function mnt(s,t){return mt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:r}=await V.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!r)return null;const{data:n}=await V.from("user_roles").select("user_id").eq("role","admin"),a=new Set((n==null?void 0:n.map(c=>c.user_id))||[]),{data:i,error:l}=await V.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",r.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 V.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(h=>h.id))||[]);o=o.filter(h=>d.has(h.user_id))}return o.length+1},enabled:!!s})}function z$t(){const{user:s,brokerageId:t,isAdmin:r}=js();br();const n=!!t,[a,i]=k.useState("brokerage"),l=()=>{if(r)return null;if(n)return a==="global"?null:t},{data:o,isLoading:c}=dnt(5,l()),{data:d}=unt(s==null?void 0:s.id),{data:h}=mnt(s==null?void 0:s.id,l()),{data:m}=hnt(s==null?void 0:s.id),x=r||n,y=()=>r?"Agent Leaderboard":n?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4 text-yellow-500"}),y()]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2",children:[...Array(x?5:3)].map((w,b)=>e.jsx(Fs,{className:"h-10 w-full"},b))})})]});const v=w=>w===0?e.jsx(Gi,{className:"h-4 w-4 text-yellow-500 mx-auto"}):w===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):w===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:w+1});if(x){const w=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4 text-yellow-500"}),y()]}),!r&&n&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(G,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(G,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Pe,{children:[!r&&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:["#",h||"-"]})]}),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:[w.map((b,N)=>{var S,T,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${b.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":N===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:v(N)}),e.jsx(Nn,{className:"h-6 w-6",children:e.jsx(kn,{className:"text-xs",children:((T=(S=b.profile)==null?void 0:S.name)==null?void 0:T.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=b.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:b.total_points})]},b.user_id)}),w.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Yn,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(ii,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(va,{className:"h-4 w-4"})]})]})]})}return e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Pe,{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(mc,{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," 🔥"]})]}),m&&m.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(Yl,{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:[m.slice(0,4).map(w=>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:w.badge_name},w.id)),m.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",m.length-4," more"]})]})]}),e.jsxs(Yn,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(ii,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(va,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Xn,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Yn,{to:"/reward-store",className:"mt-3 inline-flex items-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(ii,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(va,{className:"h-4 w-4"})]})]})})]})}const WI=()=>mt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await V.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),l3e=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{data:n}=await V.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",r.trim()),a=(n||[]).find(o=>o.name.toLowerCase()===r.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await V.from("lead_sources").insert({name:r,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"]}),ue.success("Lead source added")},onError:r=>{ue.error("Failed to add lead source"),console.error(r)}})},$$t=()=>{const s=Xt();return Ct({mutationFn:async({id:t,name:r})=>{const{error:n}=await V.from("lead_sources").update({name:r}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ue.success("Lead source updated")},onError:t=>{ue.error(t.message||"Failed to update lead source")}})},U$t=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("lead_sources").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ue.success("Lead source removed")},onError:t=>{ue.error(t.message||"Failed to remove lead source")}})},c3e=(s,t)=>{const{user:r,isAdmin:n}=js(),a=n&&t?t:r==null?void 0:r.id;return mt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=V.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})},d3e=s=>{const{user:t,isAdmin:r}=js(),n=r&&s?s:t==null?void 0:t.id;return mt({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:a,error:i}=await V.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",n).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!n})},Vfe=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{data:n,error:a}=await V.from("scorecard_transactions").insert({...r,owner_user_id:t.id}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ue.success("Transaction added")},onError:r=>{ue.error("Failed to add transaction"),console.error(r)}})},q$t=()=>{const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("scorecard_transactions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ue.success("Transaction updated")},onError:t=>{ue.error("Failed to update transaction"),console.error(t)}})},V$t=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("scorecard_transactions").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ue.success("Transaction deleted")},onError:t=>{ue.error("Failed to delete transaction"),console.error(t)}})},fnt=(s,t)=>{const{user:r,isAdmin:n}=js(),a=n&&t?t:r==null?void 0:r.id;return mt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await V.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},H$t=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{data:n,error:a}=await V.from("scorecard_goals").upsert({...r,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["scorecard-goals",n.year]}),ue.success("Goals saved")},onError:r=>{ue.error("Failed to save goals"),console.error(r)}})},Hfe=()=>{const{user:s}=js();return mt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t},enabled:!!(s!=null&&s.id)})},G$t=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{data:n,error:a}=await V.from("scorecard_settings").upsert({...r,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),ue.success("Settings saved")},onError:r=>{ue.error("Failed to save settings"),console.error(r)}})},pnt=(s,t)=>{const{data:r,isLoading:n}=c3e(s,t),{data:a,isLoading:i}=d3e(t),{data:l}=Hfe(),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 h=d.filter(I=>I.transaction_type==="buyer").length,m=d.filter(I=>I.transaction_type==="seller").length,x=d.reduce((I,D)=>I+Number(D.sale_price),0),y=d.reduce((I,D)=>I+(Number(D.commission_amount)||0),0),v=d.reduce((I,D)=>{const R=Number(D.commission_amount)||0;if(!R)return I;let $=R;return D.brokerage_split_pct&&($-=R*(D.brokerage_split_pct/100)),D.team_split_pct&&($-=R*(D.team_split_pct/100)),D.franchise_fee_pct&&($-=R*(D.franchise_fee_pct/100)),D.referral_fee_pct&&($-=R*(D.referral_fee_pct/100)),D.transaction_fee&&($-=D.transaction_fee),I+Math.max(0,$)},0),w={};d.forEach(I=>{var R;const D=((R=I.lead_source)==null?void 0:R.name)||"Unknown";w[D]=(w[D]||0)+1});const b=Object.entries(w).map(([I,D])=>({name:I,count:D})).sort((I,D)=>D.count-I.count),N=b[0]||null,S={};d.forEach(I=>{const D=Fl(I.close_date).toLocaleString("default",{month:"short"});S[D]=(S[D]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(I=>({month:I,count:S[I]||0}));return{totalTransactions:d.length,buyerCount:h,sellerCount:m,totalVolume:x,averagePrice:d.length>0?x/d.length:0,totalCommission:o?y:0,totalNetToAgent:o?v:0,topLeadSource:N,transactionsByMonth:A,leadSourceBreakdown:b}};return{yearStats:c(r),lifetimeStats:c(a),isLoading:n||i,showCommission:o}},W$t=()=>{const{isAdmin:s}=js();return mt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:r}=await V.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(r)throw r;const n=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await V.from("profiles").select("id, name, email").in("id",n);if(i)throw i;return a},enabled:s})},rw={recency:40,touchpoints:30,transactions:20,referrals:10},B8e={warm:70,cooling:40};function K$t(s){return s===null?0:s<=14?rw.recency:s<=30?rw.recency*.85:s<=60?rw.recency*.65:s<=90?rw.recency*.4:s<=180?rw.recency*.2:rw.recency*.05}function Y$t(s){const t=Math.min(s/12,1);return Math.round(rw.touchpoints*t)}function Z$t(s){return s?rw.transactions:0}function X$t(){return 0}function Q$t(s){return s>=B8e.warm?"warm":s>=B8e.cooling?"cooling":"at-risk"}function Gfe(){const{data:s,isLoading:t}=Sm(),{data:r}=Qrt(),{data:n}=hB(365),{data:a}=d3e(),i=k.useMemo(()=>{if(!s)return[];const o=new Date,c=t4(o,12),d={};n==null||n.forEach(m=>{new Date(m.completed_at)>=c&&(d[m.contact_id]=(d[m.contact_id]||0)+1)});const h=new Set((a==null?void 0:a.filter(m=>m.contact_id).map(m=>m.contact_id))||[]);return s.map(m=>{const x=(r==null?void 0:r[m.id])||null,y=x?pg(o,new Date(x)):null,v=d[m.id]||0,w=h.has(m.id),b=K$t(y),N=Y$t(v),S=Z$t(w),T=X$t(),A=Math.round(b+N+S+T),I={score:A,status:Q$t(A),breakdown:{recency:Math.round(b),touchpoints:Math.round(N),transactions:Math.round(S),referrals:Math.round(T)},lastTouchDate:x,daysSinceTouch:y,touchCountLast12Months:v,hasTransaction:w};return{...m,relationshipScore:I}})},[s,r,n,a]),l=k.useMemo(()=>{const o=i.filter(x=>x.relationshipScore.status==="warm").length,c=i.filter(x=>x.relationshipScore.status==="cooling").length,d=i.filter(x=>x.relationshipScore.status==="at-risk").length,h=i.length,m=h>0?Math.round(i.reduce((x,y)=>x+y.relationshipScore.score,0)/h):0;return{warm:o,cooling:c,atRisk:d,total:h,averageScore:m}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function xnt(){const s=br(),{stats:t,contactsWithScores:r,isLoading:n}=Gfe();if(n)return e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Fs,{className:"h-5 w-40"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(Fs,{className:"h-20 w-full"}),e.jsx(Fs,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(G,{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=r.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(bo,{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(Pe,{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(ei,{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(ei,{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(ei,{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(va,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(va,{className:"h-4 w-4 ml-1"})]})]})]})}const J$t=()=>{var le;const{user:s,isAdmin:t}=js(),r=br(),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState([]),[d,h]=k.useState([]),[m,x]=k.useState([]),[y,v]=k.useState([]),[w,b]=k.useState(new Set),[N,S]=k.useState([]),[T,A]=k.useState([]),[I,D]=k.useState([]),[R,$]=k.useState(null),[F,z]=k.useState(!0);k.useEffect(()=>{Q()},[s]);const Q=async()=>{var oe,ne,ie,ye,ce;try{const[ve,be,Ue,Be,De,Ae,He,Le,Ie,Te,xe]=await Promise.all([V.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),V.from("app_tiles").select("*").order("name"),V.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),V.from("events").select("*").order("event_date",{ascending:!0}),V.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),V.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),V.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.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),V.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),V.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(oe=xe.data)!=null&&oe.name&&$(xe.data.name);const et=((ne=ve.data)==null?void 0:ne.map(_e=>_e.tag))||[],fe=new Set(((ie=Ue.data)==null?void 0:ie.map(_e=>_e.app_id))||[]);b(fe);const Oe=(((ye=be.data)==null?void 0:ye.filter(_e=>!_e.required_tags||_e.required_tags.length===0?!0:_e.required_tags.some(Re=>et.includes(Re))))||[]).sort((_e,Re)=>_e.name==="LevelUp Members Portal"?-1:Re.name==="LevelUp Members Portal"?1:0);a(Oe.slice(0,6));const Ye=((ce=Be.data)==null?void 0:ce.filter(_e=>OA(_e.event_date)!=="ended"))||[];l(Ye.slice(0,4)),S(De.data||[]),c(Ae.data||[]),h(He.data||[]),x(Le.data||[]),v(Ie.data||[]);const We=Te.data||[];A(We.filter(_e=>_e.placement==="top")),D(We.filter(_e=>_e.placement==="between"))}catch(ve){console.error("Error loading dashboard:",ve),ue.error("Failed to load dashboard data")}finally{z(!1)}},K=async oe=>{var ie;const ne=window.open("about:blank","_blank");try{await V.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:oe.app_id,app_name:oe.name,user_agent:navigator.userAgent});const{data:ye,error:ce}=await V.functions.invoke("sso-launch",{body:{app_id:oe.app_id}});if(ce)throw ce;ye!=null&&ye.redirect_url?ne&&!ne.closed?(ne.location.href=ye.redirect_url,(ie=ne.focus)==null||ie.call(ne)):window.location.assign(ye.redirect_url):(ne==null||ne.close(),ue.error("Launch link unavailable"))}catch(ye){ne==null||ne.close(),console.error("Error launching app:",ye),ue.error("Failed to launch app")}},X=oe=>N==null?void 0:N.some(ne=>ne.event_id===oe),Z=oe=>{const ne=N==null?void 0:N.find(ie=>ie.event_id===oe);return ne==null?void 0:ne.zoom_join_url};if(F)return e.jsx(ws,{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 re=oe=>I.filter(ne=>ne.section_after===oe);return e.jsxs(ws,{title:"Dashboard",children:[e.jsx($9t,{events:i,registrations:N,onNavigateToEvents:()=>r("/events")}),T.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(sD,{banners:T})}),e.jsx(H9t,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(R||((le=s==null?void 0:s.user_metadata)==null?void 0:le.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(i$t,{}),e.jsx(xnt,{}),e.jsx(z$t,{})]}),e.jsx(b$t,{}),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(G,{variant:"ghost",size:"sm",onClick:()=>r("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(on,{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(oe=>{const ne=X(oe.id),ie=Z(oe.id)||oe.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 ${O8e(oe.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>r("/events"),children:[O8e(oe.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(gb,{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(oe.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(oe.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:oe.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(oe.event_date))," at ",_8(new Date(oe.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:ne?e.jsxs(G,{size:"sm",variant:"default",className:"gap-1",onClick:ye=>{ye.stopPropagation(),window.open(ie,"_blank")},children:[e.jsx(Qr,{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(va,{className:"h-4 w-4"})]})})]},oe.id)})})]}),re("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(sD,{banners:re("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(G,{variant:"ghost",size:"sm",onClick:()=>r("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),m.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(rf,{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:m.map(oe=>e.jsxs("div",{onClick:()=>r(`/academy/${oe.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:[oe.thumbnail_url?e.jsx("img",{src:oe.thumbnail_url,alt:oe.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(rf,{className:"h-8 w-8 text-muted-foreground/50"})}),oe.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:oe.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:oe.title})})]},oe.id))})]}),re("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(sD,{banners:re("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(G,{variant:"ghost",size:"sm",onClick:()=>r("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Qh,{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(oe=>e.jsxs("div",{onClick:()=>r(`/toolbox/${oe.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:oe.featured_image_url?e.jsx("img",{src:oe.featured_image_url,alt:oe.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(Qh,{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:oe.name})})]},oe.id))})]}),re("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(sD,{banners:re("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(G,{variant:"ghost",size:"sm",onClick:()=>r("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(hb,{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(oe=>e.jsxs("div",{onClick:()=>r("/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:oe.preview_image_url?e.jsx("img",{src:oe.preview_image_url,alt:oe.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(hb,{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:oe.name})})]},oe.id))})]}),re("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(sD,{banners:re("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(B$t,{})}),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(G,{variant:"ghost",size:"sm",onClick:()=>r("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),n.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ag,{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:n.map(oe=>{const ne=w.has(oe.id);return e.jsxs("div",{onClick:()=>K(oe),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:oe.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:oe.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:oe.description})]}),ne&&e.jsx(ag,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},oe.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(G,{variant:"ghost",size:"sm",onClick:()=>r("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Ha,{className:"h-4 w-4"})]})]}),y.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(jr,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:y.map(oe=>e.jsxs("div",{onClick:()=>window.open(oe.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:oe.preview_image_url?e.jsx("img",{src:oe.preview_image_url,alt:oe.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(jr,{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:oe.name}),oe.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:oe.description})]})]},oe.id))})]})]})};var gnt="AlertDialog",[eUt,FUs]=pd(gnt,[NQe]),Hb=NQe(),ynt=s=>{const{__scopeAlertDialog:t,...r}=s,n=Hb(t);return e.jsx(afe,{...n,...r,modal:!0})};ynt.displayName=gnt;var tUt="AlertDialogTrigger",vnt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=Hb(r);return e.jsx(VCe,{...a,...n,ref:t})});vnt.displayName=tUt;var sUt="AlertDialogPortal",bnt=s=>{const{__scopeAlertDialog:t,...r}=s,n=Hb(t);return e.jsx(ife,{...n,...r})};bnt.displayName=sUt;var rUt="AlertDialogOverlay",_nt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=Hb(r);return e.jsx(zI,{...a,...n,ref:t})});_nt.displayName=rUt;var FA="AlertDialogContent",[nUt,aUt]=eUt(FA),iUt=qKe("AlertDialogContent"),wnt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,children:n,...a}=s,i=Hb(r),l=k.useRef(null),o=Ga(t,l),c=k.useRef(null);return e.jsx(JEt,{contentName:FA,titleName:jnt,docsSlug:"alert-dialog",children:e.jsx(nUt,{scope:r,cancelRef:c,children:e.jsxs($I,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:Vr(a.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=c.current)==null||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsx(iUt,{children:n}),e.jsx(lUt,{contentRef:l})]})})})});wnt.displayName=FA;var jnt="AlertDialogTitle",Nnt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=Hb(r);return e.jsx(JF,{...a,...n,ref:t})});Nnt.displayName=jnt;var knt="AlertDialogDescription",Snt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=Hb(r);return e.jsx(eB,{...a,...n,ref:t})});Snt.displayName=knt;var oUt="AlertDialogAction",Cnt=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,a=Hb(r);return e.jsx(tB,{...a,...n,ref:t})});Cnt.displayName=oUt;var Tnt="AlertDialogCancel",Ent=k.forwardRef((s,t)=>{const{__scopeAlertDialog:r,...n}=s,{cancelRef:a}=aUt(Tnt,r),i=Hb(r),l=Ga(t,a);return e.jsx(tB,{...i,...n,ref:l})});Ent.displayName=Tnt;var lUt=({contentRef:s})=>{const t=`\`${FA}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${FA}\` by passing a \`${knt}\` 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 \`${FA}\`. 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 k.useEffect(()=>{var n;document.getElementById((n=s.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},cUt=ynt,dUt=vnt,uUt=bnt,Ant=_nt,Mnt=wnt,Int=Cnt,Lnt=Ent,Pnt=Nnt,Dnt=Snt;const Ko=cUt,vm=dUt,hUt=uUt,Rnt=k.forwardRef(({className:s,...t},r)=>e.jsx(Ant,{className:It("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:r}));Rnt.displayName=Ant.displayName;const Do=k.forwardRef(({className:s,...t},r)=>e.jsxs(hUt,{children:[e.jsx(Rnt,{}),e.jsx(Mnt,{ref:r,className:It("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})]}));Do.displayName=Mnt.displayName;const Ro=({className:s,...t})=>e.jsx("div",{className:It("flex flex-col space-y-2 text-center sm:text-left",s),...t});Ro.displayName="AlertDialogHeader";const Oo=({className:s,...t})=>e.jsx("div",{className:It("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Oo.displayName="AlertDialogFooter";const Fo=k.forwardRef(({className:s,...t},r)=>e.jsx(Pnt,{ref:r,className:It("text-lg font-semibold",s),...t}));Fo.displayName=Pnt.displayName;const Bo=k.forwardRef(({className:s,...t},r)=>e.jsx(Dnt,{ref:r,className:It("text-sm text-muted-foreground",s),...t}));Bo.displayName=Dnt.displayName;const Co=k.forwardRef(({className:s,...t},r)=>e.jsx(Int,{ref:r,className:It(jM(),s),...t}));Co.displayName=Int.displayName;const zo=k.forwardRef(({className:s,...t},r)=>e.jsx(Lnt,{ref:r,className:It(jM({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));zo.displayName=Lnt.displayName;const mUt=[{key:"contacts",label:"Contacts",icon:Cn,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:$4,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:Qh,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:Jr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:En,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:Zw,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Ca,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:Vp,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:bh,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:Ty,description:"Create and manage smart presentations"}];function fUt(){var R;const{user:s}=js(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState({email:"",name:"",password:""}),[y,v]=k.useState("create"),[w,b]=k.useState(!1),[N,S]=k.useState(null);k.useEffect(()=>{s&&T()},[s]);const T=async()=>{if(s){a(!0);try{const{data:$,error:F}=await V.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(F)throw F;if($&&$.length>0){const z=$.map(X=>X.assistant_id),{data:Q}=await V.from("profiles").select("id, name, email").in("id",z),K=$.map(X=>{const Z=Q==null?void 0:Q.find(re=>re.id===X.assistant_id);return{...X,permissions:X.permissions,assistant_profile:Z?{name:Z.name||"",email:Z.email||""}:void 0}});r(K)}else r([])}catch($){console.error("Error loading assistants:",$)}finally{a(!1)}}},A=async()=>{if(s){if(y==="link"){if(!m.email.trim()){ue.error("Please enter the assistant's email");return}b(!0);try{const{data:{session:$}}=await V.auth.getSession();if(!$)throw new Error("Not authenticated");const{data:F,error:z}=await V.from("profiles").select("id, name, email").eq("email",m.email.trim().toLowerCase()).single();if(z||!F){ue.error("No account found with that email. Try creating a new assistant instead.");return}const{data:Q}=await V.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",F.id);if(Q&&Q.length>0){ue.error("This assistant is already assigned to you");return}const K=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$.access_token}`},body:JSON.stringify({userId:F.id,role:"assistant",action:"add",agentId:s.id})}),X=await K.json();if(!K.ok)throw new Error(X.error||"Failed to assign assistant role");const{error:Z}=await V.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(Z)throw Z;ue.success(`${F.name||F.email} linked as your assistant`),l(!1),x({email:"",name:"",password:""}),T()}catch($){console.error("Error linking assistant:",$),ue.error($.message||"Failed to link assistant")}finally{b(!1)}return}if(!m.email.trim()||!m.name.trim()||!m.password.trim()){ue.error("Please fill in all fields");return}if(m.password.length<6){ue.error("Password must be at least 6 characters");return}b(!0);try{const{data:{session:$}}=await V.auth.getSession();if(!$)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 ${$.access_token}`},body:JSON.stringify({email:m.email.trim(),password:m.password,name:m.name.trim(),purpose:"assistant"})}),z=await F.json();if(!F.ok)throw new Error(z.error||"Failed to create assistant account");const Q=z.userId||z.id;if(!Q)throw new Error("No user ID returned");const K=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$.access_token}`},body:JSON.stringify({userId:Q,role:"assistant",action:"add",agentId:s.id})}),X=await K.json();if(!K.ok)throw new Error(X.error||"Failed to assign assistant role");const{error:Z}=await V.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:Q,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(Z)throw Z;ue.success(`Assistant account created for ${m.name.trim()}`),l(!1),x({email:"",name:"",password:""}),T()}catch($){console.error("Error adding assistant:",$),ue.error($.message||"Failed to add assistant")}finally{b(!1)}}},I=async()=>{if(!(!d||!s))try{const{data:{session:$}}=await V.auth.getSession();if(!$)throw new Error("Not authenticated");const{error:F}=await V.from("agent_assistant_assignments").delete().eq("id",d.id);if(F)throw F;const{data:z}=await V.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 ${$.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ue.success("Assistant removed"),c(!1),h(null),T()}catch($){console.error("Error removing assistant:",$),ue.error($.message||"Failed to remove assistant")}},D=async($,F,z)=>{S($);try{const Q=t.find(Z=>Z.id===$);if(!Q)return;const K={...Q.permissions,[F]:z},{error:X}=await V.from("agent_assistant_assignments").update({permissions:K}).eq("id",$);if(X)throw X;r(Z=>Z.map(re=>re.id===$?{...re,permissions:K}:re))}catch(Q){console.error("Error updating permissions:",Q),ue.error("Failed to update permissions")}finally{S(null)}};return n?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Nr,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(G,{size:"sm",onClick:()=>{v("create"),l(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Pe,{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($=>{var F,z,Q,K;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(Nn,{className:"h-10 w-10",children:e.jsx(kn,{children:((z=(F=$.assistant_profile)==null?void 0:F.name)==null?void 0:z.split(" ").map(X=>X[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Q=$.assistant_profile)==null?void 0:Q.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((K=$.assistant_profile)==null?void 0:K.email)||""})]}),e.jsxs(Ge,{variant:"secondary",className:"ml-2",children:[e.jsx(Wu,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{h($),c(!0)},children:e.jsx(yr,{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:mUt.map(X=>{const Z=X.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(Z,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:X.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:X.description})]})]}),e.jsx(_r,{checked:$.permissions[X.key]||!1,onCheckedChange:re=>D($.id,X.key,re),disabled:N===$.id})]},X.key)})})]})]},$.id)})})})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add Assistant"}),e.jsx(Hr,{children:y==="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(G,{variant:y==="create"?"default":"outline",size:"sm",onClick:()=>v("create"),children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(G,{variant:y==="link"?"default":"outline",size:"sm",onClick:()=>v("link"),children:[e.jsx(po,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[y==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"assistant-name",children:"Name"}),e.jsx(Ne,{id:"assistant-name",value:m.name,onChange:$=>x({...m,name:$.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"assistant-email",children:"Email"}),e.jsx(Ne,{id:"assistant-email",type:"email",value:m.email,onChange:$=>x({...m,email:$.target.value}),placeholder:"assistant@email.com"})]}),y==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(Ne,{id:"assistant-password",type:"password",value:m.password,onChange:$=>x({...m,password:$.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(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(G,{onClick:A,disabled:w,children:[w&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),y==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Ko,{open:o,onOpenChange:c,children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Remove Assistant?"}),e.jsxs(Bo,{children:["This will remove ",(R=d==null?void 0:d.assistant_profile)==null?void 0:R.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function zh(s){this.content=s}zh.prototype={constructor:zh,find:function(s){for(var t=0;t>1}};zh.from=function(s){if(s instanceof zh)return s;var t=[];if(s)for(var r in s)t.push(r,s[r]);return new zh(t)};function Ont(s,t,r){for(let n=0;;n++){if(n==s.childCount||n==t.childCount)return s.childCount==t.childCount?null:r;let a=s.child(n),i=t.child(n);if(a==i){r+=a.nodeSize;continue}if(!a.sameMarkup(i))return r;if(a.isText&&a.text!=i.text){for(let l=0;a.text[l]==i.text[l];l++)r++;return r}if(a.content.size||i.content.size){let l=Ont(a.content,i.content,r+1);if(l!=null)return l}r+=a.nodeSize}}function Fnt(s,t,r,n){for(let a=s.childCount,i=t.childCount;;){if(a==0||i==0)return a==i?null:{a:r,b:n};let l=s.child(--a),o=t.child(--i),c=l.nodeSize;if(l==o){r-=c,n-=c;continue}if(!l.sameMarkup(o))return{a:r,b:n};if(l.isText&&l.text!=o.text){let d=0,h=Math.min(l.text.length,o.text.length);for(;dt&&n(c,a+o,i||null,l)!==!1&&c.content.size){let h=o+1;c.nodesBetween(Math.max(0,t-h),Math.min(c.content.size,r-h),n,a+h)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,r,n,a){let i="",l=!0;return this.nodesBetween(t,r,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,r-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)&&n&&(l?l=!1:i+=n),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let r=this.lastChild,n=t.firstChild,a=this.content.slice(),i=0;for(r.isText&&r.sameMarkup(n)&&(a[a.length-1]=r.withText(r.text+n.text),i=1);it)for(let i=0,l=0;lt&&((lr)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,r-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,r-l-1))),n.push(o),a+=o.nodeSize),l=c}return new Ym(n,a)}cutByIndex(t,r){return t==r?Ym.empty:t==0&&r==this.content.length?this:new Ym(this.content.slice(t,r))}replaceChild(t,r){let n=this.content[t];if(n==r)return this;let a=this.content.slice(),i=this.size+r.nodeSize-n.nodeSize;return a[t]=r,new Ym(a,i)}addToStart(t){return new Ym([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Ym(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let r=0;rthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let r=0,n=0;;r++){let a=this.child(r),i=n+a.nodeSize;if(i>=t)return i==t?X9(r+1,i):X9(r,n);n=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,r){if(!r)return Ym.empty;if(!Array.isArray(r))throw new RangeError("Invalid input for Fragment.fromJSON");return new Ym(r.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Ym.empty;let r,n=0;for(let a=0;athis.type.rank&&(r||(r=t.slice(0,a)),r.push(this),n=!0),r&&r.push(i)}}return r||(r=t.slice()),n||r.push(this),r}removeFromSet(t){for(let r=0;rn.type.rank-a.type.rank),r}};Kl.none=[];class Yde extends Error{}class Un{constructor(t,r,n){this.content=t,this.openStart=r,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,r){let n=znt(this.content,t+this.openStart,r);return n&&new Un(n,this.openStart,this.openEnd)}removeBetween(t,r){return new Un(Bnt(this.content,t+this.openStart,r+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,r){if(!r)return Un.empty;let n=r.openStart||0,a=r.openEnd||0;if(typeof n!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Un(dn.fromJSON(t,r.content),n,a)}static maxOpen(t,r=!0){let n=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.firstChild)n++;for(let i=t.lastChild;i&&!i.isLeaf&&(r||!i.type.spec.isolating);i=i.lastChild)a++;return new Un(t,n,a)}}Un.empty=new Un(dn.empty,0,0);function Bnt(s,t,r){let{index:n,offset:a}=s.findIndex(t),i=s.maybeChild(n),{index:l,offset:o}=s.findIndex(r);if(a==t||i.isText){if(o!=r&&!s.child(l).isText)throw new RangeError("Removing non-flat range");return s.cut(0,t).append(s.cut(r))}if(n!=l)throw new RangeError("Removing non-flat range");return s.replaceChild(n,i.copy(Bnt(i.content,t-a-1,r-a-1)))}function znt(s,t,r,n){let{index:a,offset:i}=s.findIndex(t),l=s.maybeChild(a);if(i==t||l.isText)return n&&!n.canReplace(a,a,r)?null:s.cut(0,t).append(r).append(s.cut(t));let o=znt(l.content,t-i-1,r,l);return o&&s.replaceChild(a,l.copy(o))}function pUt(s,t,r){if(r.openStart>s.depth)throw new Yde("Inserted content deeper than insertion position");if(s.depth-r.openStart!=t.depth-r.openEnd)throw new Yde("Inconsistent open depths");return $nt(s,t,r,0)}function $nt(s,t,r,n){let a=s.index(n),i=s.node(n);if(a==t.index(n)&&n=0&&s.isText&&s.sameMarkup(t[r])?t[r]=s.withText(t[r].text+s.text):t.push(s)}function hO(s,t,r,n){let a=(t||s).node(r),i=0,l=t?t.index(r):a.childCount;s&&(i=s.index(r),s.depth>r?i++:s.textOffset&&(o3(s.nodeAfter,n),i++));for(let o=i;oa&&Hje(s,t,a+1),l=n.depth>a&&Hje(r,n,a+1),o=[];return hO(null,s,a,o),i&&l&&t.index(a)==r.index(a)?(Unt(i,l),o3(l3(i,qnt(s,t,r,n,a+1)),o)):(i&&o3(l3(i,Zde(s,t,a+1)),o),hO(t,r,a,o),l&&o3(l3(l,Zde(r,n,a+1)),o)),hO(n,null,a,o),new dn(o)}function Zde(s,t,r){let n=[];if(hO(null,s,r,n),s.depth>r){let a=Hje(s,t,r+1);o3(l3(a,Zde(s,t,r+1)),n)}return hO(t,null,r,n),new dn(n)}function xUt(s,t){let r=t.depth-s.openStart,a=t.node(r).copy(s.content);for(let i=r-1;i>=0;i--)a=t.node(i).copy(dn.from(a));return{start:a.resolveNoCache(s.openStart+r),end:a.resolveNoCache(a.content.size-s.openEnd-r)}}class w8{constructor(t,r,n){this.pos=t,this.path=r,this.parentOffset=n,this.depth=r.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,r=this.index(this.depth);if(r==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],a=t.child(r);return n?t.child(r).cut(n):a}get nodeBefore(){let t=this.index(this.depth),r=this.pos-this.path[this.path.length-1];return r?this.parent.child(t).cut(0,r):t==0?null:this.parent.child(t-1)}posAtIndex(t,r){r=this.resolveDepth(r);let n=this.path[r*3],a=r==0?0:this.path[r*3-1]+1;for(let i=0;i0;r--)if(this.start(r)<=t&&this.end(r)>=t)return r;return 0}blockRange(t=this,r){if(t.pos=0;n--)if(t.pos<=this.end(n)&&(!r||r(this.node(n))))return new Xde(this,t,n);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&&r<=t.content.size))throw new RangeError("Position "+r+" out of range");let n=[],a=0,i=r;for(let l=t;;){let{index:o,offset:c}=l.content.findIndex(i),d=i-c;if(n.push(l,o,a+c),!d||(l=l.child(o),l.isText))break;i=d-1,a+=c+1}return new w8(r,n,i)}static resolveCached(t,r){let n=z8e.get(t);if(n)for(let i=0;it&&this.nodesBetween(t,r,i=>(n.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()+")"),Vnt(this.marks,t)}contentMatchAt(t){let r=this.type.contentMatch.matchFragment(this.content,0,t);if(!r)throw new Error("Called contentMatchAt on a node with invalid content");return r}canReplace(t,r,n=dn.empty,a=0,i=n.childCount){let l=this.contentMatchAt(t).matchFragment(n,a,i),o=l&&l.matchFragment(this.content,r);if(!o||!o.validEnd)return!1;for(let c=a;cr.type.name)}`);this.content.forEach(r=>r.check())}toJSON(){let t={type:this.type.name};for(let r 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(r=>r.toJSON())),t}static fromJSON(t,r){if(!r)throw new RangeError("Invalid input for Node.fromJSON");let n;if(r.marks){if(!Array.isArray(r.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=r.marks.map(t.markFromJSON)}if(r.type=="text"){if(typeof r.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(r.text,n)}let a=dn.fromJSON(t,r.content),i=t.nodeType(r.type).create(r.attrs,a,n);return i.type.checkAttrs(i.attrs),i}};pj.prototype.text=void 0;class Qde extends pj{constructor(t,r,n,a){if(super(t,r,null,a),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Vnt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,r){return this.text.slice(t,r)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new Qde(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new Qde(this.type,this.attrs,t,this.marks)}cut(t=0,r=this.text.length){return t==0&&r==this.text.length?this:this.withText(this.text.slice(t,r))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function Vnt(s,t){for(let r=s.length-1;r>=0;r--)t=s[r].type.name+"("+t+")";return t}class D3{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,r){let n=new bUt(t,r);if(n.next==null)return D3.empty;let a=Hnt(n);n.next&&n.err("Unexpected trailing text");let i=CUt(SUt(a));return TUt(i,n),i}matchType(t){for(let r=0;rd.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 r(n){t.push(n);for(let a=0;a{let i=a+(n.validEnd?"*":" ")+" ";for(let l=0;l"+t.indexOf(n.next[l].next);return i}).join(` `)}}D3.empty=new D3(!0);class bUt{constructor(t,r){this.string=t,this.nodeTypes=r,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 Hnt(s){let t=[];do t.push(_Ut(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function _Ut(s){let t=[];do t.push(wUt(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function wUt(s){let t=kUt(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=jUt(s,t);else break;return t}function $8e(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function jUt(s,t){let r=$8e(s),n=r;return s.eat(",")&&(s.next!="}"?n=$8e(s):n=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:r,max:n,expr:t}}function NUt(s,t){let r=s.nodeTypes,n=r[t];if(n)return[n];let a=[];for(let i in r){let l=r[i];l.isInGroup(t)&&a.push(l)}return a.length==0&&s.err("No node type or group '"+t+"' found"),a}function kUt(s){if(s.eat("(")){let t=Hnt(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=NUt(s,s.next).map(r=>(s.inline==null?s.inline=r.isInline:s.inline!=r.isInline&&s.err("Mixing inline and block content"),{type:"name",value:r}));return s.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function SUt(s){let t=[[]];return a(i(s,0),r()),t;function r(){return t.push([])-1}function n(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=r())}else if(l.type=="star"){let c=r();return n(o,c),a(i(l.expr,c),c),[n(c)]}else if(l.type=="plus"){let c=r();return a(i(l.expr,o),c),a(i(l.expr,c),c),[n(c)]}else{if(l.type=="opt")return[n(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 h=0;h{d||a.push([o,d=[]]),d.indexOf(h)==-1&&d.push(h)})})});let i=t[n.join(",")]=new D3(n.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:Knt(this.attrs,t)}create(t=null,r,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new pj(this,this.computeAttrs(t),dn.from(r),Kl.setFrom(n))}createChecked(t=null,r,n){return r=dn.from(r),this.checkContent(r),new pj(this,this.computeAttrs(t),r,Kl.setFrom(n))}createAndFill(t=null,r,n){if(t=this.computeAttrs(t),r=dn.from(r),r.size){let l=this.contentMatch.fillBefore(r);if(!l)return null;r=l.append(r)}let a=this.contentMatch.matchFragment(r),i=a&&a.fillBefore(dn.empty,!0);return i?new pj(this,t,r.append(i),Kl.setFrom(n)):null}validContent(t){let r=this.contentMatch.matchFragment(t);if(!r||!r.validEnd)return!1;for(let n=0;n-1}allowsMarks(t){if(this.markSet==null)return!0;for(let r=0;rn[i]=new Xnt(i,r,l));let a=r.spec.topNode||"doc";if(!n[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let i in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};function EUt(s,t,r){let n=r.split("|");return a=>{let i=a===null?"null":typeof a;if(n.indexOf(i)<0)throw new RangeError(`Expected value of type ${n} for attribute ${t} on type ${s}, got ${i}`)}}class AUt{constructor(t,r,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?EUt(t,r,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class Wfe{constructor(t,r,n,a){this.name=t,this.rank=r,this.schema=n,this.spec=a,this.attrs=Znt(t,a.attrs),this.excluded=null;let i=Wnt(this.attrs);this.instance=i?new Kl(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Kl(this,Knt(this.attrs,t))}static compile(t,r){let n=Object.create(null),a=0;return t.forEach((i,l)=>n[i]=new Wfe(i,a++,r,l)),n}removeFromSet(t){for(var r=0;r-1}}class Qnt{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let r=this.spec={};for(let a in t)r[a]=t[a];r.nodes=zh.from(t.nodes),r.marks=zh.from(t.marks||{}),this.nodes=q8e.compile(this.spec.nodes,this),this.marks=Wfe.compile(this.spec.marks,this);let n=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=n[l]||(n[l]=D3.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?V8e(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==""?[]:V8e(this,l.split(" "))}this.nodeFromJSON=a=>pj.fromJSON(this,a),this.markFromJSON=a=>Kl.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,r=null,n,a){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof q8e){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(r,n,a)}text(t,r){let n=this.nodes.text;return new Qde(n,n.defaultAttrs,t,Kl.setFrom(r))}mark(t,r){return typeof t=="string"&&(t=this.marks[t]),t.create(r)}nodeType(t){let r=this.nodes[t];if(!r)throw new RangeError("Unknown node type: "+t);return r}}function V8e(s,t){let r=[];for(let n=0;n-1)&&r.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[n]+"'")}return r}function MUt(s){return s.tag!=null}function IUt(s){return s.style!=null}let mO=class Wje{constructor(t,r){this.schema=t,this.rules=r,this.tags=[],this.styles=[];let n=this.matchedStyles=[];r.forEach(a=>{if(MUt(a))this.tags.push(a);else if(IUt(a)){let i=/[^=]*/.exec(a.style)[0];n.indexOf(i)<0&&n.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,r={}){let n=new G8e(this,r,!1);return n.addAll(t,Kl.none,r.from,r.to),n.finish()}parseSlice(t,r={}){let n=new G8e(this,r,!0);return n.addAll(t,Kl.none,r.from,r.to),Un.maxOpen(n.finish())}matchTag(t,r,n){for(let a=n?this.tags.indexOf(n)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=r))){if(l.getAttrs){let c=l.getAttrs(r);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let r=[];function n(a){let i=a.priority==null?50:a.priority,l=0;for(;l{n(l=W8e(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=>{n(l=W8e(l)),l.node||l.ignore||l.mark||(l.node=a)})}return r}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Wje(t,Wje.schemaRules(t)))}};const Jnt={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},LUt={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},eat={ol:!0,ul:!0},j8=1,Kje=2,fO=4;function H8e(s,t,r){return t!=null?(t?j8:0)|(t==="full"?Kje:0):s&&s.whitespace=="pre"?j8|Kje:r&~fO}class Q9{constructor(t,r,n,a,i,l){this.type=t,this.attrs=r,this.marks=n,this.solid=a,this.options=l,this.content=[],this.activeMarks=Kl.none,this.match=i||(l&fO?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let r=this.type.contentMatch.fillBefore(dn.from(t));if(r)this.match=this.type.contentMatch.matchFragment(r);else{let n=this.type.contentMatch,a;return(a=n.findWrapping(t.type))?(this.match=n,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&j8)){let n=this.content[this.content.length-1],a;if(n&&n.isText&&(a=/[ \t\r\n\u000c]+$/.exec(n.text))){let i=n;n.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 r=dn.from(this.content);return!t&&this.match&&(r=r.append(this.match.fillBefore(dn.empty,!0))),this.type?this.type.create(this.attrs,r,this.marks):r}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Jnt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class G8e{constructor(t,r,n){this.parser=t,this.options=r,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let a=r.topNode,i,l=H8e(null,r.preserveWhitespace,0)|(n?fO:0);a?i=new Q9(a.type,a.attrs,Kl.none,!0,r.topMatch||a.type.contentMatch,l):n?i=new Q9(null,null,Kl.none,!0,null,l):i=new Q9(t.schema.topNodeType,null,Kl.none,!0,null,l),this.nodes=[i],this.find=r.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,r){t.nodeType==3?this.addTextNode(t,r):t.nodeType==1&&this.addElement(t,r)}addTextNode(t,r){let n=t.nodeValue,a=this.top,i=a.options&Kje?"full":this.localPreserveWS||(a.options&j8)>0,{schema:l}=this.parser;if(i==="full"||a.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(i)if(i==="full")n=n.replace(/\r\n?/g,` `);else if(l.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=n.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):r=r.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return r}addElementByRule(t,r,n,a){let i,l;if(r.node)if(l=this.parser.schema.nodes[r.node],l.isLeaf)this.insertNode(l.create(r.attrs),n,t.nodeName=="BR")||this.leafFallback(t,n);else{let c=this.enter(l,r.attrs||null,n,r.preserveWhitespace);c&&(i=!0,n=c)}else{let c=this.parser.schema.marks[r.mark];n=n.concat(c.create(r.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(t);else if(a)this.addElement(t,n,a);else if(r.getContent)this.findInside(t),r.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,n,!1));else{let c=t;typeof r.contentElement=="string"?c=t.querySelector(r.contentElement):typeof r.contentElement=="function"?c=r.contentElement(t):r.contentElement&&(c=r.contentElement),this.findAround(t,c,!0),this.addAll(c,n),this.findAround(t,c,!1)}i&&this.sync(o)&&this.open--}addAll(t,r,n,a){let i=n||0;for(let l=n?t.childNodes[n]:t.firstChild,o=a==null?null:t.childNodes[a];l!=o;l=l.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(l,r);this.findAtPoint(t,i)}findPlace(t,r,n){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(n)break;o+=2}}if(!a)return null;this.sync(i);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):K8e(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Q9(t,r,c,a,null,o)),this.open++,n}closeExtra(t=!1){let r=this.nodes.length-1;if(r>this.open){for(;r>this.open;r--)this.nodes[r-1].content.push(this.nodes[r].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 r=this.open;r>=0;r--){if(this.nodes[r]==t)return this.open=r,!0;this.localPreserveWS&&(this.nodes[r].options|=j8)}return!1}get currentPos(){this.closeExtra();let t=0;for(let r=this.open;r>=0;r--){let n=this.nodes[r].content;for(let a=n.length-1;a>=0;a--)t+=n[a].nodeSize;r&&t++}return t}findAtPoint(t,r){if(this.find)for(let n=0;n-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let r=t.split("/"),n=this.options.context,a=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=r[o];if(d==""){if(o==r.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let h=c>0||c==0&&a?this.nodes[c].type:n&&c>=i?n.node(c-i).type:null;if(!h||h.name!=d&&!h.isInGroup(d))return!1;c--}}return!0};return l(r.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let r=t.depth;r>=0;r--){let n=t.node(r).contentMatchAt(t.indexAfter(r)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let r in this.parser.schema.nodes){let n=this.parser.schema.nodes[r];if(n.isTextblock&&n.defaultAttrs)return n}}}function PUt(s){for(let t=s.firstChild,r=null;t;t=t.nextSibling){let n=t.nodeType==1?t.nodeName.toLowerCase():null;n&&eat.hasOwnProperty(n)&&r?(r.appendChild(t),t=r):n=="li"?r=t:n&&(r=null)}}function DUt(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function W8e(s){let t={};for(let r in s)t[r]=s[r];return t}function K8e(s,t){let r=t.schema.nodes;for(let n in r){let a=r[n];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,r);i&&((i.contentDOM||i.dom).appendChild(n),n=i.dom)}return n}serializeMark(t,r,n={}){let a=this.marks[t.type.name];return a&&xce(Wve(n),a(t,r),null,t.attrs)}static renderSpec(t,r,n=null,a){return xce(t,r,n,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new o5(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let r=Y8e(t.nodes);return r.text||(r.text=n=>n.text),r}static marksFromSchema(t){return Y8e(t.marks)}}function Y8e(s){let t={};for(let r in s){let n=s[r].spec.toDOM;n&&(t[r]=n)}return t}function Wve(s){return s.document||window.document}const Z8e=new WeakMap;function RUt(s){let t=Z8e.get(s);return t===void 0&&Z8e.set(s,t=OUt(s)),t}function OUt(s){let t=null;function r(n){if(n&&typeof n=="object")if(Array.isArray(n))if(typeof n[0]=="string")t||(t=[]),t.push(n);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&&(r=a.slice(0,l),a=a.slice(l+1));let o,c=r?s.createElementNS(r,a):s.createElement(a),d=t[1],h=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){h=2;for(let m in d)if(d[m]!=null){let x=m.indexOf(" ");x>0?c.setAttributeNS(m.slice(0,x),m.slice(x+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=h;mh)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:y,contentDOM:v}=xce(s,x,r,n);if(c.appendChild(y),v){if(o)throw new RangeError("Multiple content holes");o=v}}}return{dom:c,contentDOM:o}}const tat=65535,sat=Math.pow(2,16);function FUt(s,t){return s+t*sat}function X8e(s){return s&tat}function BUt(s){return(s-(s&tat))/sat}const rat=1,nat=2,gce=4,aat=8;class Yje{constructor(t,r,n){this.pos=t,this.delInfo=r,this.recover=n}get deleted(){return(this.delInfo&aat)>0}get deletedBefore(){return(this.delInfo&(rat|gce))>0}get deletedAfter(){return(this.delInfo&(nat|gce))>0}get deletedAcross(){return(this.delInfo&gce)>0}}class Op{constructor(t,r=!1){if(this.ranges=t,this.inverted=r,!t.length&&Op.empty)return Op.empty}recover(t){let r=0,n=X8e(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],h=this.ranges[o+l],m=c+d;if(t<=m){let x=d?t==c?-1:t==m?1:r:r,y=c+a+(x<0?0:h);if(n)return y;let v=t==(r<0?c:m)?null:FUt(o/3,t-c),w=t==c?nat:t==m?rat:gce;return(r<0?t!=c:t!=m)&&(w|=aat),new Yje(y,w,v)}a+=h-d}return n?t+a:new Yje(t+a,0,null)}touches(t,r){let n=0,a=X8e(r),i=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;ot)break;let d=this.ranges[o+i],h=c+d;if(t<=h&&o==a*3)return!0;n+=this.ranges[o+l]-d}return!1}forEach(t){let r=this.inverted?2:1,n=this.inverted?1:2;for(let a=0,i=0;a=0;r--){let a=t.getMirror(r);this.appendMap(t._maps[r].invert(),a!=null&&a>r?n-a-1:void 0)}}invert(){let t=new N8;return t.appendMappingInverted(this),t}map(t,r=1){if(this.mirror)return this._map(t,r,!0);for(let n=this.from;ni&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),r.openStart,r.openEnd);return xu.fromReplace(t,this.from,this.to,i)}invert(){return new W0(this.from,this.to,this.mark)}map(t){let r=t.mapResult(this.from,1),n=t.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new Rw(r.pos,n.pos,this.mark)}merge(t){return t instanceof Rw&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Rw(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,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Rw(r.from,r.to,t.markFromJSON(r.mark))}}Cm.jsonID("addMark",Rw);class W0 extends Cm{constructor(t,r,n){super(),this.from=t,this.to=r,this.mark=n}apply(t){let r=t.slice(this.from,this.to),n=new Un(u3e(r.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),r.openStart,r.openEnd);return xu.fromReplace(t,this.from,this.to,n)}invert(){return new Rw(this.from,this.to,this.mark)}map(t){let r=t.mapResult(this.from,1),n=t.mapResult(this.to,-1);return r.deleted&&n.deleted||r.pos>=n.pos?null:new W0(r.pos,n.pos,this.mark)}merge(t){return t instanceof W0&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new W0(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,r){if(typeof r.from!="number"||typeof r.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new W0(r.from,r.to,t.markFromJSON(r.mark))}}Cm.jsonID("removeMark",W0);class Ow extends Cm{constructor(t,r){super(),this.pos=t,this.mark=r}apply(t){let r=t.nodeAt(this.pos);if(!r)return xu.fail("No node at mark step's position");let n=r.type.create(r.attrs,null,this.mark.addToSet(r.marks));return xu.fromReplace(t,this.pos,this.pos+1,new Un(dn.from(n),0,r.isLeaf?0:1))}invert(t){let r=t.nodeAt(this.pos);if(r){let n=this.mark.addToSet(r.marks);if(n.length==r.marks.length){for(let a=0;an.pos?null:new Nh(r.pos,n.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,r){if(typeof r.from!="number"||typeof r.to!="number"||typeof r.gapFrom!="number"||typeof r.gapTo!="number"||typeof r.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Nh(r.from,r.to,r.gapFrom,r.gapTo,Un.fromJSON(t,r.slice),r.insert,!!r.structure)}}Cm.jsonID("replaceAround",Nh);function Zje(s,t,r){let n=s.resolve(t),a=r-t,i=n.depth;for(;a>0&&i>0&&n.indexAfter(i)==n.node(i).childCount;)i--,a--;if(a>0){let l=n.node(i).maybeChild(n.indexAfter(i));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function zUt(s,t,r,n){let a=[],i=[],l,o;s.doc.nodesBetween(t,r,(c,d,h)=>{if(!c.isInline)return;let m=c.marks;if(!n.isInSet(m)&&h.type.allowsMarkType(n.type)){let x=Math.max(d,t),y=Math.min(d+c.nodeSize,r),v=n.addToSet(m);for(let w=0;ws.step(c)),i.forEach(c=>s.step(c))}function $Ut(s,t,r,n){let a=[],i=0;s.doc.nodesBetween(t,r,(l,o)=>{if(!l.isInline)return;i++;let c=null;if(n instanceof Wfe){let d=l.marks,h;for(;h=n.isInSet(d);)(c||(c=[])).push(h),d=h.removeFromSet(d)}else n?n.isInSet(l.marks)&&(c=[n]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,r);for(let h=0;hs.step(new W0(l.from,l.to,l.style)))}function h3e(s,t,r,n=r.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 UUt(s,t,r){return(t==0||s.canReplace(t,s.childCount))&&(r==s.childCount||s.canReplace(0,r))}function KI(s){let r=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let n=s.depth,a=0,i=0;;--n){let l=s.$from.node(n),o=s.$from.index(n)+a,c=s.$to.indexAfter(n)-i;if(nr;v--)w||n.index(v)>0?(w=!0,h=dn.from(n.node(v).copy(h)),m++):c--;let x=dn.empty,y=0;for(let v=i,w=!1;v>r;v--)w||a.after(v+1)=0;l--){if(n.size){let o=r[l].type.contentMatch.matchFragment(n);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=dn.from(r[l].type.create(r[l].attrs,n))}let a=t.start,i=t.end;s.step(new Nh(a,i,a,i,new Un(n,0,0),r.length,!0))}function WUt(s,t,r,n,a){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=s.steps.length;s.doc.nodesBetween(t,r,(l,o)=>{let c=typeof a=="function"?a(l):a;if(l.isTextblock&&!l.hasMarkup(n,c)&&KUt(s.doc,s.mapping.slice(i).map(o),n)){let d=null;if(n.schema.linebreakReplacement){let y=n.whitespace=="pre",v=!!n.contentMatch.matchType(n.schema.linebreakReplacement);y&&!v?d=!1:!y&&v&&(d=!0)}d===!1&&oat(s,l,o,i),h3e(s,s.mapping.slice(i).map(o,1),n,void 0,d===null);let h=s.mapping.slice(i),m=h.map(o,1),x=h.map(o+l.nodeSize,1);return s.step(new Nh(m,x,m+1,x-1,new Un(dn.from(n.create(c,null,l.marks)),0,0),1,!0)),d===!0&&iat(s,l,o,i),!1}})}function iat(s,t,r,n){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(n).map(r+1+i+l.index);s.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function oat(s,t,r,n){t.forEach((a,i)=>{if(a.type==a.type.schema.linebreakReplacement){let l=s.mapping.slice(n).map(r+1+i);s.replaceWith(l,l+1,t.type.schema.text(` `))}})}function KUt(s,t,r){let n=s.resolve(t),a=n.index();return n.parent.canReplaceWith(a,a+1,r)}function YUt(s,t,r,n,a){let i=s.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");r||(r=i.type);let l=r.create(n,null,a||i.marks);if(i.isLeaf)return s.replaceWith(t,t+i.nodeSize,l);if(!r.validContent(i.content))throw new RangeError("Invalid content for node type "+r.name);s.step(new Nh(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Un(dn.from(l),0,0),1,!0))}function BA(s,t,r=1,n){let a=s.resolve(t),i=a.depth-r,l=n&&n[n.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,h=r-2;d>i;d--,h--){let m=a.node(d),x=a.index(d);if(m.type.spec.isolating)return!1;let y=m.content.cutByIndex(x,m.childCount),v=n&&n[h+1];v&&(y=y.replaceChild(0,v.type.create(v.attrs)));let w=n&&n[h]||m;if(!m.canReplace(x+1,m.childCount)||!w.type.validContent(y))return!1}let o=a.indexAfter(i),c=n&&n[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function ZUt(s,t,r=1,n){let a=s.doc.resolve(t),i=dn.empty,l=dn.empty;for(let o=a.depth,c=a.depth-r,d=r-1;o>c;o--,d--){i=dn.from(a.node(o).copy(i));let h=n&&n[d];l=dn.from(h?h.type.create(h.attrs,l):a.node(o).copy(l))}s.step(new mu(t,t,new Un(i.append(l),r,r),!0))}function r2(s,t){let r=s.resolve(t),n=r.index();return lat(r.nodeBefore,r.nodeAfter)&&r.parent.canReplace(n,n+1)}function XUt(s,t){t.content.size||s.type.compatibleContent(t.type);let r=s.contentMatchAt(s.childCount),{linebreakReplacement:n}=s.type.schema;for(let a=0;a0?(i=n.node(a+1),o++,l=n.node(a).maybeChild(o)):(i=n.node(a).maybeChild(o-1),l=n.node(a+1)),i&&!i.isTextblock&&lat(i,l)&&n.node(a).canReplace(o,o+1))return t;if(a==0)break;t=r<0?n.before(a):n.after(a)}}function QUt(s,t,r){let n=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-r),l=i.node().type;if(a&&l.inlineContent){let h=l.whitespace=="pre",m=!!l.contentMatch.matchType(a);h&&!m?n=!1:!h&&m&&(n=!0)}let o=s.steps.length;if(n===!1){let h=s.doc.resolve(t+r);oat(s,h.node(),h.before(),o)}l.inlineContent&&h3e(s,t+r-1,l,i.node().contentMatchAt(i.index()),n==null);let c=s.mapping.slice(o),d=c.map(t-r);if(s.step(new mu(d,c.map(t+r,-1),Un.empty,!0)),n===!0){let h=s.doc.resolve(d);iat(s,h.node(),h.before(),s.steps.length)}return s}function JUt(s,t,r){let n=s.resolve(t);if(n.parent.canReplaceWith(n.index(),n.index(),r))return t;if(n.parentOffset==0)for(let a=n.depth-1;a>=0;a--){let i=n.index(a);if(n.node(a).canReplaceWith(i,i,r))return n.before(a+1);if(i>0)return null}if(n.parentOffset==n.parent.content.size)for(let a=n.depth-1;a>=0;a--){let i=n.indexAfter(a);if(n.node(a).canReplaceWith(i,i,r))return n.after(a+1);if(i=0;l--){let o=l==n.depth?0:n.pos<=(n.start(l+1)+n.end(l+1))/2?-1:1,c=n.index(l)+(o>0?1:0),d=n.node(l),h=!1;if(i==1)h=d.canReplace(c,c,a);else{let m=d.contentMatchAt(c).findWrapping(a.firstChild.type);h=m&&d.canReplaceWith(c,c,m[0])}if(h)return o==0?n.pos:o<0?n.before(l+1):n.after(l+1)}return null}function Yfe(s,t,r=t,n=Un.empty){if(t==r&&!n.size)return null;let a=s.resolve(t),i=s.resolve(r);return dat(a,i,n)?new mu(t,r,n):new eqt(a,i,n).fit()}function dat(s,t,r){return!r.openStart&&!r.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),r.content)}class eqt{constructor(t,r,n){this.$from=t,this.$to=r,this.unplaced=n,this.frontier=[],this.placed=dn.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=dn.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(),r=this.placed.size-this.depth-this.$from.depth,n=this.$from,a=this.close(t<0?this.$to:n.doc.resolve(t));if(!a)return null;let i=this.placed,l=n.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new Un(i,l,o);return t>-1?new Nh(n.pos,t,this.$to.pos,this.$to.end(),c,r):c.size||n.pos!=this.$to.pos?new mu(n.pos,a.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let r=this.unplaced.content,n=0,a=this.unplaced.openEnd;n1&&(a=0),i.type.spec.isolating&&a<=n){t=n;break}r=i.content}for(let r=1;r<=2;r++)for(let n=r==1?t:this.unplaced.openStart;n>=0;n--){let a,i=null;n?(i=Yve(this.unplaced.content,n-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],h,m=null;if(r==1&&(l?d.matchType(l.type)||(m=d.fillBefore(dn.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:n,frontierDepth:o,parent:i,inject:m};if(r==2&&l&&(h=d.findWrapping(l.type)))return{sliceDepth:n,frontierDepth:o,parent:i,wrap:h};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=Yve(t,r);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Un(t,r+1,Math.max(n,a.size+r>=t.size-n?r+1:0)),!0)}dropNode(){let{content:t,openStart:r,openEnd:n}=this.unplaced,a=Yve(t,r);if(a.childCount<=1&&r>0){let i=t.size-r<=r+a.size;this.unplaced=new Un(PD(t,r-1,1),r-1,i?r-1:n)}else this.unplaced=new Un(PD(t,r,1),r,n)}placeNodes({sliceDepth:t,frontierDepth:r,parent:n,inject:a,wrap:i}){for(;this.depth>r;)this.closeFrontierNode();if(i)for(let w=0;w1||c==0||w.content.size)&&(m=b,h.push(uat(w.mark(x.allowedMarks(w.marks)),d==1?c:0,d==o.childCount?y:-1)))}let v=d==o.childCount;v||(y=-1),this.placed=DD(this.placed,r,dn.from(h)),this.frontier[r].match=m,v&&y<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let w=0,b=o;w1&&a==this.$to.end(--n);)++a;return a}findCloseLevel(t){e:for(let r=Math.min(this.depth,t.depth);r>=0;r--){let{match:n,type:a}=this.frontier[r],i=r=0;o--){let{match:c,type:d}=this.frontier[o],h=Zve(t,o,d,c,!0);if(!h||h.childCount)continue e}return{depth:r,fit:l,move:i?t.doc.resolve(t.after(r+1)):t}}}}close(t){let r=this.findCloseLevel(t);if(!r)return null;for(;this.depth>r.depth;)this.closeFrontierNode();r.fit.childCount&&(this.placed=DD(this.placed,r.depth,r.fit)),t=r.move;for(let n=r.depth+1;n<=t.depth;n++){let a=t.node(n),i=a.type.contentMatch.fillBefore(a.content,!0,t.index(n));this.openFrontierNode(a.type,a.attrs,i)}return t}openFrontierNode(t,r=null,n){let a=this.frontier[this.depth];a.match=a.match.matchType(t),this.placed=DD(this.placed,this.depth,dn.from(t.create(r,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let r=this.frontier.pop().match.fillBefore(dn.empty,!0);r.childCount&&(this.placed=DD(this.placed,this.frontier.length,r))}}function PD(s,t,r){return t==0?s.cutByIndex(r,s.childCount):s.replaceChild(0,s.firstChild.copy(PD(s.firstChild.content,t-1,r)))}function DD(s,t,r){return t==0?s.append(r):s.replaceChild(s.childCount-1,s.lastChild.copy(DD(s.lastChild.content,t-1,r)))}function Yve(s,t){for(let r=0;r1&&(n=n.replaceChild(0,uat(n.firstChild,t-1,n.childCount==1?r-1:0))),t>0&&(n=s.type.contentMatch.fillBefore(n).append(n),r<=0&&(n=n.append(s.type.contentMatch.matchFragment(n).fillBefore(dn.empty,!0)))),s.copy(n)}function Zve(s,t,r,n,a){let i=s.node(t),l=a?s.indexAfter(t):s.index(t);if(l==i.childCount&&!r.compatibleContent(i.type))return null;let o=n.fillBefore(i.content,!0,l);return o&&!tqt(r,i.content,l)?o:null}function tqt(s,t,r){for(let n=r;n0;x--,y--){let v=a.node(x).type.spec;if(v.defining||v.definingAsContext||v.isolating)break;l.indexOf(x)>-1?o=x:a.before(x)==y&&l.splice(1,0,-x)}let c=l.indexOf(o),d=[],h=n.openStart;for(let x=n.content,y=0;;y++){let v=x.firstChild;if(d.push(v),y==n.openStart)break;x=v.content}for(let x=h-1;x>=0;x--){let y=d[x],v=sqt(y.type);if(v&&!y.sameMarkup(a.node(Math.abs(o)-1)))h=x;else if(v||!y.type.isTextblock)break}for(let x=n.openStart;x>=0;x--){let y=(x+h+1)%(n.openStart+1),v=d[y];if(v)for(let w=0;w=0&&(s.replace(t,r,n),!(s.steps.length>m));x--){let y=l[x];y<0||(t=a.before(y),r=i.after(y))}}function hat(s,t,r,n,a){if(tn){let i=a.contentMatchAt(0),l=i.fillBefore(s).append(s);s=l.append(i.matchFragment(l).fillBefore(dn.empty,!0))}return s}function nqt(s,t,r,n){if(!n.isInline&&t==r&&s.doc.resolve(t).parent.content.size){let a=JUt(s.doc,t,n.type);a!=null&&(t=r=a)}s.replaceRange(t,r,new Un(dn.from(n),0,0))}function aqt(s,t,r){let n=s.doc.resolve(t),a=s.doc.resolve(r);if(n.parent.isTextblock&&a.parent.isTextblock&&n.start()!=a.start()&&n.parentOffset==0&&a.parentOffset==0){let l=n.sharedDepth(r),o=!1;for(let c=n.depth;c>l;c--)n.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=n.depth;c>0&&t==n.start(c);c--)t=n.before(c);for(let c=a.depth;c>0&&r==a.start(c);c--)r=a.before(c);n=s.doc.resolve(t),a=s.doc.resolve(r)}}let i=mat(n,a);for(let l=0;l0&&(c||n.node(o-1).canReplace(n.index(o-1),a.indexAfter(o-1))))return s.delete(n.before(o),a.after(o))}for(let l=1;l<=n.depth&&l<=a.depth;l++)if(t-n.start(l)==n.depth-l&&r>n.end(l)&&a.end(l)-r!=a.depth-l&&n.start(l-1)==a.start(l-1)&&n.node(l-1).canReplace(n.index(l-1),a.index(l-1)))return s.delete(n.before(l),r);s.delete(t,r)}function mat(s,t){let r=[],n=Math.min(s.depth,t.depth);for(let a=n;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)&&r.push(a)}return r}class zA extends Cm{constructor(t,r,n){super(),this.pos=t,this.attr=r,this.value=n}apply(t){let r=t.nodeAt(this.pos);if(!r)return xu.fail("No node at attribute step's position");let n=Object.create(null);for(let i in r.attrs)n[i]=r.attrs[i];n[this.attr]=this.value;let a=r.type.create(n,null,r.marks);return xu.fromReplace(t,this.pos,this.pos+1,new Un(dn.from(a),0,r.isLeaf?0:1))}getMap(){return Op.empty}invert(t){return new zA(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let r=t.mapResult(this.pos,1);return r.deletedAfter?null:new zA(r.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,r){if(typeof r.pos!="number"||typeof r.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new zA(r.pos,r.attr,r.value)}}Cm.jsonID("attr",zA);class k8 extends Cm{constructor(t,r){super(),this.attr=t,this.value=r}apply(t){let r=Object.create(null);for(let a in t.attrs)r[a]=t.attrs[a];r[this.attr]=this.value;let n=t.type.create(r,t.content,t.marks);return xu.ok(n)}getMap(){return Op.empty}invert(t){return new k8(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,r){if(typeof r.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new k8(r.attr,r.value)}}Cm.jsonID("docAttr",k8);let DM=class extends Error{};DM=function s(t){let r=Error.call(this,t);return r.__proto__=s.prototype,r};DM.prototype=Object.create(Error.prototype);DM.prototype.constructor=DM;DM.prototype.name="TransformError";class f3e{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new N8}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let r=this.maybeStep(t);if(r.failed)throw new DM(r.failed);return this}maybeStep(t){let r=t.apply(this.doc);return r.failed||this.addStep(t,r.doc),r}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,r=-1e9;for(let n=0;n{t=Math.min(t,o),r=Math.max(r,c)})}return t==1e9?null:{from:t,to:r}}addStep(t,r){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=r}replace(t,r=t,n=Un.empty){let a=Yfe(this.doc,t,r,n);return a&&this.step(a),this}replaceWith(t,r,n){return this.replace(t,r,new Un(dn.from(n),0,0))}delete(t,r){return this.replace(t,r,Un.empty)}insert(t,r){return this.replaceWith(t,t,r)}replaceRange(t,r,n){return rqt(this,t,r,n),this}replaceRangeWith(t,r,n){return nqt(this,t,r,n),this}deleteRange(t,r){return aqt(this,t,r),this}lift(t,r){return qUt(this,t,r),this}join(t,r=1){return QUt(this,t,r),this}wrap(t,r){return GUt(this,t,r),this}setBlockType(t,r=t,n,a=null){return WUt(this,t,r,n,a),this}setNodeMarkup(t,r,n=null,a){return YUt(this,t,r,n,a),this}setNodeAttribute(t,r,n){return this.step(new zA(t,r,n)),this}setDocAttribute(t,r){return this.step(new k8(t,r)),this}addNodeMark(t,r){return this.step(new Ow(t,r)),this}removeNodeMark(t,r){let n=this.doc.nodeAt(t);if(!n)throw new RangeError("No node at position "+t);if(r instanceof Kl)r.isInSet(n.marks)&&this.step(new R3(t,r));else{let a=n.marks,i,l=[];for(;i=r.isInSet(a);)l.push(new R3(t,i)),a=i.removeFromSet(a);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(t,r=1,n){return ZUt(this,t,r,n),this}addMark(t,r,n){return zUt(this,t,r,n),this}removeMark(t,r,n){return $Ut(this,t,r,n),this}clearIncompatible(t,r,n){return h3e(this,t,r,n),this}}const Xve=Object.create(null);class pi{constructor(t,r,n){this.$anchor=t,this.$head=r,this.ranges=n||[new fat(t.min(r),t.max(r))]}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 r=0;r=0;i--){let l=r<0?jE(t.node(0),t.node(i),t.before(i+1),t.index(i),r,n):jE(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,r,n);if(l)return l}return null}static near(t,r=1){return this.findFrom(t,r)||this.findFrom(t,-r)||new dg(t.node(0))}static atStart(t){return jE(t,t,0,0,1)||new dg(t)}static atEnd(t){return jE(t,t,t.content.size,t.childCount,-1)||new dg(t)}static fromJSON(t,r){if(!r||!r.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=Xve[r.type];if(!n)throw new RangeError(`No selection type ${r.type} defined`);return n.fromJSON(t,r)}static jsonID(t,r){if(t in Xve)throw new RangeError("Duplicate use of selection JSON ID "+t);return Xve[t]=r,r.prototype.jsonID=t,r}getBookmark(){return oi.between(this.$anchor,this.$head).getBookmark()}}pi.prototype.visible=!0;class fat{constructor(t,r){this.$from=t,this.$to=r}}let J8e=!1;function eFe(s){!J8e&&!s.parent.inlineContent&&(J8e=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class oi extends pi{constructor(t,r=t){eFe(t),eFe(r),super(t,r)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,r){let n=t.resolve(r.map(this.head));if(!n.parent.inlineContent)return pi.near(n);let a=t.resolve(r.map(this.anchor));return new oi(a.parent.inlineContent?a:n,n)}replace(t,r=Un.empty){if(super.replace(t,r),r==Un.empty){let n=this.$from.marksAcross(this.$to);n&&t.ensureMarks(n)}}eq(t){return t instanceof oi&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Zfe(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,r){if(typeof r.anchor!="number"||typeof r.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new oi(t.resolve(r.anchor),t.resolve(r.head))}static create(t,r,n=r){let a=t.resolve(r);return new this(a,n==r?a:t.resolve(n))}static between(t,r,n){let a=t.pos-r.pos;if((!n||a)&&(n=a>=0?1:-1),!r.parent.inlineContent){let i=pi.findFrom(r,n,!0)||pi.findFrom(r,-n,!0);if(i)r=i.$head;else return pi.near(r,n)}return t.parent.inlineContent||(a==0?t=r:(t=(pi.findFrom(t,-n,!0)||pi.findFrom(t,n,!0)).$anchor,t.pos0?0:1);a>0?l=0;l+=a){let o=t.child(l);if(o.isAtom){if(!i&&Xa.isSelectable(o))return Xa.create(s,r-(a<0?o.nodeSize:0))}else{let c=jE(s,o,r+a,a<0?o.childCount:0,a,i);if(c)return c}r+=o.nodeSize*a}return null}function tFe(s,t,r){let n=s.steps.length-1;if(n{l==null&&(l=h)}),s.setSelection(pi.near(s.doc.resolve(l),r))}const sFe=1,J9=2,rFe=4;class oqt extends f3e{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|=J9,this}ensureMarks(t){return Kl.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&J9)>0}addStep(t,r){super.addStep(t,r),this.updated=this.updated&~J9,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,r=!0){let n=this.selection;return r&&(t=t.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||Kl.none))),n.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,r,n){let a=this.doc.type.schema;if(r==null)return t?this.replaceSelectionWith(a.text(t),!0):this.deleteSelection();{if(n==null&&(n=r),!t)return this.deleteRange(r,n);let i=this.storedMarks;if(!i){let l=this.doc.resolve(r);i=n==r?l.marks():l.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(r,n,a.text(t,i)),!this.selection.empty&&this.selection.to==r+t.length&&this.setSelection(pi.near(this.selection.$to)),this}}setMeta(t,r){return this.meta[typeof t=="string"?t:t.key]=r,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|=rFe,this}get scrolledIntoView(){return(this.updated&rFe)>0}}function nFe(s,t){return!t||!s?s:s.bind(t)}class RD{constructor(t,r,n){this.name=t,this.init=nFe(r.init,n),this.apply=nFe(r.apply,n)}}const lqt=[new RD("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new RD("selection",{init(s,t){return s.selection||pi.atStart(t.doc)},apply(s){return s.selection}}),new RD("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,r,n){return n.selection.$cursor?s.storedMarks:null}}),new RD("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class Qve{constructor(t,r){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=lqt.slice(),r&&r.forEach(n=>{if(this.pluginsByKey[n.key])throw new RangeError("Adding different instances of a keyed plugin ("+n.key+")");this.plugins.push(n),this.pluginsByKey[n.key]=n,n.spec.state&&this.fields.push(new RD(n.key,n.spec.state,n))})}}class HE{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,r=-1){for(let n=0;nn.toJSON())),t&&typeof t=="object")for(let n in t){if(n=="doc"||n=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=t[n],i=a.spec.state;i&&i.toJSON&&(r[n]=i.toJSON.call(a,this[a.key]))}return r}static fromJSON(t,r,n){if(!r)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let a=new Qve(t.schema,t.plugins),i=new HE(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=pj.fromJSON(t.schema,r.doc);else if(l.name=="selection")i.selection=pi.fromJSON(i.doc,r.selection);else if(l.name=="storedMarks")r.storedMarks&&(i.storedMarks=r.storedMarks.map(t.schema.markFromJSON));else{if(n)for(let o in n){let c=n[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(r,o)){i[l.name]=d.fromJSON.call(c,t,r[o],i);return}}i[l.name]=l.init(t,i)}}),i}}function pat(s,t,r){for(let n in s){let a=s[n];a instanceof Function?a=a.bind(t):n=="handleDOMEvents"&&(a=pat(a,t,{})),r[n]=a}return r}class Ju{constructor(t){this.spec=t,this.props={},t.props&&pat(t.props,this,this.props),this.key=t.key?t.key.key:xat("plugin")}getState(t){return t[this.key]}}const Jve=Object.create(null);function xat(s){return s in Jve?s+"$"+ ++Jve[s]:(Jve[s]=0,s+"$")}class Tm{constructor(t="key"){this.key=xat(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const Vh=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},RM=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let Xje=null;const $1=function(s,t,r){let n=Xje||(Xje=document.createRange());return n.setEnd(s,r??s.nodeValue.length),n.setStart(s,t||0),n},cqt=function(){Xje=null},O3=function(s,t,r,n){return r&&(aFe(s,t,r,n,-1)||aFe(s,t,r,n,1))},dqt=/^(img|br|input|textarea|hr)$/i;function aFe(s,t,r,n,a){for(var i;;){if(s==r&&t==n)return!0;if(t==(a<0?0:Xx(s))){let l=s.parentNode;if(!l||l.nodeType!=1||mB(s)||dqt.test(s.nodeName)||s.contentEditable=="false")return!1;t=Vh(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?Xx(s):0}else return!1}}function Xx(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function uqt(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=Xx(s)}else if(s.parentNode&&!mB(s))t=Vh(s),s=s.parentNode;else return null}}function hqt(s,t){for(;;){if(s.nodeType==3&&t2),Hx=OM||(Nv?/Mac/.test(Nv.platform):!1),vat=Nv?/Win/.test(Nv.platform):!1,ib=/Android \d/.test(n2),fB=!!iFe&&"webkitFontSmoothing"in iFe.documentElement.style,xqt=fB?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function gqt(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 T1(s,t){return typeof s=="number"?s:s[t]}function yqt(s){let t=s.getBoundingClientRect(),r=t.width/s.offsetWidth||1,n=t.height/s.offsetHeight||1;return{left:t.left,right:t.left+s.clientWidth*r,top:t.top,bottom:t.top+s.clientHeight*n}}function oFe(s,t,r){let n=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=r||s.dom;l;){if(l.nodeType!=1){l=RM(l);continue}let o=l,c=o==i.body,d=c?gqt(i):yqt(o),h=0,m=0;if(t.topd.bottom-T1(n,"bottom")&&(m=t.bottom-t.top>d.bottom-d.top?t.top+T1(a,"top")-d.top:t.bottom-d.bottom+T1(a,"bottom")),t.leftd.right-T1(n,"right")&&(h=t.right-d.right+T1(a,"right")),h||m)if(c)i.defaultView.scrollBy(h,m);else{let y=o.scrollLeft,v=o.scrollTop;m&&(o.scrollTop+=m),h&&(o.scrollLeft+=h);let w=o.scrollLeft-y,b=o.scrollTop-v;t={left:t.left-w,top:t.top-b,right:t.right-w,bottom:t.bottom-b}}let x=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(x))break;l=x=="absolute"?l.offsetParent:RM(l)}}function vqt(s){let t=s.dom.getBoundingClientRect(),r=Math.max(0,t.top),n,a;for(let i=(t.left+t.right)/2,l=r+1;l=r-20){n=o,a=c.top;break}}return{refDOM:n,refTop:a,stack:bat(s.dom)}}function bat(s){let t=[],r=s.ownerDocument;for(let n=s;n&&(t.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),s!=r);n=RM(n));return t}function bqt({refDOM:s,refTop:t,stack:r}){let n=s?s.getBoundingClientRect().top:0;_at(r,n==0?0:n-t)}function _at(s,t){for(let r=0;r=o){l=Math.max(v.bottom,l),o=Math.min(v.top,o);let w=v.left>t.left?v.left-t.left:v.right=(v.left+v.right)/2?1:0));continue}}else v.top>t.top&&!c&&v.left<=t.left&&v.right>=t.left&&(c=h,d={left:Math.max(v.left,Math.min(v.right,t.left)),top:v.top});!r&&(t.left>=v.right&&t.top>=v.top||t.left>=v.left&&t.top>=v.bottom)&&(i=m+1)}}return!r&&c&&(r=c,a=d,n=0),r&&r.nodeType==3?wqt(r,a):!r||n&&r.nodeType==1?{node:s,offset:i}:wat(r,a)}function wqt(s,t){let r=s.nodeValue.length,n=document.createRange(),a;for(let i=0;i=(l.left+l.right)/2?1:0)};break}}return n.detach(),a||{node:s,offset:0}}function x3e(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function jqt(s,t){let r=s.parentNode;return r&&/^li$/i.test(r.nodeName)&&t.left(l.left+l.right)/2?1:-1}return s.docView.posFromDOM(n,a,i)}function kqt(s,t,r,n){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>n.left||c.top>n.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,r,-1)}function jat(s,t,r){let n=s.childNodes.length;if(n&&r.topt.top&&a++}let d;fB&&a&&n.nodeType==1&&(d=n.childNodes[a-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,n==s.dom&&a==n.childNodes.length-1&&n.lastChild.nodeType==1&&t.top>n.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||n.nodeType!=1||n.childNodes[a-1].nodeName!="BR")&&(o=kqt(s,n,a,t))}o==null&&(o=Nqt(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function lFe(s){return s.top=0&&a==n.nodeValue.length?(c--,h=1):r<0?c--:d++,rD(X_($1(n,c,d),h),h<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(r<0||a==Xx(n))){let c=n.childNodes[a-1];if(c.nodeType==1)return e1e(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(r<0||a==Xx(n))){let c=n.childNodes[a-1],d=c.nodeType==3?$1(c,Xx(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return rD(X_(d,1),!1)}if(i==null&&a=0)}function rD(s,t){if(s.width==0)return s;let r=t?s.left:s.right;return{top:s.top,bottom:s.bottom,left:r,right:r}}function e1e(s,t){if(s.height==0)return s;let r=t?s.top:s.bottom;return{top:r,bottom:r,left:s.left,right:s.right}}function kat(s,t,r){let n=s.state,a=s.root.activeElement;n!=t&&s.updateState(t),a!=s.dom&&s.focus();try{return r()}finally{n!=t&&s.updateState(n),a!=s.dom&&a&&a.focus()}}function Tqt(s,t,r){let n=t.selection,a=r=="up"?n.$from:n.$to;return kat(s,t,()=>{let{node:i}=s.docView.domFromPos(a.pos,r=="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=Nat(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=$1(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;dh.top+1&&(r=="up"?l.top-h.top>(h.bottom-l.top)*2:h.bottom-l.bottom>(l.bottom-h.top)*2))return!1}}return!0})}const Eqt=/[\u0590-\u08ac]/;function Aqt(s,t,r){let{$head:n}=t.selection;if(!n.parent.isTextblock)return!1;let a=n.parentOffset,i=!a,l=a==n.parent.content.size,o=s.domSelection();return o?!Eqt.test(n.parent.textContent)||!o.modify?r=="left"||r=="backward"?i:l:kat(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:h,anchorOffset:m}=s.domSelectionRange(),x=o.caretBidiLevel;o.modify("move",r,"character");let y=n.depth?s.docView.domAfterPos(n.before()):s.dom,{focusNode:v,focusOffset:w}=s.domSelectionRange(),b=v&&!y.contains(v.nodeType==1?v:v.parentNode)||c==v&&d==w;try{o.collapse(h,m),c&&(c!=h||d!=m)&&o.extend&&o.extend(c,d)}catch{}return x!=null&&(o.caretBidiLevel=x),b}):n.pos==n.start()||n.pos==n.end()}let cFe=null,dFe=null,uFe=!1;function Mqt(s,t,r){return cFe==t&&dFe==r?uFe:(cFe=t,dFe=r,uFe=r=="up"||r=="down"?Tqt(s,t,r):Aqt(s,t,r))}const hg=0,hFe=1,a4=2,kv=3;class pB{constructor(t,r,n,a){this.parent=t,this.children=r,this.dom=n,this.contentDOM=a,this.dirty=hg,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,r,n){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let r=0;rVh(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(r==0)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!1;break}if(i.previousSibling)break}if(a==null&&r==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!0;break}if(i.nextSibling)break}}return a??n>0?this.posAtEnd:this.posAtStart}nearestDesc(t,r=!1){for(let n=!0,a=t;a;a=a.parentNode){let i=this.getDesc(a),l;if(i&&(!r||i.node))if(n&&(l=i.nodeDOM)&&!(l.nodeType==1?l.contains(t.nodeType==1?t:t.parentNode):l==t))n=!1;else return i}}getDesc(t){let r=t.pmViewDesc;for(let n=r;n;n=n.parent)if(n==this)return r}posFromDOM(t,r,n){for(let a=t;a;a=a.parentNode){let i=this.getDesc(a);if(i)return i.localPosFromDOM(t,r,n)}return-1}descAt(t){for(let r=0,n=0;rt||l instanceof Cat){a=t-i;break}i=o}if(a)return this.children[n].domFromPos(a-this.children[n].border,r);for(let i;n&&!(i=this.children[n-1]).size&&i instanceof Sat&&i.side>=0;n--);if(r<=0){let i,l=!0;for(;i=n?this.children[n-1]:null,!(!i||i.dom.parentNode==this.contentDOM);n--,l=!1);return i&&r&&l&&!i.border&&!i.domAtom?i.domFromPos(i.size,r):{node:this.contentDOM,offset:i?Vh(i.dom)+1:0}}else{let i,l=!0;for(;i=n=h&&r<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,r,h);t=l;for(let m=o;m>0;m--){let x=this.children[m-1];if(x.size&&x.dom.parentNode==this.contentDOM&&!x.emptyChildAt(1)){a=Vh(x.dom)+1;break}t-=x.size}a==-1&&(a=0)}if(a>-1&&(d>r||o==this.children.length-1)){r=d;for(let h=o+1;hv&&lr){let v=o;o=c,c=v}let y=document.createRange();y.setEnd(c.node,c.offset),y.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(y)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,r){for(let n=0,a=0;a=n:tn){let o=n+i.border,c=l-i.border;if(t>=o&&r<=c){this.dirty=t==n||r==l?a4:hFe,t==o&&r==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=kv:i.markDirty(t-o,r-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?a4:kv}n=l}this.dirty=a4}markParentsDirty(){let t=1;for(let r=this.parent;r;r=r.parent,t++){let n=t==1?a4:hFe;r.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!r.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=r,this.widget=r,i=this}matchesWidget(t){return this.dirty==hg&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let r=this.widget.spec.stopEvent;return r?r(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 Iqt extends pB{constructor(t,r,n,a){super(t,[],r,null),this.textDOM=n,this.text=a}get size(){return this.text.length}localPosFromDOM(t,r){return t!=this.textDOM?this.posAtStart+(r?this.size:0):this.posAtStart+r}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class F3 extends pB{constructor(t,r,n,a,i){super(t,[],n,a),this.mark=r,this.spec=i}static create(t,r,n,a){let i=a.nodeViews[r.type.name],l=i&&i(r,a,n);return(!l||!l.dom)&&(l=o5.renderSpec(document,r.type.spec.toDOM(r,n),null,r.attrs)),new F3(t,r,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&kv||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=kv&&this.mark.eq(t)}markDirty(t,r){if(super.markDirty(t,r),this.dirty!=hg){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty0&&(i=s2e(i,0,t,n));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},n,a),h=d&&d.dom,m=d&&d.contentDOM;if(r.isText){if(!h)h=document.createTextNode(r.text);else if(h.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else h||({dom:h,contentDOM:m}=o5.renderSpec(document,r.type.spec.toDOM(r),null,r.attrs));!m&&!r.isText&&h.nodeName!="BR"&&(h.hasAttribute("contenteditable")||(h.contentEditable="false"),r.type.spec.draggable&&(h.draggable=!0));let x=h;return h=Aat(h,n,r),d?c=new Lqt(t,r,n,a,h,m||null,x,d,i,l+1):r.isText?new Qfe(t,r,n,a,h,x,i):new gj(t,r,n,a,h,m||null,x,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 r=this.children.length-1;r>=0;r--){let n=this.children[r];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;break}}t.contentElement||(t.getContent=()=>dn.empty)}return t}matchesNode(t,r,n){return this.dirty==hg&&t.eq(this.node)&&Jde(r,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,r){let n=this.node.inlineContent,a=r,i=t.composing?this.localCompositionInfo(t,r):null,l=i&&i.pos>-1?i:null,o=i&&i.pos<0,c=new Dqt(this,l&&l.node,t);Fqt(this.node,this.innerDeco,(d,h,m)=>{d.spec.marks?c.syncToMarks(d.spec.marks,n,t,h):d.type.side>=0&&!m&&c.syncToMarks(h==this.node.childCount?Kl.none:this.node.child(h).marks,n,t,h),c.placeWidget(d,t,a)},(d,h,m,x)=>{c.syncToMarks(d.marks,n,t,x);let y;c.findNodeMatch(d,h,m,x)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,h,m,y,t)||c.updateNextNode(d,h,m,t,x,a)||c.addNode(d,h,m,t,a),a+=d.nodeSize}),c.syncToMarks([],n,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==a4)&&(l&&this.protectLocalComposition(t,l),Tat(this.contentDOM,this.children,t),OM&&Bqt(this.dom))}localCompositionInfo(t,r){let{from:n,to:a}=t.state.selection;if(!(t.state.selection instanceof oi)||nr+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=zqt(this.node.content,l,n-r,a-r);return o<0?null:{node:i,pos:o,text:l}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:r,pos:n,text:a}){if(this.getDesc(r))return;let i=r;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 Iqt(this,i,r,a);t.input.compositionNodes.push(l),this.children=s2e(this.children,n,n+a.length,t,l)}update(t,r,n,a){return this.dirty==kv||!t.sameMarkup(this.node)?!1:(this.updateInner(t,r,n,a),!0)}updateInner(t,r,n,a){this.updateOuterDeco(r),this.node=t,this.innerDeco=n,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=hg}updateOuterDeco(t){if(Jde(t,this.outerDeco))return;let r=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=Eat(this.dom,this.nodeDOM,t2e(this.outerDeco,this.node,r),t2e(t,this.node,r)),this.dom!=n&&(n.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 mFe(s,t,r,n,a){Aat(n,t,s);let i=new gj(void 0,s,t,r,n,n,n,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class Qfe extends gj{constructor(t,r,n,a,i,l,o){super(t,r,n,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,r,n,a){return this.dirty==kv||this.dirty!=hg&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(r),(this.dirty!=hg||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=hg,!0)}inParent(){let t=this.parent.contentDOM;for(let r=this.nodeDOM;r;r=r.parentNode)if(r==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,r,n){return t==this.nodeDOM?this.posAtStart+Math.min(r,this.node.text.length):super.localPosFromDOM(t,r,n)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,r,n){let a=this.node.cut(t,r),i=document.createTextNode(a.text);return new Qfe(this.parent,a,this.outerDeco,this.innerDeco,i,i,n)}markDirty(t,r){super.markDirty(t,r),this.dom!=this.nodeDOM&&(t==0||r==this.nodeDOM.nodeValue.length)&&(this.dirty=kv)}get domAtom(){return!1}isText(t){return this.node.text==t}}class Cat extends pB{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==hg&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Lqt extends gj{constructor(t,r,n,a,i,l,o,c,d,h){super(t,r,n,a,i,l,o,d,h),this.spec=c}update(t,r,n,a){if(this.dirty==kv)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,r,n);return i&&this.updateInner(t,r,n,a),i}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,r,n,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,r,n,a){this.spec.setSelection?this.spec.setSelection(t,r,n.root):super.setSelection(t,r,n,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 Tat(s,t,r){let n=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 h=F3.create(this.top,t[l],r,n);this.top.children.splice(this.index,0,h),this.top=h,this.changed=!0}this.index=0,l++}}findNodeMatch(t,r,n,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,r,n))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(n){let d=r.children[n-1];if(d instanceof F3)r=d,n=d.children.length;else{o=d,n--;break}}else{if(r==t)break e;n=r.parent.children.indexOf(r),r=r.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 Oqt(s,t){return s.type.side-t.type.side}function Fqt(s,t,r,n){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let v=i+x.nodeSize;if(x.isText){let b=v;l!b.inline):o.slice();n(x,w,t.forChild(i,x),y),i=v}}function Bqt(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 zqt(s,t,r,n){for(let a=0,i=0;a=r){if(i>=n&&c.slice(n-t.length-o,n-o)==t)return n-t.length;let d=o=0&&d+t.length+o>=r)return o+d;if(r==n&&c.length>=n+t.length-o&&c.slice(n-o,n-o+t.length)==t)return n}}return-1}function s2e(s,t,r,n,a){let i=[];for(let l=0,o=0;l=r||h<=t?i.push(c):(dr&&i.push(c.slice(r-d,c.size,n)))}return i}function g3e(s,t=null){let r=s.domSelectionRange(),n=s.state.doc;if(!r.focusNode)return null;let a=s.docView.nearestDesc(r.focusNode),i=a&&a.size==0,l=s.docView.posFromDOM(r.focusNode,r.focusOffset,1);if(l<0)return null;let o=n.resolve(l),c,d;if(Xfe(r)){for(c=l;a&&!a.node;)a=a.parent;let m=a.node;if(a&&m.isAtom&&Xa.isSelectable(m)&&a.parent&&!(m.isInline&&mqt(r.focusNode,r.focusOffset,a.dom))){let x=a.posBefore;d=new Xa(l==x?o:n.resolve(x))}}else{if(r instanceof s.dom.ownerDocument.defaultView.Selection&&r.rangeCount>1){let m=l,x=l;for(let y=0;y{(r.anchorNode!=n||r.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!Mat(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function Uqt(s){let t=s.domSelection();if(!t)return;let r=s.cursorWrapper.dom,n=r.nodeName=="IMG";n?t.collapse(r.parentNode,Vh(r)+1):t.collapse(r,0),!n&&!s.state.selection.visible&&sp&&xj<=11&&(r.disabled=!0,r.disabled=!1)}function Iat(s,t){if(t instanceof Xa){let r=s.docView.descAt(t.from);r!=s.lastSelectedViewDesc&&(yFe(s),r&&r.selectNode(),s.lastSelectedViewDesc=r)}else yFe(s)}function yFe(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function y3e(s,t,r,n){return s.someProp("createSelectionBetween",a=>a(s,t,r))||oi.between(t,r,n)}function vFe(s){return s.editable&&!s.hasFocus()?!1:Lat(s)}function Lat(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 qqt(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),r=s.domSelectionRange();return O3(t.node,t.offset,r.anchorNode,r.anchorOffset)}function r2e(s,t){let{$anchor:r,$head:n}=s.selection,a=t>0?r.max(n):r.min(n),i=a.parent.inlineContent?a.depth?s.doc.resolve(t>0?a.after():a.before()):null:a;return i&&pi.findFrom(i,t)}function nw(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function bFe(s,t,r){let n=s.state.selection;if(n instanceof oi)if(r.indexOf("s")>-1){let{$head:a}=n,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 nw(s,new oi(n.$anchor,l))}else if(n.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=r2e(s.state,t);return a&&a instanceof Xa?nw(s,a):!1}else if(!(Hx&&r.indexOf("m")>-1)){let a=n.$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?Xa.isSelectable(i)?nw(s,new Xa(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):fB?nw(s,new oi(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(n instanceof Xa&&n.node.isInline)return nw(s,new oi(t>0?n.$to:n.$from));{let a=r2e(s.state,t);return a?nw(s,a):!1}}}function eue(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function xO(s,t){let r=s.pmViewDesc;return r&&r.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function JT(s,t){return t<0?Vqt(s):Hqt(s)}function Vqt(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a,i,l=!1;for(ug&&r.nodeType==1&&n0){if(r.nodeType!=1)break;{let o=r.childNodes[n-1];if(xO(o,-1))a=r,i=--n;else if(o.nodeType==3)r=o,n=r.nodeValue.length;else break}}else{if(Pat(r))break;{let o=r.previousSibling;for(;o&&xO(o,-1);)a=r.parentNode,i=Vh(o),o=o.previousSibling;if(o)r=o,n=eue(r);else{if(r=r.parentNode,r==s.dom)break;n=0}}}l?n2e(s,r,n):a&&n2e(s,a,i)}function Hqt(s){let t=s.domSelectionRange(),r=t.focusNode,n=t.focusOffset;if(!r)return;let a=eue(r),i,l;for(;;)if(n{s.state==a&&bb(s)},50)}function _Fe(s,t){let r=s.state.doc.resolve(t);if(!(Kh||vat)&&r.parent.inlineContent){let a=s.coordsAtPos(t);if(t>r.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 wFe(s,t,r){let n=s.state.selection;if(n instanceof oi&&!n.empty||r.indexOf("s")>-1||Hx&&r.indexOf("m")>-1)return!1;let{$from:a,$to:i}=n;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=r2e(s.state,t);if(l&&l instanceof Xa)return nw(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=n instanceof dg?pi.near(l,t):pi.findFrom(l,t);return o?nw(s,o):!1}return!1}function jFe(s,t){if(!(s.state.selection instanceof oi))return!0;let{$head:r,$anchor:n,empty:a}=s.state.selection;if(!r.sameParent(n))return!0;if(!a)return!1;if(s.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!r.textOffset&&(t<0?r.nodeBefore:r.nodeAfter);if(i&&!i.isText){let l=s.state.tr;return t<0?l.delete(r.pos-i.nodeSize,r.pos):l.delete(r.pos,r.pos+i.nodeSize),s.dispatch(l),!0}return!1}function NFe(s,t,r){s.domObserver.stop(),t.contentEditable=r,s.domObserver.start()}function Kqt(s){if(!Nm||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:r}=s.domSelectionRange();if(t&&t.nodeType==1&&r==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let n=t.firstChild;NFe(s,n,"true"),setTimeout(()=>NFe(s,n,"false"),20)}return!1}function Yqt(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function Zqt(s,t){let r=t.keyCode,n=Yqt(t);if(r==8||Hx&&r==72&&n=="c")return jFe(s,-1)||JT(s,-1);if(r==46&&!t.shiftKey||Hx&&r==68&&n=="c")return jFe(s,1)||JT(s,1);if(r==13||r==27)return!0;if(r==37||Hx&&r==66&&n=="c"){let a=r==37?_Fe(s,s.state.selection.from)=="ltr"?-1:1:-1;return bFe(s,a,n)||JT(s,a)}else if(r==39||Hx&&r==70&&n=="c"){let a=r==39?_Fe(s,s.state.selection.from)=="ltr"?1:-1:1;return bFe(s,a,n)||JT(s,a)}else{if(r==38||Hx&&r==80&&n=="c")return wFe(s,-1,n)||JT(s,-1);if(r==40||Hx&&r==78&&n=="c")return Kqt(s)||wFe(s,1,n)||JT(s,1);if(n==(Hx?"m":"c")&&(r==66||r==73||r==89||r==90))return!0}return!1}function v3e(s,t){s.someProp("transformCopied",y=>{t=y(t,s)});let r=[],{content:n,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&n.childCount==1&&n.firstChild.childCount==1;){a--,i--;let y=n.firstChild;r.push(y.type.name,y.attrs!=y.type.defaultAttrs?y.attrs:null),n=y.content}let l=s.someProp("clipboardSerializer")||o5.fromSchema(s.state.schema),o=zat(),c=o.createElement("div");c.appendChild(l.serializeFragment(n,{document:o}));let d=c.firstChild,h,m=0;for(;d&&d.nodeType==1&&(h=Bat[d.nodeName.toLowerCase()]);){for(let y=h.length-1;y>=0;y--){let v=o.createElement(h[y]);for(;c.firstChild;)v.appendChild(c.firstChild);c.appendChild(v),m++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${m?` -${m}`:""} ${JSON.stringify(r)}`);let x=s.someProp("clipboardTextSerializer",y=>y(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:x,slice:t}}function Dat(s,t,r,n,a){let i=a.parent.type.spec.code,l,o;if(!r&&!t)return null;let c=!!t&&(n||i||!r);if(c){if(s.someProp("transformPastedText",x=>{t=x(t,i||n,s)}),i)return o=new Un(dn.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",x=>{o=x(o,s,!0)}),o;let m=s.someProp("clipboardTextParser",x=>x(t,a,n,s));if(m)o=m;else{let x=a.marks(),{schema:y}=s.state,v=o5.fromSchema(y);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(w=>{let b=l.appendChild(document.createElement("p"));w&&b.appendChild(v.serializeNode(y.text(w,x)))})}}else s.someProp("transformPastedHTML",m=>{r=m(r,s)}),l=eVt(r),fB&&tVt(l);let d=l&&l.querySelector("[data-pm-slice]"),h=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(h&&h[3])for(let m=+h[3];m>0;m--){let x=l.firstChild;for(;x&&x.nodeType!=1;)x=x.nextSibling;if(!x)break;l=x}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||mO.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||h),context:a,ruleFromNode(x){return x.nodeName=="BR"&&!x.nextSibling&&x.parentNode&&!Xqt.test(x.parentNode.nodeName)?{ignore:!0}:null}})),h)o=sVt(kFe(o,+h[1],+h[2]),h[4]);else if(o=Un.maxOpen(Qqt(o.content,a),!0),o.openStart||o.openEnd){let m=0,x=0;for(let y=o.content.firstChild;m{o=m(o,s,c)}),o}const Xqt=/^(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 Qqt(s,t){if(s.childCount<2)return s;for(let r=t.depth;r>=0;r--){let a=t.node(r).contentMatchAt(t.index(r)),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&&Oat(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=Fat(l[l.length-1],i.length));let h=Rat(o,c);l.push(h),a=a.matchType(h.type),i=c}}),l)return dn.from(l)}return s}function Rat(s,t,r=0){for(let n=t.length-1;n>=r;n--)s=t[n].create(null,dn.from(s));return s}function Oat(s,t,r,n,a){if(a1&&(i=0),a=r&&(o=t<0?l.contentMatchAt(0).fillBefore(o,i<=a).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore(dn.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function kFe(s,t,r){return tr})),s1e.createHTML(s)):s}function eVt(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let r=zat().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(s),a;if((a=n&&Bat[n[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),r.innerHTML=Jqt(s),a)for(let i=0;i=0;o-=2){let c=r.nodes[n[o]];if(!c||c.hasRequiredAttrs())break;a=dn.from(c.create(n[o+1],a)),i++,l++}return new Un(a,i,l)}const vf={},bf={},rVt={touchstart:!0,touchmove:!0};class nVt{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 aVt(s){for(let t in vf){let r=vf[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=n=>{oVt(s,n)&&!b3e(s,n)&&(s.editable||!(n.type in bf))&&r(s,n)},rVt[t]?{passive:!0}:void 0)}Nm&&s.dom.addEventListener("input",()=>null),i2e(s)}function Fw(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function iVt(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 i2e(s){s.someProp("handleDOMEvents",t=>{for(let r in t)s.input.eventHandlers[r]||s.dom.addEventListener(r,s.input.eventHandlers[r]=n=>b3e(s,n))})}function b3e(s,t){return s.someProp("handleDOMEvents",r=>{let n=r[t.type];return n?n(s,t)||t.defaultPrevented:!1})}function oVt(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let r=t.target;r!=s.dom;r=r.parentNode)if(!r||r.nodeType==11||r.pmViewDesc&&r.pmViewDesc.stopEvent(t))return!1;return!0}function lVt(s,t){!b3e(s,t)&&vf[t.type]&&(s.editable||!(t.type in bf))&&vf[t.type](s,t)}bf.keydown=(s,t)=>{let r=t;if(s.input.shiftKey=r.keyCode==16||r.shiftKey,!Uat(s,r)&&(s.input.lastKeyCode=r.keyCode,s.input.lastKeyCodeTime=Date.now(),!(ib&&Kh&&r.keyCode==13)))if(r.keyCode!=229&&s.domObserver.forceFlush(),OM&&r.keyCode==13&&!r.ctrlKey&&!r.altKey&&!r.metaKey){let n=Date.now();s.input.lastIOSEnter=n,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==n&&(s.someProp("handleKeyDown",a=>a(s,KC(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",n=>n(s,r))||Zqt(s,r)?r.preventDefault():Fw(s,"key")};bf.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};bf.keypress=(s,t)=>{let r=t;if(Uat(s,r)||!r.charCode||r.ctrlKey&&!r.altKey||Hx&&r.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,r))){r.preventDefault();return}let n=s.state.selection;if(!(n instanceof oi)||!n.$from.sameParent(n.$to)){let a=String.fromCharCode(r.charCode),i=()=>s.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!s.someProp("handleTextInput",l=>l(s,n.$from.pos,n.$to.pos,a,i))&&s.dispatch(i()),r.preventDefault()}};function Jfe(s){return{left:s.clientX,top:s.clientY}}function cVt(s,t){let r=t.x-s.clientX,n=t.y-s.clientY;return r*r+n*n<100}function _3e(s,t,r,n,a){if(n==-1)return!1;let i=s.state.doc.resolve(n);for(let l=i.depth+1;l>0;l--)if(s.someProp(t,o=>l>i.depth?o(s,r,i.nodeAfter,i.before(l),a,!0):o(s,r,i.node(l),i.before(l),a,!1)))return!0;return!1}function $A(s,t,r){if(s.focused||s.focus(),s.state.selection.eq(t))return;let n=s.state.tr.setSelection(t);n.setMeta("pointer",!0),s.dispatch(n)}function dVt(s,t){if(t==-1)return!1;let r=s.state.doc.resolve(t),n=r.nodeAfter;return n&&n.isAtom&&Xa.isSelectable(n)?($A(s,new Xa(r)),!0):!1}function uVt(s,t){if(t==-1)return!1;let r=s.state.selection,n,a;r instanceof Xa&&(n=r.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(Xa.isSelectable(o)){n&&r.$from.depth>0&&l>=r.$from.depth&&i.before(r.$from.depth+1)==r.$from.pos?a=i.before(r.$from.depth):a=i.before(l);break}}return a!=null?($A(s,Xa.create(s.state.doc,a)),!0):!1}function hVt(s,t,r,n,a){return _3e(s,"handleClickOn",t,r,n)||s.someProp("handleClick",i=>i(s,t,n))||(a?uVt(s,r):dVt(s,r))}function mVt(s,t,r,n){return _3e(s,"handleDoubleClickOn",t,r,n)||s.someProp("handleDoubleClick",a=>a(s,t,n))}function fVt(s,t,r,n){return _3e(s,"handleTripleClickOn",t,r,n)||s.someProp("handleTripleClick",a=>a(s,t,n))||pVt(s,r,n)}function pVt(s,t,r){if(r.button!=0)return!1;let n=s.state.doc;if(t==-1)return n.inlineContent?($A(s,oi.create(n,0,n.content.size)),!0):!1;let a=n.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)$A(s,oi.create(n,o+1,o+1+l.content.size));else if(Xa.isSelectable(l))$A(s,Xa.create(n,o));else continue;return!0}}function w3e(s){return tue(s)}const $at=Hx?"metaKey":"ctrlKey";vf.mousedown=(s,t)=>{let r=t;s.input.shiftKey=r.shiftKey;let n=w3e(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&cVt(r,s.input.lastClick)&&!r[$at]&&s.input.lastClick.button==r.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:r.clientX,y:r.clientY,type:i,button:r.button};let l=s.posAtCoords(Jfe(r));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new xVt(s,l,r,!!n)):(i=="doubleClick"?mVt:fVt)(s,l.pos,l.inside,r)?r.preventDefault():Fw(s,"pointer"))};class xVt{constructor(t,r,n,a){this.view=t,this.pos=r,this.event=n,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!n[$at],this.allowDefault=n.shiftKey;let i,l;if(r.inside>-1)i=t.state.doc.nodeAt(r.inside),l=r.inside;else{let h=t.state.doc.resolve(r.pos);i=h.parent,l=h.depth?h.before():0}const o=a?null:n.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;n.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Xa&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&ug&&!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)),Fw(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(()=>bb(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let r=this.pos;this.view.state.doc!=this.startDoc&&(r=this.view.posAtCoords(Jfe(t))),this.updateAllowDefault(t),this.allowDefault||!r?Fw(this.view,"pointer"):hVt(this.view,r.pos,r.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||Nm&&this.mightDrag&&!this.mightDrag.node.isAtom||Kh&&!this.view.state.selection.visible&&Math.min(Math.abs(r.pos-this.view.state.selection.from),Math.abs(r.pos-this.view.state.selection.to))<=2)?($A(this.view,pi.near(this.view.state.doc.resolve(r.pos))),t.preventDefault()):Fw(this.view,"pointer")}move(t){this.updateAllowDefault(t),Fw(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)}}vf.touchstart=s=>{s.input.lastTouch=Date.now(),w3e(s),Fw(s,"pointer")};vf.touchmove=s=>{s.input.lastTouch=Date.now(),Fw(s,"pointer")};vf.contextmenu=s=>w3e(s);function Uat(s,t){return s.composing?!0:Nm&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const gVt=ib?5e3:-1;bf.compositionstart=bf.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,r=t.selection.$to;if(t.selection instanceof oi&&(t.storedMarks||!r.textOffset&&r.parentOffset&&r.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||Kh&&vat&&yVt(s)))s.markCursor=s.state.storedMarks||r.marks(),tue(s,!0),s.markCursor=null;else if(tue(s,!t.selection.empty),ug&&t.selection.empty&&r.parentOffset&&!r.textOffset&&r.nodeBefore.marks.length){let n=s.domSelectionRange();for(let a=n.focusNode,i=n.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}qat(s,gVt)};function yVt(s){let{focusNode:t,focusOffset:r}=s.domSelectionRange();if(!t||t.nodeType!=1||r>=t.childNodes.length)return!1;let n=t.childNodes[r];return n.nodeType==1&&n.contentEditable=="false"}bf.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++,qat(s,20))};function qat(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>tue(s),t))}function Vat(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=bVt());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function vVt(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let r=uqt(t.focusNode,t.focusOffset),n=hqt(t.focusNode,t.focusOffset);if(r&&n&&r!=n){let a=n.pmViewDesc,i=s.domObserver.lastChangedTextNode;if(r==i||n==i)return i;if(!a||!a.isText(n.nodeValue))return n;if(s.input.compositionNode==n){let l=r.pmViewDesc;if(!(!l||!l.isText(r.nodeValue)))return n}}return r||n}function bVt(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function tue(s,t=!1){if(!(ib&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),Vat(s),t||s.docView&&s.docView.dirty){let r=g3e(s),n=s.state.selection;return r&&!r.eq(n)?s.dispatch(s.state.tr.setSelection(r)):(s.markCursor||t)&&!n.$from.node(n.$from.sharedDepth(n.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function _Vt(s,t){if(!s.dom.parentNode)return;let r=s.dom.parentNode.appendChild(document.createElement("div"));r.appendChild(t),r.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),a=document.createRange();a.selectNodeContents(t),s.dom.blur(),n.removeAllRanges(),n.addRange(a),setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r),s.focus()},50)}const S8=sp&&xj<15||OM&&xqt<604;vf.copy=bf.cut=(s,t)=>{let r=t,n=s.state.selection,a=r.type=="cut";if(n.empty)return;let i=S8?null:r.clipboardData,l=n.content(),{dom:o,text:c}=v3e(s,l);i?(r.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):_Vt(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function wVt(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function jVt(s,t){if(!s.dom.parentNode)return;let r=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,n=s.dom.parentNode.appendChild(document.createElement(r?"textarea":"div"));r||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let a=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),n.parentNode&&n.parentNode.removeChild(n),r?C8(s,n.value,null,a,t):C8(s,n.textContent,n.innerHTML,a,t)},50)}function C8(s,t,r,n,a){let i=Dat(s,t,r,n,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Un.empty)))return!0;if(!i)return!1;let l=wVt(i),o=l?s.state.tr.replaceSelectionWith(l,n):s.state.tr.replaceSelection(i);return s.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Hat(s){let t=s.getData("text/plain")||s.getData("Text");if(t)return t;let r=s.getData("text/uri-list");return r?r.replace(/\r?\n/g," "):""}bf.paste=(s,t)=>{let r=t;if(s.composing&&!ib)return;let n=S8?null:r.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;n&&C8(s,Hat(n),n.getData("text/html"),a,r)?r.preventDefault():jVt(s,r)};class Gat{constructor(t,r,n){this.slice=t,this.move=r,this.node=n}}const NVt=Hx?"altKey":"ctrlKey";function Wat(s,t){let r;return s.someProp("dragCopies",n=>{r=r||n(t)}),r!=null?!r:!t[NVt]}vf.dragstart=(s,t)=>{let r=t,n=s.input.mouseDown;if(n&&n.done(),!r.dataTransfer)return;let a=s.state.selection,i=a.empty?null:s.posAtCoords(Jfe(r)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Xa?a.to-1:a.to))){if(n&&n.mightDrag)l=Xa.create(s.state.doc,n.mightDrag.pos);else if(r.target&&r.target.nodeType==1){let m=s.docView.nearestDesc(r.target,!0);m&&m.node.type.spec.draggable&&m!=s.docView&&(l=Xa.create(s.state.doc,m.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:h}=v3e(s,o);(!r.dataTransfer.files.length||!Kh||yat>120)&&r.dataTransfer.clearData(),r.dataTransfer.setData(S8?"Text":"text/html",c.innerHTML),r.dataTransfer.effectAllowed="copyMove",S8||r.dataTransfer.setData("text/plain",d),s.dragging=new Gat(h,Wat(s,r),l)};vf.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};bf.dragover=bf.dragenter=(s,t)=>t.preventDefault();bf.drop=(s,t)=>{try{kVt(s,t,s.dragging)}finally{s.dragging=null}};function kVt(s,t,r){if(!t.dataTransfer)return;let n=s.posAtCoords(Jfe(t));if(!n)return;let a=s.state.doc.resolve(n.pos),i=r&&r.slice;i?s.someProp("transformPasted",y=>{i=y(i,s,!1)}):i=Dat(s,Hat(t.dataTransfer),S8?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(r&&Wat(s,t));if(s.someProp("handleDrop",y=>y(s,t,i||Un.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?cat(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:y}=r;y?y.replace(c):c.deleteSelection()}let d=c.mapping.map(o),h=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,m=c.doc;if(h?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(m))return;let x=c.doc.resolve(d);if(h&&Xa.isSelectable(i.content.firstChild)&&x.nodeAfter&&x.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Xa(x));else{let y=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((v,w,b,N)=>y=N),c.setSelection(y3e(s,x,c.doc.resolve(y)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}vf.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())&&bb(s)},20))};vf.blur=(s,t)=>{let r=t;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),r.relatedTarget&&s.dom.contains(r.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};vf.beforeinput=(s,t)=>{if(Kh&&ib&&t.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:n}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=n||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",i=>i(s,KC(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 bf)vf[s]=bf[s];function T8(s,t){if(s==t)return!0;for(let r in s)if(s[r]!==t[r])return!1;for(let r in t)if(!(r in s))return!1;return!0}class sue{constructor(t,r){this.toDOM=t,this.spec=r||c3,this.side=this.spec.side||0}map(t,r,n,a){let{pos:i,deleted:l}=t.mapResult(r.from+a,this.side<0?-1:1);return l?null:new df(i-n,i-n,this)}valid(){return!0}eq(t){return this==t||t instanceof sue&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&T8(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class yj{constructor(t,r){this.attrs=t,this.spec=r||c3}map(t,r,n,a){let i=t.map(r.from+a,this.spec.inclusiveStart?-1:1)-n,l=t.map(r.to+a,this.spec.inclusiveEnd?1:-1)-n;return i>=l?null:new df(i,l,this)}valid(t,r){return r.from=t&&(!i||i(o.spec))&&n.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,r-o,n,a+o,i)}}map(t,r,n){return this==fm||t.maps.length==0?this:this.mapInner(t,r,0,0,n||c3)}mapInner(t,r,n,a,i){let l;for(let o=0;o{let d=c+n,h;if(h=Yat(r,o,d)){for(a||(a=this.children.slice());io&&m.to=t){this.children[o]==t&&(n=this.children[o+2]);break}let i=t+1,l=i+r.content.size;for(let o=0;oi&&c.type instanceof yj){let d=Math.max(i,c.from)-i,h=Math.min(l,c.to)-i;da.map(t,r,c3));return xw.from(n)}forChild(t,r){if(r.isLeaf)return Sd.empty;let n=[];for(let a=0;ar instanceof Sd)?t:t.reduce((r,n)=>r.concat(n instanceof Sd?n:n.members),[]))}}forEachSet(t){for(let r=0;r{let b=w-v-(y-x);for(let N=0;NS+h-m)continue;let T=o[N]+h-m;y>=T?o[N+1]=x<=T?-2:-1:x>=h&&b&&(o[N]+=b,o[N+1]+=b)}m+=b}),h=r.maps[d].map(h,-1)}let c=!1;for(let d=0;d=n.content.size){c=!0;continue}let x=r.map(s[d+1]+i,-1),y=x-a,{index:v,offset:w}=n.content.findIndex(m),b=n.maybeChild(v);if(b&&w==m&&w+b.nodeSize==y){let N=o[d+2].mapInner(r,b,h+1,s[d]+i+1,l);N!=fm?(o[d]=m,o[d+1]=y,o[d+2]=N):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=CVt(o,s,t,r,a,i,l),h=rue(d,n,0,l);t=h.local;for(let m=0;mr&&l.to{let d=Yat(s,o,c+r);if(d){i=!0;let h=rue(d,o,r+c+1,n);h!=fm&&a.push(c,c+o.nodeSize,h)}});let l=Kat(i?Zat(s):s,-r).sort(d3);for(let o=0;o0;)t++;s.splice(t,0,r)}function r1e(s){let t=[];return s.someProp("decorations",r=>{let n=r(s.state);n&&n!=fm&&t.push(n)}),s.cursorWrapper&&t.push(Sd.create(s.state.doc,[s.cursorWrapper.deco])),xw.from(t)}const TVt={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},EVt=sp&&xj<=11;class AVt{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 MVt{constructor(t,r){this.view=t,this.handleDOMChange=r,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new AVt,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(n=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():Nm&&t.composing&&n.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),EVt&&(this.onCharData=n=>{this.queue.push({target:n.target,type:"characterData",oldValue:n.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,TVt)),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 r=0;rthis.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(vFe(this.view)){if(this.suppressingSelectionUpdates)return bb(this.view);if(sp&&xj<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&O3(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 r=new Set,n;for(let i=t.focusNode;i;i=RM(i))r.add(i);for(let i=t.anchorNode;i;i=RM(i))if(r.has(i)){n=i;break}let a=n&&this.view.docView.nearestDesc(n);if(a&&a.ignoreMutation({type:"selection",target:n.nodeType==3?n.parentNode:n}))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 r=this.pendingRecords();r.length&&(this.queue=[]);let n=t.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&vFe(t)&&!this.ignoreSelectionChange(n),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let h=0;hh.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46)){for(let h of c)if(h.nodeName=="BR"&&h.parentNode){let m=h.nextSibling;for(;m&&m.nodeType==1;){if(m.contentEditable=="false"){h.parentNode.removeChild(h);break}m=m.firstChild}}}else if(ug&&c.length){let h=c.filter(m=>m.nodeName=="BR");if(h.length==2){let[m,x]=h;m.parentNode&&m.parentNode.parentNode==x.parentNode?x.remove():m.remove()}else{let{focusNode:m}=this.currentSelection;for(let x of h){let y=x.parentNode;y&&y.nodeName=="LI"&&(!m||PVt(t,m)!=y)&&x.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),IVt(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,DVt(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(n)||bb(t),this.currentSelection.set(n))}registerMutation(t,r){if(r.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(n==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!n||n.ignoreMutation(t))return null;if(t.type=="childList"){for(let h=0;ha;b--){let N=n.childNodes[b-1],S=N.pmViewDesc;if(N.nodeName=="BR"&&!S){i=b;break}if(!S||S.size)break}let m=s.state.doc,x=s.someProp("domParser")||mO.fromSchema(s.state.schema),y=m.resolve(l),v=null,w=x.parse(n,{topNode:y.parent,topMatch:y.parent.contentMatchAt(y.index()),topOpen:!0,from:a,to:i,preserveWhitespace:y.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:OVt,context:y});if(d&&d[0].pos!=null){let b=d[0].pos,N=d[1]&&d[1].pos;N==null&&(N=b),v={anchor:b+l,head:N+l}}return{doc:w,sel:v,from:l,to:o}}function OVt(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(Nm&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(s.parentNode.lastChild==s||Nm&&/^(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 FVt=/^(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 BVt(s,t,r,n,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let R=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,$=g3e(s,R);if($&&!s.state.selection.eq($)){if(Kh&&ib&&s.input.lastKeyCode===13&&Date.now()-100z(s,KC(13,"Enter"))))return;let F=s.state.tr.setSelection($);R=="pointer"?F.setMeta("pointer",!0):R=="key"&&F.scrollIntoView(),i&&F.setMeta("composition",i),s.dispatch(F)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(r);t=l.before(o+1),r=s.state.doc.resolve(r).after(o+1);let c=s.state.selection,d=RVt(s,t,r),h=s.state.doc,m=h.slice(d.from,d.to),x,y;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ib)&&a.some(R=>R.nodeType==1&&!FVt.test(R.nodeName))&&(!v||v.endA>=v.endB)&&s.someProp("handleKeyDown",R=>R(s,KC(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!v)if(n&&c instanceof oi&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))v={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let R=MFe(s,s.state.doc,d.sel);if(R&&!R.eq(s.state.selection)){let $=s.state.tr.setSelection(R);i&&$.setMeta("composition",i),s.dispatch($)}}return}s.state.selection.froms.state.selection.from&&v.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?v.start=s.state.selection.from:v.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(v.endB+=s.state.selection.to-v.endA,v.endA=s.state.selection.to)),sp&&xj<=11&&v.endB==v.start+1&&v.endA==v.start&&v.start>d.from&&d.doc.textBetween(v.start-d.from-1,v.start-d.from+1)=="  "&&(v.start--,v.endA--,v.endB--);let w=d.doc.resolveNoCache(v.start-d.from),b=d.doc.resolveNoCache(v.endB-d.from),N=h.resolve(v.start),S=w.sameParent(b)&&w.parent.inlineContent&&N.end()>=v.endA;if((OM&&s.input.lastIOSEnter>Date.now()-225&&(!S||a.some(R=>R.nodeName=="DIV"||R.nodeName=="P"))||!S&&w.posR(s,KC(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>v.start&&$Vt(h,v.start,v.endA,w,b)&&s.someProp("handleKeyDown",R=>R(s,KC(8,"Backspace")))){ib&&Kh&&s.domObserver.suppressSelectionUpdates();return}Kh&&v.endB==v.start&&(s.input.lastChromeDelete=Date.now()),ib&&!S&&w.start()!=b.start()&&b.parentOffset==0&&w.depth==b.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==v.endA&&(v.endB-=2,b=d.doc.resolveNoCache(v.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(R){return R(s,KC(13,"Enter"))})},20));let T=v.start,A=v.endA,I=R=>{let $=R||s.state.tr.replace(T,A,d.doc.slice(v.start-d.from,v.endB-d.from));if(d.sel){let F=MFe(s,$.doc,d.sel);F&&!(Kh&&s.composing&&F.empty&&(v.start!=v.endB||s.input.lastChromeDeletebb(s),20));let R=I(s.state.tr.delete(T,A)),$=h.resolve(v.start).marksAcross(h.resolve(v.endA));$&&R.ensureMarks($),s.dispatch(R)}else if(v.endA==v.endB&&(D=zVt(w.parent.content.cut(w.parentOffset,b.parentOffset),N.parent.content.cut(N.parentOffset,v.endA-N.start())))){let R=I(s.state.tr);D.type=="add"?R.addMark(T,A,D.mark):R.removeMark(T,A,D.mark),s.dispatch(R)}else if(w.parent.child(w.index()).isText&&w.index()==b.index()-(b.textOffset?0:1)){let R=w.parent.textBetween(w.parentOffset,b.parentOffset),$=()=>I(s.state.tr.insertText(R,T,A));s.someProp("handleTextInput",F=>F(s,T,A,R,$))||s.dispatch($())}else s.dispatch(I());else s.dispatch(I())}function MFe(s,t,r){return Math.max(r.anchor,r.head)>t.content.size?null:y3e(s,t.resolve(r.anchor),t.resolve(r.head))}function zVt(s,t){let r=s.firstChild.marks,n=t.firstChild.marks,a=r,i=n,l,o,c;for(let h=0;hh.mark(o.addToSet(h.marks));else if(a.length==0&&i.length==1)o=i[0],l="remove",c=h=>h.mark(o.removeFromSet(h.marks));else return null;let d=[];for(let h=0;hr||n1e(l,!0,!1)0&&(t||s.indexAfter(n)==s.node(n).childCount);)n--,a++,t=!1;if(r){let i=s.node(n).maybeChild(s.indexAfter(n));for(;i&&!i.isLeaf;)i=i.firstChild,a++}return a}function UVt(s,t,r,n,a){let i=s.findDiffStart(t,r);if(i==null)return null;let{a:l,b:o}=s.findDiffEnd(t,r+s.size,r+t.size);if(a=="end"){let c=Math.max(0,i-Math.min(l,o));n-=l+c-i}if(l=l?i-n:0;i-=c,i&&i=o?i-n:0;i-=c,i&&i=56320&&t<=57343&&r>=55296&&r<=56319}class Xat{constructor(t,r){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 nVt,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=r,this.state=r.state,this.directPlugins=r.plugins||[],this.directPlugins.forEach(OFe),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=DFe(this),PFe(this),this.nodeViews=RFe(this),this.docView=mFe(this.state.doc,LFe(this),r1e(this),this.dom,this),this.domObserver=new MVt(this,(n,a,i,l)=>BVt(this,n,a,i,l)),this.domObserver.start(),aVt(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 r in t)this._props[r]=t[r];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&i2e(this);let r=this._props;this._props=t,t.plugins&&(t.plugins.forEach(OFe),this.directPlugins=t.plugins),this.updateStateInner(t.state,r)}setProps(t){let r={};for(let n in this._props)r[n]=this._props[n];r.state=this.state;for(let n in t)r[n]=t[n];this.update(r)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,r){var n;let a=this.state,i=!1,l=!1;t.storedMarks&&this.composing&&(Vat(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=r.plugins;if(o||this._props.plugins!=r.plugins||this._props.nodeViews!=r.nodeViews){let y=RFe(this);VVt(y,this.nodeViews)&&(this.nodeViews=y,i=!0)}(o||r.handleDOMEvents!=this._props.handleDOMEvents)&&i2e(this),this.editable=DFe(this),PFe(this);let c=r1e(this),d=LFe(this),h=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",m=i||!this.docView.matchesNode(t.doc,d,c);(m||!t.selection.eq(a.selection))&&(l=!0);let x=h=="preserve"&&l&&this.dom.style.overflowAnchor==null&&vqt(this);if(l){this.domObserver.stop();let y=m&&(sp||Kh)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&qVt(a.selection,t.selection);if(m){let v=Kh?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=vVt(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=mFe(t.doc,d,c,this.dom,this)),v&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(y=!0)}y||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&qqt(this))?bb(this,y):(Iat(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((n=this.dragging)===null||n===void 0)&&n.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),h=="reset"?this.dom.scrollTop=0:h=="to selection"?this.scrollToSelection():x&&bqt(x)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",r=>r(this)))if(this.state.selection instanceof Xa){let r=this.docView.domAfterPos(this.state.selection.from);r.nodeType==1&&oFe(this,r.getBoundingClientRect(),t)}else oFe(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 r=0;r0&&ir.ownerDocument.getSelection()),this._root=r}return t||document}updateRoot(){this._root=null}posAtCoords(t){return Sqt(this,t)}coordsAtPos(t,r=1){return Nat(this,t,r)}domAtPos(t,r=0){return this.docView.domFromPos(t,r)}nodeDOM(t){let r=this.docView.descAt(t);return r?r.nodeDOM:null}posAtDOM(t,r,n=-1){let a=this.docView.posFromDOM(t,r,n);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(t,r){return Mqt(this,r||this.state,t)}pasteHTML(t,r){return C8(this,"",t,!1,r||new ClipboardEvent("paste"))}pasteText(t,r){return C8(this,t,null,!0,r||new ClipboardEvent("paste"))}serializeForClipboard(t){return v3e(this,t)}destroy(){this.docView&&(iVt(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],r1e(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,cqt())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return lVt(this,t)}domSelectionRange(){let t=this.domSelection();return t?Nm&&this.root.nodeType===11&&fqt(this.dom.ownerDocument)==this.dom&&LVt(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}Xat.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function LFe(s){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(s.editable),s.someProp("attributes",r=>{if(typeof r=="function"&&(r=r(s.state)),r)for(let n in r)n=="class"?t.class+=" "+r[n]:n=="style"?t.style=(t.style?t.style+";":"")+r[n]:!t[n]&&n!="contenteditable"&&n!="nodeName"&&(t[n]=String(r[n]))}),t.translate||(t.translate="no"),[df.node(0,s.state.doc.content.size,t)]}function PFe(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:df.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function DFe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function qVt(s,t){let r=Math.min(s.$anchor.sharedDepth(s.head),t.$anchor.sharedDepth(t.head));return s.$anchor.start(r)!=t.$anchor.start(r)}function RFe(s){let t=Object.create(null);function r(n){for(let a in n)Object.prototype.hasOwnProperty.call(t,a)||(t[a]=n[a])}return s.someProp("nodeViews",r),s.someProp("markViews",r),t}function VVt(s,t){let r=0,n=0;for(let a in s){if(s[a]!=t[a])return!0;r++}for(let a in t)n++;return r!=n}function OFe(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 Rj={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:"'"},nue={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},HVt=typeof navigator<"u"&&/Mac/.test(navigator.platform),GVt=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Hh=0;Hh<10;Hh++)Rj[48+Hh]=Rj[96+Hh]=String(Hh);for(var Hh=1;Hh<=24;Hh++)Rj[Hh+111]="F"+Hh;for(var Hh=65;Hh<=90;Hh++)Rj[Hh]=String.fromCharCode(Hh+32),nue[Hh]=String.fromCharCode(Hh);for(var a1e in Rj)nue.hasOwnProperty(a1e)||(nue[a1e]=Rj[a1e]);function WVt(s){var t=HVt&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||GVt&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",r=!t&&s.key||(s.shiftKey?nue:Rj)[s.keyCode]||s.key||"Unidentified";return r=="Esc"&&(r="Escape"),r=="Del"&&(r="Delete"),r=="Left"&&(r="ArrowLeft"),r=="Up"&&(r="ArrowUp"),r=="Right"&&(r="ArrowRight"),r=="Down"&&(r="ArrowDown"),r}const KVt=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),YVt=typeof navigator<"u"&&/Win/.test(navigator.platform);function ZVt(s){let t=s.split(/-(?!$)/),r=t[t.length-1];r=="Space"&&(r=" ");let n,a,i,l;for(let o=0;os.selection.empty?!1:(t&&t(s.tr.deleteSelection().scrollIntoView()),!0);function Qat(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("backward",s):r.parentOffset>0)?null:r}const eHt=(s,t,r)=>{let n=Qat(s,r);if(!n)return!1;let a=S3e(n);if(!a){let l=n.blockRange(),o=l&&KI(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(sit(s,a,t,-1))return!0;if(n.parent.content.size==0&&(FM(i,"end")||Xa.isSelectable(i)))for(let l=n.depth;;l--){let o=Yfe(s.doc,n.before(l),n.after(l),Un.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==n.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},tHt=(s,t,r)=>{let n=Qat(s,r);if(!n)return!1;let a=S3e(n);return a?Jat(s,a,t):!1},sHt=(s,t,r)=>{let n=eit(s,r);if(!n)return!1;let a=C3e(n);return a?Jat(s,a,t):!1};function Jat(s,t,r){let n=t.nodeBefore,a=n,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let h=a.lastChild;if(!h)return!1;a=h}let l=t.nodeAfter,o=l,c=t.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let h=o.firstChild;if(!h)return!1;o=h}let d=Yfe(s.doc,i,c,Un.empty);if(!d||d.from!=i||d instanceof mu&&d.slice.size>=c-i)return!1;if(r){let h=s.tr.step(d);h.setSelection(oi.create(h.doc,i)),r(h.scrollIntoView())}return!0}function FM(s,t,r=!1){for(let n=s;n;n=t=="start"?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(r&&n.childCount!=1)return!1}return!1}const rHt=(s,t,r)=>{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("backward",s):n.parentOffset>0)return!1;i=S3e(n)}let l=i&&i.nodeBefore;return!l||!Xa.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Xa.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function S3e(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 eit(s,t){let{$cursor:r}=s.selection;return!r||(t?!t.endOfTextblock("forward",s):r.parentOffset{let n=eit(s,r);if(!n)return!1;let a=C3e(n);if(!a)return!1;let i=a.nodeAfter;if(sit(s,a,t,1))return!0;if(n.parent.content.size==0&&(FM(i,"start")||Xa.isSelectable(i))){let l=Yfe(s.doc,n.before(),n.after(),Un.empty);if(l&&l.slice.size{let{$head:n,empty:a}=s.selection,i=n;if(!a)return!1;if(n.parent.isTextblock){if(r?!r.endOfTextblock("forward",s):n.parentOffset=0;t--){let r=s.node(t);if(s.index(t)+1{let r=s.selection,n=r instanceof Xa,a;if(n){if(r.node.isTextblock||!r2(s.doc,r.from))return!1;a=r.from}else if(a=Kfe(s.doc,r.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);n&&i.setSelection(Xa.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},oHt=(s,t)=>{let r=s.selection,n;if(r instanceof Xa){if(r.node.isTextblock||!r2(s.doc,r.to))return!1;n=r.to}else if(n=Kfe(s.doc,r.to,1),n==null)return!1;return t&&t(s.tr.join(n).scrollIntoView()),!0},lHt=(s,t)=>{let{$from:r,$to:n}=s.selection,a=r.blockRange(n),i=a&&KI(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},cHt=(s,t)=>{let{$head:r,$anchor:n}=s.selection;return!r.parent.type.spec.code||!r.sameParent(n)?!1:(t&&t(s.tr.insertText(` `).scrollIntoView()),!0)};function tit(s){for(let t=0;t{let{$head:r,$anchor:n}=s.selection;if(!r.parent.type.spec.code||!r.sameParent(n))return!1;let a=r.node(-1),i=r.indexAfter(-1),l=tit(a.contentMatchAt(i));if(!l||!a.canReplaceWith(i,i,l))return!1;if(t){let o=r.after(),c=s.tr.replaceWith(o,o,l.createAndFill());c.setSelection(pi.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},uHt=(s,t)=>{let r=s.selection,{$from:n,$to:a}=r;if(r instanceof dg||n.parent.inlineContent||a.parent.inlineContent)return!1;let i=tit(a.parent.contentMatchAt(a.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let l=(!n.parentOffset&&a.index(){let{$cursor:r}=s.selection;if(!r||r.parent.content.size)return!1;if(r.depth>1&&r.after()!=r.end(-1)){let i=r.before();if(BA(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let n=r.blockRange(),a=n&&KI(n);return a==null?!1:(t&&t(s.tr.lift(n,a).scrollIntoView()),!0)},mHt=(s,t)=>{let{$from:r,to:n}=s.selection,a,i=r.sharedDepth(n);return i==0?!1:(a=r.before(i),t&&t(s.tr.setSelection(Xa.create(s.doc,a))),!0)};function fHt(s,t,r){let n=t.nodeBefore,a=t.nodeAfter,i=t.index();return!n||!a||!n.type.compatibleContent(a.type)?!1:!n.content.size&&t.parent.canReplace(i-1,i)?(r&&r(s.tr.delete(t.pos-n.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(a.isTextblock||r2(s.doc,t.pos))?!1:(r&&r(s.tr.join(t.pos).scrollIntoView()),!0)}function sit(s,t,r,n){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&fHt(s,t,r))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(r){let y=t.pos+i.nodeSize,v=dn.empty;for(let N=l.length-1;N>=0;N--)v=dn.from(l[N].create(null,v));v=dn.from(a.copy(v));let w=s.tr.step(new Nh(t.pos-1,y,t.pos,y,new Un(v,1,0),l.length,!0)),b=w.doc.resolve(y+2*l.length);b.nodeAfter&&b.nodeAfter.type==a.type&&r2(w.doc,b.pos)&&w.join(b.pos),r(w.scrollIntoView())}return!0}let h=i.type.spec.isolating||n>0&&c?null:pi.findFrom(t,1),m=h&&h.$from.blockRange(h.$to),x=m&&KI(m);if(x!=null&&x>=t.depth)return r&&r(s.tr.lift(m,x).scrollIntoView()),!0;if(d&&FM(i,"start",!0)&&FM(a,"end")){let y=a,v=[];for(;v.push(y),!y.isTextblock;)y=y.lastChild;let w=i,b=1;for(;!w.isTextblock;w=w.firstChild)b++;if(y.canReplace(y.childCount,y.childCount,w.content)){if(r){let N=dn.empty;for(let T=v.length-1;T>=0;T--)N=dn.from(v[T].copy(N));let S=s.tr.step(new Nh(t.pos-v.length,t.pos+i.nodeSize,t.pos+b,t.pos+i.nodeSize-b,new Un(N,v.length,0),0,!0));r(S.scrollIntoView())}return!0}}return!1}function rit(s){return function(t,r){let n=t.selection,a=s<0?n.$from:n.$to,i=a.depth;for(;a.node(i).isInline;){if(!i)return!1;i--}return a.node(i).isTextblock?(r&&r(t.tr.setSelection(oi.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const pHt=rit(-1),xHt=rit(1);function gHt(s,t=null){return function(r,n){let{$from:a,$to:i}=r.selection,l=a.blockRange(i),o=l&&m3e(l,s,t);return o?(n&&n(r.tr.wrap(l,o).scrollIntoView()),!0):!1}}function FFe(s,t=null){return function(r,n){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 h=r.doc.resolve(d),m=h.index();a=h.parent.canReplaceWith(m,m+1,s)}})}if(!a)return!1;if(n){let i=r.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(r)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new Xde(c,c,t.depth),t.endIndex=0;h--)i=dn.from(r[h].type.create(r[h].attrs,i));s.step(new Nh(t.start-(n?2:0),t.end,t.start,t.end,new Un(i,0,0),r.length,!0));let l=0;for(let h=0;hl.childCount>0&&l.firstChild.type==s);return i?r?n.node(i.depth-1).type==s?wHt(t,r,s,i):jHt(t,r,i):!0:!1}}function wHt(s,t,r,n){let a=s.tr,i=n.end,l=n.$to.end(n.depth);iw;v--)y-=a.child(v).nodeSize,n.delete(y-1,y+1);let i=n.doc.resolve(r.start),l=i.nodeAfter;if(n.mapping.map(r.end)!=r.start+i.nodeAfter.nodeSize)return!1;let o=r.startIndex==0,c=r.endIndex==a.childCount,d=i.node(-1),h=i.index(-1);if(!d.canReplace(h+(o?0:1),h+1,l.content.append(c?dn.empty:dn.from(a))))return!1;let m=i.pos,x=m+l.nodeSize;return n.step(new Nh(m-(o?1:0),x+(c?1:0),m+1,x-1,new Un((o?dn.empty:dn.from(a.copy(dn.empty))).append(c?dn.empty:dn.from(a.copy(dn.empty))),o?0:1,c?0:1),o?0:1)),t(n.scrollIntoView()),!0}function NHt(s){return function(t,r){let{$from:n,$to:a}=t.selection,i=n.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(r){let d=c.lastChild&&c.lastChild.type==o.type,h=dn.from(d?s.create():null),m=new Un(dn.from(s.create(null,dn.from(o.type.create(null,h)))),d?3:1,0),x=i.start,y=i.end;r(t.tr.step(new Nh(x-(d?3:1),y,x,y,m,1,!0)).scrollIntoView())}return!0}}function epe(s){const{state:t,transaction:r}=s;let{selection:n}=r,{doc:a}=r,{storedMarks:i}=r;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 n},get doc(){return a},get tr(){return n=r.selection,a=r.doc,i=r.storedMarks,r}}}class tpe{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:r,state:n}=this,{view:a}=r,{tr:i}=n,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...h)=>{const m=c(...h)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),m}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,h=()=>(!c&&r&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(x=>x===!0)),m={...Object.fromEntries(Object.entries(n).map(([x,y])=>[x,(...w)=>{const b=this.buildProps(d,r),N=y(...w)(b);return o.push(N),m}])),run:h};return m}createCan(t){const{rawCommands:r,state:n}=this,a=!1,i=t||n.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...h)=>d(...h)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,r=!0){const{rawCommands:n,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:epe({state:i,transaction:t}),dispatch:r?()=>{}:void 0,chain:()=>this.createChain(t,r),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...h)=>d(...h)(o)]))}};return o}}let kHt=class{constructor(){this.callbacks={}}on(t,r){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(r),this}emit(t,...r){const n=this.callbacks[t];return n&&n.forEach(a=>a.apply(this,r)),this}off(t,r){const n=this.callbacks[t];return n&&(r?this.callbacks[t]=n.filter(a=>a!==r):delete this.callbacks[t]),this}once(t,r){const n=(...a)=>{this.off(t,n),r.apply(this,a)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}};function ja(s,t,r){return s.config[t]===void 0&&s.parent?ja(s.parent,t,r):typeof s.config[t]=="function"?s.config[t].bind({...r,parent:s.parent?ja(s.parent,t,r):null}):s.config[t]}function spe(s){const t=s.filter(a=>a.type==="extension"),r=s.filter(a=>a.type==="node"),n=s.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:r,markExtensions:n}}function nit(s){const t=[],{nodeExtensions:r,markExtensions:n}=spe(s),a=[...r,...n],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=ja(l,"addGlobalAttributes",o);if(!c)return;c().forEach(h=>{h.types.forEach(m=>{Object.entries(h.attributes).forEach(([x,y])=>{t.push({type:m,name:x,attribute:{...i,...y}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=ja(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([h,m])=>{const x={...i,...m};typeof(x==null?void 0:x.default)=="function"&&(x.default=x.default()),x!=null&&x.isRequired&&(x==null?void 0:x.default)===void 0&&delete x.default,t.push({type:l.name,name:h,attribute:x})})}),t}function Ch(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 Wc(...s){return s.filter(t=>!!t).reduce((t,r)=>{const n={...t};return Object.entries(r).forEach(([a,i])=>{if(!n[a]){n[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=n[a]?n[a].split(" "):[],d=o.filter(h=>!c.includes(h));n[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(h=>h.trim()).filter(Boolean):[],c=n[a]?n[a].split(";").map(h=>h.trim()).filter(Boolean):[],d=new Map;c.forEach(h=>{const[m,x]=h.split(":").map(y=>y.trim());d.set(m,x)}),o.forEach(h=>{const[m,x]=h.split(":").map(y=>y.trim());d.set(m,x)}),n[a]=Array.from(d.entries()).map(([h,m])=>`${h}: ${m}`).join("; ")}else n[a]=i}),n},{})}function o2e(s,t){return t.filter(r=>r.type===s.type.name).filter(r=>r.attribute.rendered).map(r=>r.attribute.renderHTML?r.attribute.renderHTML(s.attrs)||{}:{[r.name]:s.attrs[r.name]}).reduce((r,n)=>Wc(r,n),{})}function ait(s){return typeof s=="function"}function Qi(s,t=void 0,...r){return ait(s)?t?s.bind(t)(...r):s(...r):s}function SHt(s={}){return Object.keys(s).length===0&&s.constructor===Object}function CHt(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function BFe(s,t){return"style"in s?s:{...s,getAttrs:r=>{const n=s.getAttrs?s.getAttrs(r):s.attrs;if(n===!1)return!1;const a=t.reduce((i,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(r):CHt(r.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...n,...a}}}}function zFe(s){return Object.fromEntries(Object.entries(s).filter(([t,r])=>t==="attrs"&&SHt(r)?!1:r!=null))}function THt(s,t){var r;const n=nit(s),{nodeExtensions:a,markExtensions:i}=spe(s),l=(r=a.find(d=>ja(d,"topNode")))===null||r===void 0?void 0:r.name,o=Object.fromEntries(a.map(d=>{const h=n.filter(N=>N.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},x=s.reduce((N,S)=>{const T=ja(S,"extendNodeSchema",m);return{...N,...T?T(d):{}}},{}),y=zFe({...x,content:Qi(ja(d,"content",m)),marks:Qi(ja(d,"marks",m)),group:Qi(ja(d,"group",m)),inline:Qi(ja(d,"inline",m)),atom:Qi(ja(d,"atom",m)),selectable:Qi(ja(d,"selectable",m)),draggable:Qi(ja(d,"draggable",m)),code:Qi(ja(d,"code",m)),whitespace:Qi(ja(d,"whitespace",m)),linebreakReplacement:Qi(ja(d,"linebreakReplacement",m)),defining:Qi(ja(d,"defining",m)),isolating:Qi(ja(d,"isolating",m)),attrs:Object.fromEntries(h.map(N=>{var S;return[N.name,{default:(S=N==null?void 0:N.attribute)===null||S===void 0?void 0:S.default}]}))}),v=Qi(ja(d,"parseHTML",m));v&&(y.parseDOM=v.map(N=>BFe(N,h)));const w=ja(d,"renderHTML",m);w&&(y.toDOM=N=>w({node:N,HTMLAttributes:o2e(N,h)}));const b=ja(d,"renderText",m);return b&&(y.toText=b),[d.name,y]})),c=Object.fromEntries(i.map(d=>{const h=n.filter(b=>b.type===d.name),m={name:d.name,options:d.options,storage:d.storage,editor:t},x=s.reduce((b,N)=>{const S=ja(N,"extendMarkSchema",m);return{...b,...S?S(d):{}}},{}),y=zFe({...x,inclusive:Qi(ja(d,"inclusive",m)),excludes:Qi(ja(d,"excludes",m)),group:Qi(ja(d,"group",m)),spanning:Qi(ja(d,"spanning",m)),code:Qi(ja(d,"code",m)),attrs:Object.fromEntries(h.map(b=>{var N;return[b.name,{default:(N=b==null?void 0:b.attribute)===null||N===void 0?void 0:N.default}]}))}),v=Qi(ja(d,"parseHTML",m));v&&(y.parseDOM=v.map(b=>BFe(b,h)));const w=ja(d,"renderHTML",m);return w&&(y.toDOM=b=>w({mark:b,HTMLAttributes:o2e(b,h)})),[d.name,y]}));return new Qnt({topNode:l,nodes:o,marks:c})}function o1e(s,t){return t.nodes[s]||t.marks[s]||null}function $Fe(s,t){return Array.isArray(t)?t.some(r=>(typeof r=="string"?r:r.name)===s.name):t}function T3e(s,t){const r=o5.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(r),a.innerHTML}const EHt=(s,t=500)=>{let r="";const n=s.parentOffset;return s.parent.nodesBetween(Math.max(0,n-t),n,(a,i,l,o)=>{var c,d;const h=((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%";r+=a.isAtom&&!a.isText?h:h.slice(0,Math.max(0,n-i))}),r};function E3e(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class rpe{constructor(t){this.find=t.find,this.handler=t.handler}}const AHt=(s,t)=>{if(E3e(t))return t.exec(s);const r=t(s);if(!r)return null;const n=[r.text];return n.index=r.index,n.input=s,n.data=r.data,r.replaceWith&&(r.text.includes(r.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),n.push(r.replaceWith)),n};function e$(s){var t;const{editor:r,from:n,to:a,text:i,rules:l,plugin:o}=s,{view:c}=r;if(c.composing)return!1;const d=c.state.doc.resolve(n);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(x=>x.type.spec.code))return!1;let h=!1;const m=EHt(d)+i;return l.forEach(x=>{if(h)return;const y=AHt(m,x.find);if(!y)return;const v=c.state.tr,w=epe({state:c.state,transaction:v}),b={from:n-(y[0].length-i.length),to:a},{commands:N,chain:S,can:T}=new tpe({editor:r,state:w});x.handler({state:w,range:b,match:y,commands:N,chain:S,can:T})===null||!v.steps.length||(v.setMeta(o,{transform:v,from:n,to:a,text:i}),c.dispatch(v),h=!0)}),h}function MHt(s){const{editor:t,rules:r}=s,n=new Ju({state:{init(){return null},apply(a,i,l){const o=a.getMeta(n);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:h}=c;typeof h=="string"?h=h:h=T3e(dn.from(h),l.schema);const{from:m}=c,x=m+h.length;e$({editor:t,from:m,to:x,text:h,rules:r,plugin:n})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return e$({editor:t,from:i,to:l,text:o,rules:r,plugin:n})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&e$({editor:t,from:i.pos,to:i.pos,text:"",rules:r,plugin:n})}),!1)},handleKeyDown(a,i){if(i.key!=="Enter")return!1;const{$cursor:l}=a.state.selection;return l?e$({editor:t,from:l.pos,to:l.pos,text:` `,rules:r,plugin:n}):!1}},isInputRules:!0});return n}function IHt(s){return Object.prototype.toString.call(s).slice(8,-1)}function t$(s){return IHt(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function npe(s,t){const r={...s};return t$(s)&&t$(t)&&Object.keys(t).forEach(n=>{t$(t[n])&&t$(s[n])?r[n]=npe(s[n],t[n]):r[n]=t[n]}),r}class Oy{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=Qi(ja(this,"addOptions",{name:this.name}))),this.storage=Qi(ja(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Oy(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>npe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new Oy(t);return r.parent=this,this.child=r,r.name=t.name?t.name:r.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: "${r.name}".`),r.options=Qi(ja(r,"addOptions",{name:r.name})),r.storage=Qi(ja(r,"addStorage",{name:r.name,options:r.options})),r}static handleExit({editor:t,mark:r}){const{tr:n}=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)===r.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===r.name);return c&&n.removeStoredMark(c),n.insertText(" ",a.pos),t.view.dispatch(n),!0}return!1}}function LHt(s){return typeof s=="number"}class PHt{constructor(t){this.find=t.find,this.handler=t.handler}}const DHt=(s,t,r)=>{if(E3e(t))return[...s.matchAll(t)];const n=t(s,r);return n?n.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 RHt(s){const{editor:t,state:r,from:n,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:h}=new tpe({editor:t,state:r}),m=[];return r.doc.nodesBetween(n,a,(y,v)=>{if(!y.isTextblock||y.type.spec.code)return;const w=Math.max(n,v),b=Math.min(a,v+y.content.size),N=y.textBetween(w-v,b-v,void 0,"");DHt(N,i.find,l).forEach(T=>{if(T.index===void 0)return;const A=w+T.index+1,I=A+T[0].length,D={from:r.tr.mapping.map(A),to:r.tr.mapping.map(I)},R=i.handler({state:r,range:D,match:T,commands:c,chain:d,can:h,pasteEvent:l,dropEvent:o});m.push(R)})}),m.every(y=>y!==null)}let s$=null;const OHt=s=>{var t;const r=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=r.clipboardData)===null||t===void 0||t.setData("text/html",s),r};function FHt(s){const{editor:t,rules:r}=s;let n=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:h,from:m,to:x,rule:y,pasteEvt:v})=>{const w=h.tr,b=epe({state:h,transaction:w});if(!(!RHt({editor:t,state:b,from:Math.max(m-1,0),to:x.b-1,rule:y,pasteEvent:v,dropEvent:o})||!w.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,w}};return r.map(h=>new Ju({view(m){const x=v=>{var w;n=!((w=m.dom.parentElement)===null||w===void 0)&&w.contains(v.target)?m.dom.parentElement:null,n&&(s$=t)},y=()=>{s$&&(s$=null)};return window.addEventListener("dragstart",x),window.addEventListener("dragend",y),{destroy(){window.removeEventListener("dragstart",x),window.removeEventListener("dragend",y)}}},props:{handleDOMEvents:{drop:(m,x)=>{if(i=n===m.dom.parentElement,o=x,!i){const y=s$;y!=null&&y.isEditable&&setTimeout(()=>{const v=y.state.selection;v&&y.commands.deleteRange({from:v.from,to:v.to})},10)}return!1},paste:(m,x)=>{var y;const v=(y=x.clipboardData)===null||y===void 0?void 0:y.getData("text/html");return l=x,a=!!(v!=null&&v.includes("data-pm-slice")),!1}}},appendTransaction:(m,x,y)=>{const v=m[0],w=v.getMeta("uiEvent")==="paste"&&!a,b=v.getMeta("uiEvent")==="drop"&&!i,N=v.getMeta("applyPasteRules"),S=!!N;if(!w&&!b&&!S)return;if(S){let{text:I}=N;typeof I=="string"?I=I:I=T3e(dn.from(I),y.schema);const{from:D}=N,R=D+I.length,$=OHt(I);return c({rule:h,state:y,from:D,to:{b:R},pasteEvt:$})}const T=x.doc.content.findDiffStart(y.doc.content),A=x.doc.content.findDiffEnd(y.doc.content);if(!(!LHt(T)||!A||T===A.b))return c({rule:h,state:y,from:T,to:A,pasteEvt:l})}}))}function BHt(s){const t=s.filter((r,n)=>s.indexOf(r)!==n);return Array.from(new Set(t))}class GE{constructor(t,r){this.splittableMarks=[],this.editor=r,this.extensions=GE.resolve(t),this.schema=THt(this.extensions,r),this.setupExtensions()}static resolve(t){const r=GE.sort(GE.flatten(t)),n=BHt(r.map(a=>a.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),r}static flatten(t){return t.map(r=>{const n={name:r.name,options:r.options,storage:r.storage},a=ja(r,"addExtensions",n);return a?[r,...this.flatten(a())]:r}).flat(10)}static sort(t){return t.sort((n,a)=>{const i=ja(n,"priority")||100,l=ja(a,"priority")||100;return i>l?-1:i{const n={name:r.name,options:r.options,storage:r.storage,editor:this.editor,type:o1e(r.name,this.schema)},a=ja(r,"addCommands",n);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,r=GE.sort([...this.extensions].reverse()),n=[],a=[],i=r.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:o1e(l.name,this.schema)},c=[],d=ja(l,"addKeyboardShortcuts",o);let h={};if(l.type==="mark"&&ja(l,"exitable",o)&&(h.ArrowRight=()=>Oy.handleExit({editor:t,mark:l})),d){const w=Object.fromEntries(Object.entries(d()).map(([b,N])=>[b,()=>N({editor:t})]));h={...h,...w}}const m=QVt(h);c.push(m);const x=ja(l,"addInputRules",o);$Fe(l,t.options.enableInputRules)&&x&&n.push(...x());const y=ja(l,"addPasteRules",o);$Fe(l,t.options.enablePasteRules)&&y&&a.push(...y());const v=ja(l,"addProseMirrorPlugins",o);if(v){const w=v();c.push(...w)}return c}).flat();return[MHt({editor:t,rules:n}),...FHt({editor:t,rules:a}),...i]}get attributes(){return nit(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:r}=spe(this.extensions);return Object.fromEntries(r.filter(n=>!!ja(n,"addNodeView")).map(n=>{const a=this.attributes.filter(c=>c.type===n.name),i={name:n.name,options:n.options,storage:n.storage,editor:t,type:Ch(n.name,this.schema)},l=ja(n,"addNodeView",i);if(!l)return[];const o=(c,d,h,m,x)=>{const y=o2e(c,a);return l()({node:c,view:d,getPos:h,decorations:m,innerDecorations:x,editor:t,extension:n,HTMLAttributes:y})};return[n.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var r;this.editor.extensionStorage[t.name]=t.storage;const n={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:o1e(t.name,this.schema)};t.type==="mark"&&(!((r=Qi(ja(t,"keepOnSplit",n)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(t.name);const a=ja(t,"onBeforeCreate",n),i=ja(t,"onCreate",n),l=ja(t,"onUpdate",n),o=ja(t,"onSelectionUpdate",n),c=ja(t,"onTransaction",n),d=ja(t,"onFocus",n),h=ja(t,"onBlur",n),m=ja(t,"onDestroy",n);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),h&&this.editor.on("blur",h),m&&this.editor.on("destroy",m)})}}class nm{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=Qi(ja(this,"addOptions",{name:this.name}))),this.storage=Qi(ja(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new nm(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>npe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new nm({...this.config,...t});return r.parent=this,this.child=r,r.name=t.name?t.name:r.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: "${r.name}".`),r.options=Qi(ja(r,"addOptions",{name:r.name})),r.storage=Qi(ja(r,"addStorage",{name:r.name,options:r.options})),r}}function iit(s,t,r){const{from:n,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=r||{};let o="";return s.nodesBetween(n,a,(c,d,h,m)=>{var x;c.isBlock&&d>n&&(o+=i);const y=l==null?void 0:l[c.type.name];if(y)return h&&(o+=y({node:c,pos:d,parent:h,index:m,range:t})),!1;c.isText&&(o+=(x=c==null?void 0:c.text)===null||x===void 0?void 0:x.slice(Math.max(n,d)-d,a-d))}),o}function oit(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,r])=>[t,r.spec.toText]))}const zHt=nm.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Ju({key:new Tm("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:r}=s,{doc:n,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(h=>h.$from.pos)),o=Math.max(...i.map(h=>h.$to.pos)),c=oit(r);return iit(n,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),$Ht=()=>({editor:s,view:t})=>(requestAnimationFrame(()=>{var r;s.isDestroyed||(t.dom.blur(),(r=window==null?void 0:window.getSelection())===null||r===void 0||r.removeAllRanges())}),!0),UHt=(s=!1)=>({commands:t})=>t.setContent("",s),qHt=()=>({state:s,tr:t,dispatch:r})=>{const{selection:n}=t,{ranges:a}=n;return r&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:h}=t,m=d.resolve(h.map(c)),x=d.resolve(h.map(c+o.nodeSize)),y=m.blockRange(x);if(!y)return;const v=KI(y);if(o.type.isTextblock){const{defaultType:w}=m.parent.contentMatchAt(m.index());t.setNodeMarkup(y.start,w)}(v||v===0)&&t.lift(y,v)})}),!0},VHt=s=>t=>s(t),HHt=()=>({state:s,dispatch:t})=>uHt(s,t),GHt=(s,t)=>({editor:r,tr:n})=>{const{state:a}=r,i=a.doc.slice(s.from,s.to);n.deleteRange(s.from,s.to);const l=n.mapping.map(t);return n.insert(l,i.content),n.setSelection(new oi(n.doc.resolve(Math.max(l-1,0)))),!0},WHt=()=>({tr:s,dispatch:t})=>{const{selection:r}=s,n=r.$anchor.node();if(n.content.size>0)return!1;const a=s.selection.$anchor;for(let i=a.depth;i>0;i-=1)if(a.node(i).type===n.type){if(t){const o=a.before(i),c=a.after(i);s.delete(o,c).scrollIntoView()}return!0}return!1},KHt=s=>({tr:t,state:r,dispatch:n})=>{const a=Ch(s,r.schema),i=t.selection.$anchor;for(let l=i.depth;l>0;l-=1)if(i.node(l).type===a){if(n){const c=i.before(l),d=i.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},YHt=s=>({tr:t,dispatch:r})=>{const{from:n,to:a}=s;return r&&t.delete(n,a),!0},ZHt=()=>({state:s,dispatch:t})=>JVt(s,t),XHt=()=>({commands:s})=>s.keyboardShortcut("Enter"),QHt=()=>({state:s,dispatch:t})=>dHt(s,t);function aue(s,t,r={strict:!0}){const n=Object.keys(t);return n.length?n.every(a=>r.strict?t[a]===s[a]:E3e(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function lit(s,t,r={}){return s.find(n=>n.type===t&&aue(Object.fromEntries(Object.keys(r).map(a=>[a,n.attrs[a]])),r))}function UFe(s,t,r={}){return!!lit(s,t,r)}function A3e(s,t,r){var n;if(!s||!t)return;let a=s.parent.childAfter(s.parentOffset);if((!a.node||!a.node.marks.some(h=>h.type===t))&&(a=s.parent.childBefore(s.parentOffset)),!a.node||!a.node.marks.some(h=>h.type===t)||(r=r||((n=a.node.marks[0])===null||n===void 0?void 0:n.attrs),!lit([...a.node.marks],t,r)))return;let l=a.index,o=s.start()+a.offset,c=l+1,d=o+a.node.nodeSize;for(;l>0&&UFe([...s.parent.child(l-1).marks],t,r);)l-=1,o-=s.parent.child(l).nodeSize;for(;c({tr:r,state:n,dispatch:a})=>{const i=a2(s,n.schema),{doc:l,selection:o}=r,{$from:c,from:d,to:h}=o;if(a){const m=A3e(c,i,t);if(m&&m.from<=d&&m.to>=h){const x=oi.create(l,m.from,m.to);r.setSelection(x)}}return!0},eGt=s=>t=>{const r=typeof s=="function"?s(t):s;for(let n=0;n({editor:r,view:n,tr:a,dispatch:i})=>{t={scrollIntoView:!0,...t};const l=()=>{(iue()||qFe())&&n.dom.focus(),requestAnimationFrame(()=>{r.isDestroyed||(n.focus(),tGt()&&!iue()&&!qFe()&&n.dom.focus({preventScroll:!0}))})};if(n.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!cit(r.state.selection))return l(),!0;const o=dit(a.doc,s)||r.state.selection,c=r.state.selection.eq(o);return i&&(c||a.setSelection(o),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},rGt=(s,t)=>r=>s.every((n,a)=>t(n,{...r,index:a})),nGt=(s,t)=>({tr:r,commands:n})=>n.insertContentAt({from:r.selection.from,to:r.selection.to},s,t),uit=s=>{const t=s.childNodes;for(let r=t.length-1;r>=0;r-=1){const n=t[r];n.nodeType===3&&n.nodeValue&&/^(\n\s\s|\n)$/.test(n.nodeValue)?s.removeChild(n):n.nodeType===1&&uit(n)}return s};function r$(s){const t=`${s}`,r=new window.DOMParser().parseFromString(t,"text/html").body;return uit(r)}function E8(s,t,r){if(s instanceof pj||s instanceof dn)return s;r={slice:!0,parseOptions:{},...r};const n=typeof s=="object"&&s!==null,a=typeof s=="string";if(n)try{if(Array.isArray(s)&&s.length>0)return dn.fromArray(s.map(o=>t.nodeFromJSON(o)));const l=t.nodeFromJSON(s);return r.errorOnInvalidContent&&l.check(),l}catch(i){if(r.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",i),E8("",t,r)}if(a){if(r.errorOnInvalidContent){let l=!1,o="";const c=new Qnt({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(r.slice?mO.fromSchema(c).parseSlice(r$(s),r.parseOptions):mO.fromSchema(c).parse(r$(s),r.parseOptions),r.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=mO.fromSchema(t);return r.slice?i.parseSlice(r$(s),r.parseOptions).content:i.parse(r$(s),r.parseOptions)}return E8("",t,r)}function aGt(s,t,r){const n=s.steps.length-1;if(n{l===0&&(l=h)}),s.setSelection(pi.near(s.doc.resolve(l),r))}const iGt=s=>!("type"in s),oGt=(s,t,r)=>({tr:n,dispatch:a,editor:i})=>{var l;if(a){r={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...r};let o;const c=b=>{i.emit("contentError",{editor:i,error:b,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...r.parseOptions};if(!r.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{E8(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(b){c(b)}try{o=E8(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=r.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(b){return c(b),!1}let{from:h,to:m}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},x=!0,y=!0;if((iGt(o)?o:[o]).forEach(b=>{b.check(),x=x?b.isText&&b.marks.length===0:!1,y=y?b.isBlock:!1}),h===m&&y){const{parent:b}=n.doc.resolve(h);b.isTextblock&&!b.type.spec.code&&!b.childCount&&(h-=1,m+=1)}let w;if(x){if(Array.isArray(t))w=t.map(b=>b.text||"").join("");else if(t instanceof dn){let b="";t.forEach(N=>{N.text&&(b+=N.text)}),w=b}else typeof t=="object"&&t&&t.text?w=t.text:w=t;n.insertText(w,h,m)}else w=o,n.replaceWith(h,m,w);r.updateSelection&&aGt(n,n.steps.length-1,-1),r.applyInputRules&&n.setMeta("applyInputRules",{from:h,text:w}),r.applyPasteRules&&n.setMeta("applyPasteRules",{from:h,text:w})}return!0},lGt=()=>({state:s,dispatch:t})=>iHt(s,t),cGt=()=>({state:s,dispatch:t})=>oHt(s,t),dGt=()=>({state:s,dispatch:t})=>eHt(s,t),uGt=()=>({state:s,dispatch:t})=>nHt(s,t),hGt=()=>({state:s,dispatch:t,tr:r})=>{try{const n=Kfe(s.doc,s.selection.$from.pos,-1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},mGt=()=>({state:s,dispatch:t,tr:r})=>{try{const n=Kfe(s.doc,s.selection.$from.pos,1);return n==null?!1:(r.join(n,2),t&&t(r),!0)}catch{return!1}},fGt=()=>({state:s,dispatch:t})=>tHt(s,t),pGt=()=>({state:s,dispatch:t})=>sHt(s,t);function hit(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function xGt(s){const t=s.split(/-(?!$)/);let r=t[t.length-1];r==="Space"&&(r=" ");let n,a,i,l;for(let o=0;o({editor:t,view:r,tr:n,dispatch:a})=>{const i=xGt(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(()=>{r.someProp("handleKeyDown",d=>d(r,o))});return c==null||c.steps.forEach(d=>{const h=d.map(n.mapping);h&&a&&n.maybeStep(h)}),!0};function A8(s,t,r={}){const{from:n,to:a,empty:i}=s.selection,l=t?Ch(t,s.schema):null,o=[];s.doc.nodesBetween(n,a,(m,x)=>{if(m.isText)return;const y=Math.max(n,x),v=Math.min(a,x+m.nodeSize);o.push({node:m,from:y,to:v})});const c=a-n,d=o.filter(m=>l?l.name===m.node.type.name:!0).filter(m=>aue(m.node.attrs,r,{strict:!1}));return i?!!d.length:d.reduce((m,x)=>m+x.to-x.from,0)>=c}const yGt=(s,t={})=>({state:r,dispatch:n})=>{const a=Ch(s,r.schema);return A8(r,a,t)?lHt(r,n):!1},vGt=()=>({state:s,dispatch:t})=>hHt(s,t),bGt=s=>({state:t,dispatch:r})=>{const n=Ch(s,t.schema);return _Ht(n)(t,r)},_Gt=()=>({state:s,dispatch:t})=>cHt(s,t);function ape(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function VFe(s,t){const r=typeof t=="string"?[t]:t;return Object.keys(s).reduce((n,a)=>(r.includes(a)||(n[a]=s[a]),n),{})}const wGt=(s,t)=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=ape(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=Ch(s,n.schema)),o==="mark"&&(l=a2(s,n.schema)),a&&r.selection.ranges.forEach(c=>{n.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,h)=>{i&&i===d.type&&r.setNodeMarkup(h,void 0,VFe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(m=>{l===m.type&&r.addMark(h,h+d.nodeSize,l.create(VFe(m.attrs,t)))})})}),!0):!1},jGt=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),NGt=()=>({tr:s,dispatch:t})=>{if(t){const r=new dg(s.doc);s.setSelection(r)}return!0},kGt=()=>({state:s,dispatch:t})=>rHt(s,t),SGt=()=>({state:s,dispatch:t})=>aHt(s,t),CGt=()=>({state:s,dispatch:t})=>mHt(s,t),TGt=()=>({state:s,dispatch:t})=>xHt(s,t),EGt=()=>({state:s,dispatch:t})=>pHt(s,t);function l2e(s,t,r={},n={}){return E8(s,t,{slice:!1,parseOptions:r,errorOnInvalidContent:n.errorOnInvalidContent})}const AGt=(s,t=!1,r={},n={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:h}=i;if(r.preserveWhitespace!=="full"){const m=l2e(s,a.schema,r,{errorOnInvalidContent:(c=n.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,h.content.size,m).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:h.content.size},s,{parseOptions:r,errorOnInvalidContent:(d=n.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function mit(s,t){const r=a2(t,s.schema),{from:n,to:a,empty:i}=s.selection,l=[];i?(s.storedMarks&&l.push(...s.storedMarks),l.push(...s.selection.$head.marks())):s.doc.nodesBetween(n,a,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===r.name);return o?{...o.attrs}:{}}function MGt(s,t){const r=new f3e(s);return t.forEach(n=>{n.steps.forEach(a=>{r.step(a)})}),r}function IGt(s){for(let t=0;t{r(a)&&n.push({node:a,pos:i})}),n}function fit(s,t){for(let r=s.depth;r>0;r-=1){const n=s.node(r);if(t(n))return{pos:r>0?s.before(r):0,start:s.start(r),depth:r,node:n}}}function M3e(s){return t=>fit(t.$from,s)}function PGt(s,t){const r={from:0,to:s.content.size};return iit(s,r,t)}function DGt(s,t){const r=Ch(t,s.schema),{from:n,to:a}=s.selection,i=[];s.doc.nodesBetween(n,a,o=>{i.push(o)});const l=i.reverse().find(o=>o.type.name===r.name);return l?{...l.attrs}:{}}function pit(s,t){const r=ape(typeof t=="string"?t:t.name,s.schema);return r==="node"?DGt(s,t):r==="mark"?mit(s,t):{}}function RGt(s,t=JSON.stringify){const r={};return s.filter(n=>{const a=t(n);return Object.prototype.hasOwnProperty.call(r,a)?!1:r[a]=!0})}function OGt(s){const t=RGt(s);return t.length===1?t:t.filter((r,n)=>!t.filter((i,l)=>l!==n).some(i=>r.oldRange.from>=i.oldRange.from&&r.oldRange.to<=i.oldRange.to&&r.newRange.from>=i.newRange.from&&r.newRange.to<=i.newRange.to))}function FGt(s){const{mapping:t,steps:r}=s,n=[];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}=r[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),h=t.slice(i).map(c),m=t.invert().map(d,-1),x=t.invert().map(h);n.push({oldRange:{from:m,to:x},newRange:{from:d,to:h}})})}),OGt(n)}function I3e(s,t,r){const n=[];return s===t?r.resolve(s).marks().forEach(a=>{const i=r.resolve(s),l=A3e(i,a.type);l&&n.push({mark:a,...l})}):r.nodesBetween(s,t,(a,i)=>{!a||(a==null?void 0:a.nodeSize)===void 0||n.push(...a.marks.map(l=>({from:i,to:i+a.nodeSize,mark:l})))}),n}function yce(s,t,r){return Object.fromEntries(Object.entries(r).filter(([n])=>{const a=s.find(i=>i.type===t&&i.name===n);return a?a.attribute.keepOnSplit:!1}))}function c2e(s,t,r={}){const{empty:n,ranges:a}=s.selection,i=t?a2(t,s.schema):null;if(n)return!!(s.storedMarks||s.selection.$from.marks()).filter(m=>i?i.name===m.type.name:!0).find(m=>aue(m.attrs,r,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:m,$to:x})=>{const y=m.pos,v=x.pos;s.doc.nodesBetween(y,v,(w,b)=>{if(!w.isText&&!w.marks.length)return;const N=Math.max(y,b),S=Math.min(v,b+w.nodeSize),T=S-N;l+=T,o.push(...w.marks.map(A=>({mark:A,from:N,to:S})))})}),l===0)return!1;const c=o.filter(m=>i?i.name===m.mark.type.name:!0).filter(m=>aue(m.mark.attrs,r,{strict:!1})).reduce((m,x)=>m+x.to-x.from,0),d=o.filter(m=>i?m.mark.type!==i&&m.mark.type.excludes(i):!0).reduce((m,x)=>m+x.to-x.from,0);return(c>0?c+d:c)>=l}function BGt(s,t,r={}){if(!t)return A8(s,null,r)||c2e(s,null,r);const n=ape(t,s.schema);return n==="node"?A8(s,t,r):n==="mark"?c2e(s,t,r):!1}function HFe(s,t){const{nodeExtensions:r}=spe(t),n=r.find(l=>l.name===s);if(!n)return!1;const a={name:n.name,options:n.options,storage:n.storage},i=Qi(ja(n,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function L3e(s,{checkChildren:t=!0,ignoreWhitespace:r=!1}={}){var n;if(r){if(s.type.name==="hardBreak")return!0;if(s.isText)return/^\s*$/m.test((n=s.text)!==null&&n!==void 0?n:"")}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&&(L3e(i,{ignoreWhitespace:r,checkChildren:t})||(a=!1))}),a}return!1}function zGt(s){return s instanceof Xa}function $Gt(s,t,r){var n;const{selection:a}=t;let i=null;if(cit(a)&&(i=a.$cursor),i){const o=(n=s.storedMarks)!==null&&n!==void 0?n:i.marks();return!!r.isInSet(o)||!o.some(c=>c.type.excludes(r))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(r):!1;return s.doc.nodesBetween(o.pos,c.pos,(h,m,x)=>{if(d)return!1;if(h.isInline){const y=!x||x.type.allowsMarkType(r),v=!!r.isInSet(h.marks)||!h.marks.some(w=>w.type.excludes(r));d=y&&v}return!d}),d})}const UGt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{const{selection:i}=r,{empty:l,ranges:o}=i,c=a2(s,n.schema);if(a)if(l){const d=mit(n,c);r.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const h=d.$from.pos,m=d.$to.pos;n.doc.nodesBetween(h,m,(x,y)=>{const v=Math.max(y,h),w=Math.min(y+x.nodeSize,m);x.marks.find(N=>N.type===c)?x.marks.forEach(N=>{c===N.type&&r.addMark(v,w,c.create({...N.attrs,...t}))}):r.addMark(v,w,c.create(t))})});return $Gt(n,r,c)},qGt=(s,t)=>({tr:r})=>(r.setMeta(s,t),!0),VGt=(s,t={})=>({state:r,dispatch:n,chain:a})=>{const i=Ch(s,r.schema);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),i.isTextblock?a().command(({commands:o})=>FFe(i,{...l,...t})(r)?!0:o.clearNodes()).command(({state:o})=>FFe(i,{...l,...t})(o,n)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},HGt=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,a=o4(s,0,n.content.size),i=Xa.create(n,a);t.setSelection(i)}return!0},GGt=s=>({tr:t,dispatch:r})=>{if(r){const{doc:n}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=oi.atStart(n).from,o=oi.atEnd(n).to,c=o4(a,l,o),d=o4(i,l,o),h=oi.create(n,c,d);t.setSelection(h)}return!0},WGt=s=>({state:t,dispatch:r})=>{const n=Ch(s,t.schema);return NHt(n)(t,r)};function GFe(s,t){const r=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(r){const n=r.filter(a=>t==null?void 0:t.includes(a.type.name));s.tr.ensureMarks(n)}}const KGt=({keepMarks:s=!0}={})=>({tr:t,state:r,dispatch:n,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,h=yce(d,o.node().type.name,o.node().attrs);if(i instanceof Xa&&i.node.isBlock)return!o.parentOffset||!BA(l,o.pos)?!1:(n&&(s&&GFe(r,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const m=c.parentOffset===c.parent.content.size,x=o.depth===0?void 0:IGt(o.node(-1).contentMatchAt(o.indexAfter(-1)));let y=m&&x?[{type:x,attrs:h}]:void 0,v=BA(t.doc,t.mapping.map(o.pos),1,y);if(!y&&!v&&BA(t.doc,t.mapping.map(o.pos),1,x?[{type:x}]:void 0)&&(v=!0,y=x?[{type:x,attrs:h}]:void 0),n){if(v&&(i instanceof oi&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,y),x&&!m&&!o.parentOffset&&o.parent.type!==x)){const w=t.mapping.map(o.before()),b=t.doc.resolve(w);o.node(-1).canReplaceWith(b.index(),b.index()+1,x)&&t.setNodeMarkup(t.mapping.map(o.before()),x)}s&&GFe(r,a.extensionManager.splittableMarks),t.scrollIntoView()}return v},YGt=(s,t={})=>({tr:r,state:n,dispatch:a,editor:i})=>{var l;const o=Ch(s,n.schema),{$from:c,$to:d}=n.selection,h=n.selection.node;if(h&&h.isBlock||c.depth<2||!c.sameParent(d))return!1;const m=c.node(-1);if(m.type!==o)return!1;const x=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 N=dn.empty;const S=c.index(-1)?1:c.index(-2)?2:3;for(let $=c.depth-S;$>=c.depth-3;$-=1)N=dn.from(c.node($).copy(N));const T=c.indexAfter(-1){if(R>-1)return!1;$.isTextblock&&$.content.size===0&&(R=F+1)}),R>-1&&r.setSelection(oi.near(r.doc.resolve(R))),r.scrollIntoView()}return!0}const y=d.pos===c.end()?m.contentMatchAt(0).defaultType:null,v={...yce(x,m.type.name,m.attrs),...t},w={...yce(x,c.node().type.name,c.node().attrs),...t};r.delete(c.pos,d.pos);const b=y?[{type:o,attrs:v},{type:y,attrs:w}]:[{type:o,attrs:v}];if(!BA(r.doc,c.pos,2))return!1;if(a){const{selection:N,storedMarks:S}=n,{splittableMarks:T}=i.extensionManager,A=S||N.$to.parentOffset&&N.$from.marks();if(r.split(c.pos,2,b).scrollIntoView(),!A||!a)return!0;const I=A.filter(D=>T.includes(D.type.name));r.ensureMarks(I)}return!0},l1e=(s,t)=>{const r=M3e(l=>l.type===t)(s.selection);if(!r)return!0;const n=s.doc.resolve(Math.max(0,r.pos-1)).before(r.depth);if(n===void 0)return!0;const a=s.doc.nodeAt(n);return r.node.type===(a==null?void 0:a.type)&&r2(s.doc,r.pos)&&s.join(r.pos),!0},c1e=(s,t)=>{const r=M3e(l=>l.type===t)(s.selection);if(!r)return!0;const n=s.doc.resolve(r.start).after(r.depth);if(n===void 0)return!0;const a=s.doc.nodeAt(n);return r.node.type===(a==null?void 0:a.type)&&r2(s.doc,n)&&s.join(n),!0},ZGt=(s,t,r,n={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:h})=>{const{extensions:m,splittableMarks:x}=a.extensionManager,y=Ch(s,l.schema),v=Ch(t,l.schema),{selection:w,storedMarks:b}=l,{$from:N,$to:S}=w,T=N.blockRange(S),A=b||w.$to.parentOffset&&w.$from.marks();if(!T)return!1;const I=M3e(D=>HFe(D.type.name,m))(w);if(T.depth>=1&&I&&T.depth-I.depth<=1){if(I.node.type===y)return d.liftListItem(v);if(HFe(I.node.type.name,m)&&y.validContent(I.node.content)&&o)return c().command(()=>(i.setNodeMarkup(I.pos,y),!0)).command(()=>l1e(i,y)).command(()=>c1e(i,y)).run()}return!r||!A||!o?c().command(()=>h().wrapInList(y,n)?!0:d.clearNodes()).wrapInList(y,n).command(()=>l1e(i,y)).command(()=>c1e(i,y)).run():c().command(()=>{const D=h().wrapInList(y,n),R=A.filter($=>x.includes($.type.name));return i.ensureMarks(R),D?!0:d.clearNodes()}).wrapInList(y,n).command(()=>l1e(i,y)).command(()=>c1e(i,y)).run()},XGt=(s,t={},r={})=>({state:n,commands:a})=>{const{extendEmptyMarkRange:i=!1}=r,l=a2(s,n.schema);return c2e(n,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},QGt=(s,t,r={})=>({state:n,commands:a})=>{const i=Ch(s,n.schema),l=Ch(t,n.schema),o=A8(n,i,r);let c;return n.selection.$anchor.sameParent(n.selection.$head)&&(c=n.selection.$anchor.parent.attrs),o?a.setNode(l,c):a.setNode(i,{...c,...r})},JGt=(s,t={})=>({state:r,commands:n})=>{const a=Ch(s,r.schema);return A8(r,a,t)?n.lift(a):n.wrapIn(a,t)},eWt=()=>({state:s,dispatch:t})=>{const r=s.plugins;for(let n=0;n=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},tWt=()=>({tr:s,dispatch:t})=>{const{selection:r}=s,{empty:n,ranges:a}=r;return n||t&&a.forEach(i=>{s.removeMark(i.$from.pos,i.$to.pos)}),!0},sWt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=r,c=a2(s,n.schema),{$from:d,empty:h,ranges:m}=o;if(!a)return!0;if(h&&l){let{from:x,to:y}=o;const v=(i=d.marks().find(b=>b.type===c))===null||i===void 0?void 0:i.attrs,w=A3e(d,c,v);w&&(x=w.from,y=w.to),r.removeMark(x,y,c)}else m.forEach(x=>{r.removeMark(x.$from.pos,x.$to.pos,c)});return r.removeStoredMark(c),!0},rWt=(s,t={})=>({tr:r,state:n,dispatch:a})=>{let i=null,l=null;const o=ape(typeof s=="string"?s:s.name,n.schema);return o?(o==="node"&&(i=Ch(s,n.schema)),o==="mark"&&(l=a2(s,n.schema)),a&&r.selection.ranges.forEach(c=>{const d=c.$from.pos,h=c.$to.pos;let m,x,y,v;r.selection.empty?n.doc.nodesBetween(d,h,(w,b)=>{i&&i===w.type&&(y=Math.max(b,d),v=Math.min(b+w.nodeSize,h),m=b,x=w)}):n.doc.nodesBetween(d,h,(w,b)=>{b=d&&b<=h&&(i&&i===w.type&&r.setNodeMarkup(b,void 0,{...w.attrs,...t}),l&&w.marks.length&&w.marks.forEach(N=>{if(l===N.type){const S=Math.max(b,d),T=Math.min(b+w.nodeSize,h);r.addMark(S,T,l.create({...N.attrs,...t}))}}))}),x&&(m!==void 0&&r.setNodeMarkup(m,void 0,{...x.attrs,...t}),l&&x.marks.length&&x.marks.forEach(w=>{l===w.type&&r.addMark(y,v,l.create({...w.attrs,...t}))}))}),!0):!1},nWt=(s,t={})=>({state:r,dispatch:n})=>{const a=Ch(s,r.schema);return gHt(a,t)(r,n)},aWt=(s,t={})=>({state:r,dispatch:n})=>{const a=Ch(s,r.schema);return yHt(a,t)(r,n)};var iWt=Object.freeze({__proto__:null,blur:$Ht,clearContent:UHt,clearNodes:qHt,command:VHt,createParagraphNear:HHt,cut:GHt,deleteCurrentNode:WHt,deleteNode:KHt,deleteRange:YHt,deleteSelection:ZHt,enter:XHt,exitCode:QHt,extendMarkRange:JHt,first:eGt,focus:sGt,forEach:rGt,insertContent:nGt,insertContentAt:oGt,joinBackward:dGt,joinDown:cGt,joinForward:uGt,joinItemBackward:hGt,joinItemForward:mGt,joinTextblockBackward:fGt,joinTextblockForward:pGt,joinUp:lGt,keyboardShortcut:gGt,lift:yGt,liftEmptyBlock:vGt,liftListItem:bGt,newlineInCode:_Gt,resetAttributes:wGt,scrollIntoView:jGt,selectAll:NGt,selectNodeBackward:kGt,selectNodeForward:SGt,selectParentNode:CGt,selectTextblockEnd:TGt,selectTextblockStart:EGt,setContent:AGt,setMark:UGt,setMeta:qGt,setNode:VGt,setNodeSelection:HGt,setTextSelection:GGt,sinkListItem:WGt,splitBlock:KGt,splitListItem:YGt,toggleList:ZGt,toggleMark:XGt,toggleNode:QGt,toggleWrap:JGt,undoInputRule:eWt,unsetAllMarks:tWt,unsetMark:sWt,updateAttributes:rWt,wrapIn:nWt,wrapInList:aWt});const oWt=nm.create({name:"commands",addCommands(){return{...iWt}}}),lWt=nm.create({name:"drop",addProseMirrorPlugins(){return[new Ju({key:new Tm("tiptapDrop"),props:{handleDrop:(s,t,r,n)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:r,moved:n})}}})]}}),cWt=nm.create({name:"editable",addProseMirrorPlugins(){return[new Ju({key:new Tm("editable"),props:{editable:()=>this.editor.options.editable}})]}}),dWt=new Tm("focusEvents"),uWt=nm.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Ju({key:dWt,props:{handleDOMEvents:{focus:(t,r)=>{s.isFocused=!0;const n=s.state.tr.setMeta("focus",{event:r}).setMeta("addToHistory",!1);return t.dispatch(n),!1},blur:(t,r)=>{s.isFocused=!1;const n=s.state.tr.setMeta("blur",{event:r}).setMeta("addToHistory",!1);return t.dispatch(n),!1}}}})]}}),hWt=nm.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:h,$anchor:m}=c,{pos:x,parent:y}=m,v=m.parent.isTextblock&&x>0?o.doc.resolve(x-1):m,w=v.parent.type.spec.isolating,b=m.pos-m.parentOffset,N=w&&v.parent.childCount===1?b===m.pos:pi.atStart(d).from===x;return!h||!y.type.isTextblock||y.textContent.length||!N||N&&m.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()]),n={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={...n},i={...n,"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 iue()||hit()?i:a},addProseMirrorPlugins(){return[new Ju({key:new Tm("clearDocument"),appendTransaction:(s,t,r)=>{if(s.some(w=>w.getMeta("composition")))return;const n=s.some(w=>w.docChanged)&&!t.doc.eq(r.doc),a=s.some(w=>w.getMeta("preventClearDocument"));if(!n||a)return;const{empty:i,from:l,to:o}=t.selection,c=pi.atStart(t.doc).from,d=pi.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!L3e(r.doc))return;const x=r.tr,y=epe({state:r,transaction:x}),{commands:v}=new tpe({editor:this.editor,state:y});if(v.clearNodes(),!!x.steps.length)return x}})]}}),mWt=nm.create({name:"paste",addProseMirrorPlugins(){return[new Ju({key:new Tm("tiptapPaste"),props:{handlePaste:(s,t,r)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:r})}}})]}}),fWt=nm.create({name:"tabindex",addProseMirrorPlugins(){return[new Ju({key:new Tm("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class YC{get name(){return this.node.type.name}constructor(t,r,n=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=n,this.resolvedPos=t,this.editor=r,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 r=this.from,n=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}r=this.from+1,n=this.to-1}this.editor.commands.insertContentAt({from:r,to:n},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),r=this.resolvedPos.doc.resolve(t);return new YC(r,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 YC(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 YC(t,this.editor)}get children(){const t=[];return this.node.content.forEach((r,n)=>{const a=r.isBlock&&!r.isTextblock,i=r.isAtom&&!r.isText,l=this.pos+n+(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 YC(o,this.editor,a,a?r:null);a&&(c.actualDepth=this.depth+1),t.push(new YC(o,this.editor,a,a?r:null))}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,r={}){let n=null,a=this.parent;for(;a&&!n;){if(a.node.type.name===t)if(Object.keys(r).length>0){const i=a.node.attrs,l=Object.keys(r);for(let o=0;o{n&&a.length>0||(l.node.type.name===t&&i.every(c=>r[c]===l.node.attrs[c])&&a.push(l),!(n&&a.length>0)&&(a=a.concat(l.querySelectorAll(t,r,n))))}),a}setAttribute(t){const{tr:r}=this.editor.state;r.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(r)}}const pWt=`.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 xWt(s,t,r){const n=document.querySelector("style[data-tiptap-style]");if(n!==null)return n;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 gWt extends kHt{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:r})=>{throw r},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:r,slice:n,moved:a})=>this.options.onDrop(r,n,a)),this.on("paste",({event:r,slice:n})=>this.options.onPaste(r,n)),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=xWt(pWt,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,r=!0){this.setOptions({editable:t}),r&&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,r){const n=ait(r)?r(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}unregisterPlugin(t){if(this.isDestroyed)return;const r=this.state.plugins;let n=r;if([].concat(t).forEach(i=>{const l=typeof i=="string"?`${i}$`:i.key;n=n.filter(o=>!o.key.startsWith(l))}),r.length===n.length)return;const a=this.state.reconfigure({plugins:n});return this.view.updateState(a),a}createExtensionManager(){var t,r;const a=[...this.options.enableCoreExtensions?[cWt,zHt.configure({blockSeparator:(r=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||r===void 0?void 0:r.blockSeparator}),oWt,uWt,hWt,fWt,lWt,mWt].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 GE(a,this)}createCommandManager(){this.commandManager=new tpe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let r;try{r=l2e(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()}}),r=l2e(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const n=dit(r,this.options.autofocus);this.view=new Xat(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:HE.create({doc:r,selection:n||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 r=this.capturedTransaction;return this.capturedTransaction=null,r}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 r=this.state.apply(t),n=!this.state.selection.eq(r.selection);this.emit("beforeTransaction",{editor:this,transaction:t,nextState:r}),this.view.updateState(r),this.emit("transaction",{editor:this,transaction:t}),n&&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 pit(this.state,t)}isActive(t,r){const n=typeof t=="string"?t:null,a=typeof t=="string"?r:t;return BGt(this.state,n,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return T3e(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:r=` `,textSerializers:n={}}=t||{};return PGt(this.state.doc,{blockSeparator:r,textSerializers:{...oit(this.schema),...n}})}get isEmpty(){return L3e(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,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelector(t,r))||null}$nodes(t,r){var n;return((n=this.$doc)===null||n===void 0?void 0:n.querySelectorAll(t,r))||null}$pos(t){const r=this.state.doc.resolve(t);return new YC(r,this)}get $doc(){return this.$pos(0)}}function BM(s){return new rpe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=Qi(s.getAttributes,void 0,n);if(a===!1||a===null)return null;const{tr:i}=t,l=n[n.length-1],o=n[0];if(l){const c=o.search(/\S/),d=r.from+o.indexOf(l),h=d+l.length;if(I3e(r.from,r.to,t.doc).filter(y=>y.mark.type.excluded.find(w=>w===s.type&&w!==y.mark.type)).filter(y=>y.to>d).length)return null;hr.from&&i.delete(r.from+c,d);const x=r.from+c+l.length;i.addMark(r.from+c,x,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function xit(s){return new rpe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=Qi(s.getAttributes,void 0,n)||{},{tr:i}=t,l=r.from;let o=r.to;const c=s.type.create(a);if(n[1]){const d=n[0].lastIndexOf(n[1]);let h=l+d;h>o?h=o:o=h+n[1].length;const m=n[0][n[0].length-1];i.insertText(m,l+n[0].length-1),i.replaceWith(h,o,c)}else if(n[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 d2e(s){return new rpe({find:s.find,handler:({state:t,range:r,match:n})=>{const a=t.doc.resolve(r.from),i=Qi(s.getAttributes,void 0,n)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),s.type))return null;t.tr.delete(r.from,r.to).setBlockType(r.from,r.from,s.type,i)}})}function M8(s){return new rpe({find:s.find,handler:({state:t,range:r,match:n,chain:a})=>{const i=Qi(s.getAttributes,void 0,n)||{},l=t.tr.delete(r.from,r.to),c=l.doc.resolve(r.from).blockRange(),d=c&&m3e(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:m,storedMarks:x}=t,{splittableMarks:y}=s.editor.extensionManager,v=x||m.$to.parentOffset&&m.$from.marks();if(v){const w=v.filter(b=>y.includes(b.type.name));l.ensureMarks(w)}}if(s.keepAttributes){const m=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(m,i).run()}const h=l.doc.resolve(r.from-1).nodeBefore;h&&h.type===s.type&&r2(l.doc,r.from-1)&&(!s.joinPredicate||s.joinPredicate(n,h))&&l.join(r.from-1)}})}let Em=class u2e{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=Qi(ja(this,"addOptions",{name:this.name}))),this.storage=Qi(ja(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new u2e(t)}configure(t={}){const r=this.extend({...this.config,addOptions:()=>npe(this.options,t)});return r.name=this.name,r.parent=this.parent,r}extend(t={}){const r=new u2e(t);return r.parent=this,this.child=r,r.name=t.name?t.name:r.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: "${r.name}".`),r.options=Qi(ja(r,"addOptions",{name:r.name})),r.storage=Qi(ja(r,"addStorage",{name:r.name,options:r.options})),r}};function B3(s){return new PHt({find:s.find,handler:({state:t,range:r,match:n,pasteEvent:a})=>{const i=Qi(s.getAttributes,void 0,n,a);if(i===!1||i===null)return null;const{tr:l}=t,o=n[n.length-1],c=n[0];let d=r.to;if(o){const h=c.search(/\S/),m=r.from+c.indexOf(o),x=m+o.length;if(I3e(r.from,r.to,t.doc).filter(v=>v.mark.type.excluded.find(b=>b===s.type&&b!==v.mark.type)).filter(v=>v.to>m).length)return null;xr.from&&l.delete(r.from+h,m),d=r.from+h+o.length,l.addMark(r.from+h,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function yWt(s,t){const{selection:r}=s,{$from:n}=r;if(r instanceof Xa){const i=n.index();return n.parent.canReplaceWith(i,i+1,t)}let a=n.depth;for(;a>=0;){const i=n.index(a);if(n.node(a).contentMatchAt(i).matchType(t))return!0;a-=1}return!1}function vWt(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var git={exports:{}},d1e={};/** * @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 WFe;function bWt(){if(WFe)return d1e;WFe=1;var s=wt;function t(m,x){return m===x&&(m!==0||1/m===1/x)||m!==m&&x!==x}var r=typeof Object.is=="function"?Object.is:t,n=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(m,x){var y=x(),v=n({inst:{value:y,getSnapshot:x}}),w=v[0].inst,b=v[1];return i(function(){w.value=y,w.getSnapshot=x,c(w)&&b({inst:w})},[m,y,x]),a(function(){return c(w)&&b({inst:w}),m(function(){c(w)&&b({inst:w})})},[m]),l(y),y}function c(m){var x=m.getSnapshot;m=m.value;try{var y=x();return!r(m,y)}catch{return!0}}function d(m,x){return x()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return d1e.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:h,d1e}git.exports=bWt();var P3e=git.exports;const _Wt=(...s)=>t=>{s.forEach(r=>{typeof r=="function"?r(t):r&&(r.current=t)})},wWt=({contentComponent:s})=>{const t=P3e.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return wt.createElement(wt.Fragment,null,Object.values(t))};function jWt(){const s=new Set;let t={};return{subscribe(r){return s.add(r),()=>{s.delete(r)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(r,n){t={...t,[r]:tCe.createPortal(n.reactElement,n.element,r)},s.forEach(a=>a())},removeRenderer(r){const n={...t};delete n[r],t=n,s.forEach(a=>a())}}}class NWt extends wt.Component{constructor(t){var r;super(t),this.editorContentRef=wt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((r=t.editor)===null||r===void 0)&&r.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 r=this.editorContentRef.current;r.append(...t.options.element.childNodes),t.setOptions({element:r}),t.contentComponent=jWt(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(n=>n.hasContentComponentInitialized?n:{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 r=document.createElement("div");r.append(...t.options.element.childNodes),t.setOptions({element:r})}render(){const{editor:t,innerRef:r,...n}=this.props;return wt.createElement(wt.Fragment,null,wt.createElement("div",{ref:_Wt(r,this.editorContentRef),...n}),(t==null?void 0:t.contentComponent)&&wt.createElement(wWt,{contentComponent:t.contentComponent}))}}const kWt=k.forwardRef((s,t)=>{const r=wt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return wt.createElement(NWt,{key:r,innerRef:t,...s})}),D3e=wt.memo(kWt);var SWt=function s(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!s(t[a],r[a]))return!1;return!0}if(t instanceof Map&&r instanceof Map){if(t.size!==r.size)return!1;for(a of t.entries())if(!r.has(a[0]))return!1;for(a of t.entries())if(!s(a[1],r.get(a[0])))return!1;return!0}if(t instanceof Set&&r instanceof Set){if(t.size!==r.size)return!1;for(a of t.entries())if(!r.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(r)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(t[a]!==r[a])return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var l=i[a];if(!(l==="_owner"&&t.$$typeof)&&!s(t[l],r[l]))return!1}return!0}return t!==t&&r!==r},CWt=vWt(SWt),yit={exports:{}},u1e={};/** * @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 KFe;function TWt(){if(KFe)return u1e;KFe=1;var s=wt,t=P3e;function r(d,h){return d===h&&(d!==0||1/d===1/h)||d!==d&&h!==h}var n=typeof Object.is=="function"?Object.is:r,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return u1e.useSyncExternalStoreWithSelector=function(d,h,m,x,y){var v=i(null);if(v.current===null){var w={hasValue:!1,value:null};v.current=w}else w=v.current;v=o(function(){function N(D){if(!S){if(S=!0,T=D,D=x(D),y!==void 0&&w.hasValue){var R=w.value;if(y(R,D))return A=R}return A=D}if(R=A,n(T,D))return R;var $=x(D);return y!==void 0&&y(R,$)?R:(T=D,A=$)}var S=!1,T,A,I=m===void 0?null:m;return[function(){return N(h())},I===null?void 0:function(){return N(I())}]},[h,m,x,y]);var b=a(d,v[0],v[1]);return l(function(){w.hasValue=!0,w.value=b},[b]),c(b),b},u1e}yit.exports=TWt();var EWt=yit.exports;const AWt=typeof window<"u"?k.useLayoutEffect:k.useEffect;class MWt{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 r=()=>{this.transactionNumber+=1,this.subscribers.forEach(a=>a())},n=this.editor;return n.on("transaction",r),()=>{n.off("transaction",r)}}}}function IWt(s){var t;const[r]=k.useState(()=>new MWt(s.editor)),n=EWt.useSyncExternalStoreWithSelector(r.subscribe,r.getSnapshot,r.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:CWt);return AWt(()=>r.watch(s.editor),[s.editor,r]),k.useDebugValue(n),n}const LWt=!1,h2e=typeof window>"u",PWt=h2e||!!(typeof window<"u"&&window.next);class R3e{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(r=>r())}getInitialEditor(){if(this.options.current.immediatelyRender===void 0)return h2e||PWt?null:this.createEditor();if(this.options.current.immediatelyRender&&h2e&&LWt)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:(...n)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...n)},onBlur:(...n)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...n)},onCreate:(...n)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...n)},onDestroy:(...n)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...n)},onFocus:(...n)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...n)},onSelectionUpdate:(...n)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...n)},onTransaction:(...n)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...n)},onUpdate:(...n)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...n)},onContentError:(...n)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...n)},onDrop:(...n)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...n)},onPaste:(...n)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...n)}};return new gWt(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,r){return Object.keys(t).every(n=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(n)?!0:n==="extensions"&&t.extensions&&r.extensions?t.extensions.length!==r.extensions.length?!1:t.extensions.every((a,i)=>{var l;return a===((l=r.extensions)===null||l===void 0?void 0:l[i])}):t[n]===r[n])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?R3e.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((n,a)=>n===t[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,r=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){r&&r.setOptions(this.options.current);return}r&&!r.isDestroyed&&(r.destroy(),this.instanceId===t&&this.setEditor(null))},1)}}function O3e(s={},t=[]){const r=k.useRef(s);r.current=s;const[n]=k.useState(()=>new R3e(r)),a=P3e.useSyncExternalStore(n.subscribe,n.getEditor,n.getServerSnapshot);return k.useDebugValue(a),k.useEffect(n.onRender(t)),IWt({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const DWt=k.createContext({editor:null});DWt.Consumer;const RWt=k.createContext({onDragStart:void 0}),OWt=()=>k.useContext(RWt);wt.forwardRef((s,t)=>{const{onDragStart:r}=OWt(),n=s.as||"div";return wt.createElement(n,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:r,style:{whiteSpace:"normal",...s.style}})});const FWt=/^\s*>\s$/,BWt=Em.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Wc(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[M8({find:FWt,type:this.type})]}}),zWt=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,$Wt=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,UWt=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,qWt=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,VWt=Oy.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",Wc(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[BM({find:zWt,type:this.type}),BM({find:UWt,type:this.type})]},addPasteRules(){return[B3({find:$Wt,type:this.type}),B3({find:qWt,type:this.type})]}}),HWt="listItem",YFe="textStyle",ZFe=/^\s*([-+*])\s$/,GWt=Em.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",Wc(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(HWt,this.editor.getAttributes(YFe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=M8({find:ZFe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=M8({find:ZFe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(YFe),editor:this.editor})),[s]}}),WWt=/(^|[^`])`([^`]+)`(?!`)/,KWt=/(^|[^`])`([^`]+)`(?!`)/g,YWt=Oy.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Wc(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[BM({find:WWt,type:this.type})]},addPasteRules(){return[B3({find:KWt,type:this.type})]}}),ZWt=/^```([a-z]+)?[\s\n]$/,XWt=/^~~~([a-z]+)?[\s\n]$/,QWt=Em.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:r}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(r)).map(l=>l.replace(r,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",Wc(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,r=t.pos===1;return!s||t.parent.type.name!==this.name?!1:r||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:r}=t,{$from:n,empty:a}=r;if(!a||n.parent.type!==this.type)return!1;const i=n.parentOffset===n.parent.nodeSize-2,l=n.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(n.pos-2,n.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:r,doc:n}=t,{$from:a,empty:i}=r;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:n.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(pi.near(n.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[d2e({find:ZWt,type:this.type,getAttributes:s=>({language:s[1]})}),d2e({find:XWt,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Ju({key:new Tm("codeBlockVSCodeHandler"),props:{handlePaste:(s,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const r=t.clipboardData.getData("text/plain"),n=t.clipboardData.getData("vscode-editor-data"),a=n?JSON.parse(n):void 0,i=a==null?void 0:a.mode;if(!r||!i)return!1;const{tr:l,schema:o}=s.state,c=o.text(r.replace(/\r\n?/g,` `));return l.replaceSelectionWith(this.type.create({language:i},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(oi.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),JWt=Em.create({name:"doc",topNode:!0,content:"block+"});function eKt(s={}){return new Ju({view(t){return new tKt(t,s)}})}class tKt{constructor(t,r){var n;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(n=r.width)!==null&&n!==void 0?n:1,this.color=r.color===!1?void 0:r.color||"black",this.class=r.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:r})=>this.editorView.dom.removeEventListener(t,r))}update(t,r){this.cursorPos!=null&&r.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),r=!t.parent.inlineContent,n,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(r){let m=t.nodeBefore,x=t.nodeAfter;if(m||x){let y=this.editorView.nodeDOM(this.cursorPos-(m?m.nodeSize:0));if(y){let v=y.getBoundingClientRect(),w=m?v.bottom:v.top;m&&x&&(w=(w+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let b=this.width/2*o;n={left:v.left,right:v.right,top:w-b,bottom:w+b}}}}if(!n){let m=this.editorView.coordsAtPos(this.cursorPos),x=this.width/2*l;n={left:m.left-x,right:m.left+x,top:m.top,bottom:m.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",r),this.element.classList.toggle("prosemirror-dropcursor-inline",!r);let d,h;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,h=-pageYOffset;else{let m=c.getBoundingClientRect(),x=m.width/c.offsetWidth,y=m.height/c.offsetHeight;d=m.left-c.scrollLeft*x,h=m.top-c.scrollTop*y}this.element.style.left=(n.left-d)/l+"px",this.element.style.top=(n.top-h)/o+"px",this.element.style.width=(n.right-n.left)/l+"px",this.element.style.height=(n.bottom-n.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let r=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=r&&r.inside>=0&&this.editorView.state.doc.nodeAt(r.inside),a=n&&n.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,r,t):a;if(r&&!i){let l=r.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=cat(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 sKt=nm.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[eKt(this.options)]}});class Cd extends pi{constructor(t){super(t,t)}map(t,r){let n=t.resolve(r.map(this.head));return Cd.valid(n)?new Cd(n):pi.near(n)}content(){return Un.empty}eq(t){return t instanceof Cd&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,r){if(typeof r.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Cd(t.resolve(r.pos))}getBookmark(){return new F3e(this.anchor)}static valid(t){let r=t.parent;if(r.inlineContent||!rKt(t)||!nKt(t))return!1;let n=r.type.spec.allowGapCursor;if(n!=null)return n;let a=r.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,r,n=!1){e:for(;;){if(!n&&Cd.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(r>0?t.indexAfter(l)0){i=o.child(r>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=r;let c=t.doc.resolve(a);if(Cd.valid(c))return c}for(;;){let l=r>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Xa.isSelectable(i)){t=t.doc.resolve(a+i.nodeSize*r),n=!1;continue e}break}i=l,a+=r;let o=t.doc.resolve(a);if(Cd.valid(o))return o}return null}}}Cd.prototype.visible=!1;Cd.findFrom=Cd.findGapCursorFrom;pi.jsonID("gapcursor",Cd);class F3e{constructor(t){this.pos=t}map(t){return new F3e(t.map(this.pos))}resolve(t){let r=t.resolve(this.pos);return Cd.valid(r)?new Cd(r):pi.near(r)}}function vit(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function rKt(s){for(let t=s.depth;t>=0;t--){let r=s.index(t),n=s.node(t);if(r==0){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||vit(a.type))return!0;if(a.inlineContent)return!1}}return!0}function nKt(s){for(let t=s.depth;t>=0;t--){let r=s.indexAfter(t),n=s.node(t);if(r==n.childCount){if(n.type.spec.isolating)return!0;continue}for(let a=n.child(r);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||vit(a.type))return!0;if(a.inlineContent)return!1}}return!0}function aKt(){return new Ju({props:{decorations:cKt,createSelectionBetween(s,t,r){return t.pos==r.pos&&Cd.valid(r)?new Cd(r):null},handleClick:oKt,handleKeyDown:iKt,handleDOMEvents:{beforeinput:lKt}}})}const iKt=k3e({ArrowLeft:n$("horiz",-1),ArrowRight:n$("horiz",1),ArrowUp:n$("vert",-1),ArrowDown:n$("vert",1)});function n$(s,t){const r=s=="vert"?t>0?"down":"up":t>0?"right":"left";return function(n,a,i){let l=n.selection,o=t>0?l.$to:l.$from,c=l.empty;if(l instanceof oi){if(!i.endOfTextblock(r)||o.depth==0)return!1;c=!1,o=n.doc.resolve(t>0?o.after():o.before())}let d=Cd.findGapCursorFrom(o,t,c);return d?(a&&a(n.tr.setSelection(new Cd(d))),!0):!1}}function oKt(s,t,r){if(!s||!s.editable)return!1;let n=s.state.doc.resolve(t);if(!Cd.valid(n))return!1;let a=s.posAtCoords({left:r.clientX,top:r.clientY});return a&&a.inside>-1&&Xa.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new Cd(n))),!0)}function lKt(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof Cd))return!1;let{$from:r}=s.state.selection,n=r.parent.contentMatchAt(r.index()).findWrapping(s.state.schema.nodes.text);if(!n)return!1;let a=dn.empty;for(let l=n.length-1;l>=0;l--)a=dn.from(n[l].createAndFill(null,a));let i=s.state.tr.replace(r.pos,r.pos,new Un(a,0,0));return i.setSelection(oi.near(i.doc.resolve(r.pos+1))),s.dispatch(i),!1}function cKt(s){if(!(s.selection instanceof Cd))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",Sd.create(s.doc,[df.widget(s.selection.head,t,{key:"gapcursor"})])}const dKt=nm.create({name:"gapCursor",addProseMirrorPlugins(){return[aKt()]},extendNodeSchema(s){var t;const r={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Qi(ja(s,"allowGapCursor",r)))!==null&&t!==void 0?t:null}}}),uKt=Em.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",Wc(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:r,editor:n})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=r;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=n.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:h})=>{if(h&&c&&l){const m=c.filter(x=>o.includes(x.type.name));d.ensureMarks(m)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),hKt=Em.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]}`,Wc(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=>d2e({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var oue=200,kh=function(){};kh.prototype.append=function(t){return t.length?(t=kh.from(t),!this.length&&t||t.length=r?kh.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,r))};kh.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};kh.prototype.forEach=function(t,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length),r<=n?this.forEachInner(t,r,n,0):this.forEachInvertedInner(t,r,n,0)};kh.prototype.map=function(t,r,n){r===void 0&&(r=0),n===void 0&&(n=this.length);var a=[];return this.forEach(function(i,l){return a.push(t(i,l))},r,n),a};kh.from=function(t){return t instanceof kh?t:t&&t.length?new bit(t):kh.empty};var bit=function(s){function t(n){s.call(this),this.values=n}s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t;var r={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<=oue)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=oue)return new t(a.flatten().concat(this.values))},r.length.get=function(){return this.values.length},r.depth.get=function(){return 0},Object.defineProperties(t.prototype,r),t}(kh);kh.empty=new bit([]);var mKt=function(s){function t(r,n){s.call(this),this.left=r,this.right=n,this.length=r.length+n.length,this.depth=Math.max(r.depth,n.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(n){return no&&this.right.forEachInner(n,Math.max(a-o,0),Math.min(this.length,i)-o,l+o)===!1)return!1},t.prototype.forEachInvertedInner=function(n,a,i,l){var o=this.left.length;if(a>o&&this.right.forEachInvertedInner(n,a-o,Math.max(i,o)-o,l+o)===!1||i=i?this.right.slice(n-i,a-i):this.left.slice(n,i).append(this.right.slice(0,a-i))},t.prototype.leafAppend=function(n){var a=this.right.leafAppend(n);if(a)return new t(this.left,a)},t.prototype.leafPrepend=function(n){var a=this.left.leafPrepend(n);if(a)return new t(a,this.right)},t.prototype.appendInner=function(n){return this.left.depth>=Math.max(this.right.depth,n.depth)+1?new t(this.left,new t(this.right,n)):new t(this,n)},t}(kh);const fKt=500;class gy{constructor(t,r){this.items=t,this.eventCount=r}popEvent(t,r){if(this.eventCount==0)return null;let n=this.items.length;for(;;n--)if(this.items.get(n-1).selection){--n;break}let a,i;r&&(a=this.remapping(n,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],h=[];return this.items.forEach((m,x)=>{if(!m.step){a||(a=this.remapping(n,x+1),i=a.maps.length),i--,h.push(m);return}if(a){h.push(new C0(m.map));let y=m.step.map(a.slice(i)),v;y&&l.maybeStep(y).doc&&(v=l.mapping.maps[l.mapping.maps.length-1],d.push(new C0(v,void 0,void 0,d.length+h.length))),i--,v&&a.appendMap(v,i)}else l.maybeStep(m.step);if(m.selection)return o=a?m.selection.map(a.slice(i)):m.selection,c=new gy(this.items.slice(0,n).append(h.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,r,n,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let h=0;hxKt&&(o=pKt(o,d),l-=d),new gy(o.append(i),l)}remapping(t,r){let n=new N8;return this.items.forEach((a,i)=>{let l=a.mirrorOffset!=null&&i-a.mirrorOffset>=t?n.maps.length-a.mirrorOffset:void 0;n.appendMap(a.map,l)},t,r),n}addMaps(t){return this.eventCount==0?this:new gy(this.items.append(t.map(r=>new C0(r))),this.eventCount)}rebased(t,r){if(!this.eventCount)return this;let n=[],a=Math.max(0,this.items.length-r),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(x=>{x.selection&&o--},a);let c=r;this.items.forEach(x=>{let y=i.getMirror(--c);if(y==null)return;l=Math.min(l,y);let v=i.maps[y];if(x.step){let w=t.steps[y].invert(t.docs[y]),b=x.selection&&x.selection.map(i.slice(c+1,y));b&&o++,n.push(new C0(v,w,b))}else n.push(new C0(v))},a);let d=[];for(let x=r;xfKt&&(m=m.compress(this.items.length-n.length)),m}emptyItemCount(){let t=0;return this.items.forEach(r=>{r.step||t++}),t}compress(t=this.items.length){let r=this.remapping(0,t),n=r.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(r.slice(n)),d=c&&c.getMap();if(n--,d&&r.appendMap(d,n),c){let h=l.selection&&l.selection.map(r.slice(n));h&&i++;let m=new C0(d.invert(),c,h),x,y=a.length-1;(x=a.length&&a[y].merge(m))?a[y]=x:a.push(m)}}else l.map&&n--},this.items.length,0),new gy(kh.from(a.reverse()),i)}}gy.empty=new gy(kh.empty,0);function pKt(s,t){let r;return s.forEach((n,a)=>{if(n.selection&&t--==0)return r=a,!1}),s.slice(r)}class C0{constructor(t,r,n,a){this.map=t,this.step=r,this.selection=n,this.mirrorOffset=a}merge(t){if(this.step&&t.step&&!t.selection){let r=t.step.merge(this.step);if(r)return new C0(r.getMap().invert(),r,this.selection)}}}class aw{constructor(t,r,n,a,i){this.done=t,this.undone=r,this.prevRanges=n,this.prevTime=a,this.prevComposition=i}}const xKt=20;function gKt(s,t,r,n){let a=r.getMeta(u3),i;if(a)return a.historyState;r.getMeta(bKt)&&(s=new aw(s.done,s.undone,null,0,-1));let l=r.getMeta("appendedTransaction");if(r.steps.length==0)return s;if(l&&l.getMeta(u3))return l.getMeta(u3).redo?new aw(s.done.addTransform(r,void 0,n,vce(t)),s.undone,XFe(r.mapping.maps),s.prevTime,s.prevComposition):new aw(s.done,s.undone.addTransform(r,void 0,n,vce(t)),null,s.prevTime,s.prevComposition);if(r.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=r.getMeta("composition"),c=s.prevTime==0||!l&&s.prevComposition!=o&&(s.prevTime<(r.time||0)-n.newGroupDelay||!yKt(r,s.prevRanges)),d=l?h1e(s.prevRanges,r.mapping):XFe(r.mapping.maps);return new aw(s.done.addTransform(r,c?t.selection.getBookmark():void 0,n,vce(t)),gy.empty,d,r.time,o??s.prevComposition)}else return(i=r.getMeta("rebased"))?new aw(s.done.rebased(r,i),s.undone.rebased(r,i),h1e(s.prevRanges,r.mapping),s.prevTime,s.prevComposition):new aw(s.done.addMaps(r.mapping.maps),s.undone.addMaps(r.mapping.maps),h1e(s.prevRanges,r.mapping),s.prevTime,s.prevComposition)}function yKt(s,t){if(!t)return!1;if(!s.docChanged)return!0;let r=!1;return s.mapping.maps[0].forEach((n,a)=>{for(let i=0;i=t[i]&&(r=!0)}),r}function XFe(s){let t=[];for(let r=s.length-1;r>=0&&t.length==0;r--)s[r].forEach((n,a,i,l)=>t.push(i,l));return t}function h1e(s,t){if(!s)return null;let r=[];for(let n=0;n{let a=u3.getState(r);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(n){let i=vKt(a,r,s);i&&n(t?i.scrollIntoView():i)}return!0}}const wit=_it(!1,!0),jit=_it(!0,!0),wKt=nm.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>wit(s,t),redo:()=>({state:s,dispatch:t})=>jit(s,t)}},addProseMirrorPlugins(){return[_Kt(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()}}}),jKt=Em.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Wc(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!yWt(t,t.schema.nodes[this.name]))return!1;const{selection:r}=t,{$from:n,$to:a}=r,i=s();return n.parentOffset===0?i.insertContentAt({from:Math.max(n.pos-1,0),to:a.pos},{type:this.name}):zGt(r)?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,h=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(oi.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Xa.create(l.doc,d.pos)):l.setSelection(oi.create(l.doc,d.pos));else{const m=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();m&&(l.insert(h,m),l.setSelection(oi.create(l.doc,h+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[xit({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),NKt=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,kKt=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,SKt=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,CKt=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,TKt=Oy.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",Wc(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[BM({find:NKt,type:this.type}),BM({find:SKt,type:this.type})]},addPasteRules(){return[B3({find:kKt,type:this.type}),B3({find:CKt,type:this.type})]}}),EKt=Em.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Wc(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)}}}),AKt="listItem",JFe="textStyle",eBe=/^(\d+)\.\s$/,MKt=Em.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,...r}=s;return t===1?["ol",Wc(this.options.HTMLAttributes,r),0]:["ol",Wc(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(AKt,this.editor.getAttributes(JFe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=M8({find:eBe,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=M8({find:eBe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(JFe)}),joinPredicate:(t,r)=>r.childCount+r.attrs.start===+t[1],editor:this.editor})),[s]}}),IKt=Em.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Wc(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),LKt=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,PKt=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,DKt=Oy.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",Wc(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[BM({find:LKt,type:this.type})]},addPasteRules(){return[B3({find:PKt,type:this.type})]}}),RKt=Em.create({name:"text",group:"inline"}),B3e=nm.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(VWt.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(BWt.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(GWt.configure(this.options.bulletList)),this.options.code!==!1&&s.push(YWt.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(QWt.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(JWt.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(sKt.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(dKt.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(uKt.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(hKt.configure(this.options.heading)),this.options.history!==!1&&s.push(wKt.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(jKt.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(TKt.configure(this.options.italic)),this.options.listItem!==!1&&s.push(EKt.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(MKt.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(IKt.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(DKt.configure(this.options.strike)),this.options.text!==!1&&s.push(RKt.configure(this.options.text)),s}}),OKt="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",FKt="ελ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",m2e="numeric",f2e="ascii",p2e="alpha",gO="asciinumeric",OD="alphanumeric",x2e="domain",Nit="emoji",BKt="scheme",zKt="slashscheme",f1e="whitespace";function $Kt(s,t){return s in t||(t[s]=[]),t[s]}function l4(s,t,r){t[m2e]&&(t[gO]=!0,t[OD]=!0),t[f2e]&&(t[gO]=!0,t[p2e]=!0),t[gO]&&(t[OD]=!0),t[p2e]&&(t[OD]=!0),t[OD]&&(t[x2e]=!0),t[Nit]&&(t[x2e]=!0);for(const n in t){const a=$Kt(n,r);a.indexOf(s)<0&&a.push(s)}}function UKt(s,t){const r={};for(const n in t)t[n].indexOf(s)>=0&&(r[n]=!0);return r}function Uf(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}Uf.groups={};Uf.prototype={accepts(){return!!this.t},go(s){const t=this,r=t.j[s];if(r)return r;for(let n=0;ns.ta(t,r,n,a),yd=(s,t,r,n,a)=>s.tr(t,r,n,a),tBe=(s,t,r,n,a)=>s.ts(t,r,n,a),xn=(s,t,r,n,a)=>s.tt(t,r,n,a),O1="WORD",g2e="UWORD",kit="ASCIINUMERICAL",Sit="ALPHANUMERICAL",I8="LOCALHOST",y2e="TLD",v2e="UTLD",bce="SCHEME",kE="SLASH_SCHEME",z3e="NUM",b2e="WS",$3e="NL",yO="OPENBRACE",vO="CLOSEBRACE",lue="OPENBRACKET",cue="CLOSEBRACKET",due="OPENPAREN",uue="CLOSEPAREN",hue="OPENANGLEBRACKET",mue="CLOSEANGLEBRACKET",fue="FULLWIDTHLEFTPAREN",pue="FULLWIDTHRIGHTPAREN",xue="LEFTCORNERBRACKET",gue="RIGHTCORNERBRACKET",yue="LEFTWHITECORNERBRACKET",vue="RIGHTWHITECORNERBRACKET",bue="FULLWIDTHLESSTHAN",_ue="FULLWIDTHGREATERTHAN",wue="AMPERSAND",jue="APOSTROPHE",Nue="ASTERISK",iw="AT",kue="BACKSLASH",Sue="BACKTICK",Cue="CARET",gw="COLON",U3e="COMMA",Tue="DOLLAR",T0="DOT",Eue="EQUALS",q3e="EXCLAMATION",Fx="HYPHEN",bO="PERCENT",Aue="PIPE",Mue="PLUS",Iue="POUND",_O="QUERY",V3e="QUOTE",Cit="FULLWIDTHMIDDLEDOT",H3e="SEMI",E0="SLASH",wO="TILDE",Lue="UNDERSCORE",Tit="EMOJI",Pue="SYM";var Eit=Object.freeze({__proto__:null,ALPHANUMERICAL:Sit,AMPERSAND:wue,APOSTROPHE:jue,ASCIINUMERICAL:kit,ASTERISK:Nue,AT:iw,BACKSLASH:kue,BACKTICK:Sue,CARET:Cue,CLOSEANGLEBRACKET:mue,CLOSEBRACE:vO,CLOSEBRACKET:cue,CLOSEPAREN:uue,COLON:gw,COMMA:U3e,DOLLAR:Tue,DOT:T0,EMOJI:Tit,EQUALS:Eue,EXCLAMATION:q3e,FULLWIDTHGREATERTHAN:_ue,FULLWIDTHLEFTPAREN:fue,FULLWIDTHLESSTHAN:bue,FULLWIDTHMIDDLEDOT:Cit,FULLWIDTHRIGHTPAREN:pue,HYPHEN:Fx,LEFTCORNERBRACKET:xue,LEFTWHITECORNERBRACKET:yue,LOCALHOST:I8,NL:$3e,NUM:z3e,OPENANGLEBRACKET:hue,OPENBRACE:yO,OPENBRACKET:lue,OPENPAREN:due,PERCENT:bO,PIPE:Aue,PLUS:Mue,POUND:Iue,QUERY:_O,QUOTE:V3e,RIGHTCORNERBRACKET:gue,RIGHTWHITECORNERBRACKET:vue,SCHEME:bce,SEMI:H3e,SLASH:E0,SLASH_SCHEME:kE,SYM:Pue,TILDE:wO,TLD:y2e,UNDERSCORE:Lue,UTLD:v2e,UWORD:g2e,WORD:O1,WS:b2e});const E1=/[a-z]/,nD=new RegExp("\\p{L}","u"),p1e=new RegExp("\\p{Emoji}","u"),A1=/\d/,x1e=/\s/,sBe="\r",g1e=` `,qKt="️",VKt="‍",y1e="";let a$=null,i$=null;function HKt(s=[]){const t={};Uf.groups=t;const r=new Uf;a$==null&&(a$=rBe(OKt)),i$==null&&(i$=rBe(FKt)),xn(r,"'",jue),xn(r,"{",yO),xn(r,"}",vO),xn(r,"[",lue),xn(r,"]",cue),xn(r,"(",due),xn(r,")",uue),xn(r,"<",hue),xn(r,">",mue),xn(r,"(",fue),xn(r,")",pue),xn(r,"「",xue),xn(r,"」",gue),xn(r,"『",yue),xn(r,"』",vue),xn(r,"<",bue),xn(r,">",_ue),xn(r,"&",wue),xn(r,"*",Nue),xn(r,"@",iw),xn(r,"`",Sue),xn(r,"^",Cue),xn(r,":",gw),xn(r,",",U3e),xn(r,"$",Tue),xn(r,".",T0),xn(r,"=",Eue),xn(r,"!",q3e),xn(r,"-",Fx),xn(r,"%",bO),xn(r,"|",Aue),xn(r,"+",Mue),xn(r,"#",Iue),xn(r,"?",_O),xn(r,'"',V3e),xn(r,"/",E0),xn(r,";",H3e),xn(r,"~",wO),xn(r,"_",Lue),xn(r,"\\",kue),xn(r,"・",Cit);const n=yd(r,A1,z3e,{[m2e]:!0});yd(n,A1,n);const a=yd(n,E1,kit,{[gO]:!0}),i=yd(n,nD,Sit,{[OD]:!0}),l=yd(r,E1,O1,{[f2e]:!0});yd(l,A1,a),yd(l,E1,l),yd(a,A1,a),yd(a,E1,a);const o=yd(r,nD,g2e,{[p2e]:!0});yd(o,E1),yd(o,A1,i),yd(o,nD,o),yd(i,A1,i),yd(i,E1),yd(i,nD,i);const c=xn(r,g1e,$3e,{[f1e]:!0}),d=xn(r,sBe,b2e,{[f1e]:!0}),h=yd(r,x1e,b2e,{[f1e]:!0});xn(r,y1e,h),xn(d,g1e,c),xn(d,y1e,h),yd(d,x1e,h),xn(h,sBe),xn(h,g1e),yd(h,x1e,h),xn(h,y1e,h);const m=yd(r,p1e,Tit,{[Nit]:!0});xn(m,"#"),yd(m,p1e,m),xn(m,qKt,m);const x=xn(m,VKt);xn(x,"#"),yd(x,p1e,m);const y=[[E1,l],[A1,a]],v=[[E1,null],[nD,o],[A1,i]];for(let w=0;ww[0]>b[0]?1:-1);for(let w=0;w=0?S[x2e]=!0:E1.test(b)?A1.test(b)?S[gO]=!0:S[f2e]=!0:S[m2e]=!0,tBe(r,b,b,S)}return tBe(r,"localhost",I8,{ascii:!0}),r.jd=new Uf(Pue),{start:r,tokens:Object.assign({groups:t},Eit)}}function Ait(s,t){const r=GKt(t.replace(/[A-Z]/g,o=>o.toLowerCase())),n=r.length,a=[];let i=0,l=0;for(;l=0&&(m+=r[l].length,x++),d+=r[l].length,i+=r[l].length,l++;i-=m,l-=x,d-=m,a.push({t:h.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function GKt(s){const t=[],r=s.length;let n=0;for(;n56319||n+1===r||(i=s.charCodeAt(n+1))<56320||i>57343?s[n]:s.slice(n,n+2);t.push(l),n+=l.length}return t}function F_(s,t,r,n,a){let i;const l=t.length;for(let o=0;o=0;)i++;if(i>0){t.push(r.join(""));for(let l=parseInt(s.substring(n,n+i),10);l>0;l--)r.pop();n+=i}else r.push(s[n]),n++}return t}const L8={defaultProtocol:"http",events:null,format:nBe,formatHref:nBe,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function G3e(s,t=null){let r=Object.assign({},L8);s&&(r=Object.assign(r,s instanceof G3e?s.o:s));const n=r.ignoreTags,a=[];for(let i=0;ir?n.substring(0,r)+"…":n},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=L8.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,r=this.toHref(s.get("defaultProtocol")),n=s.get("formatHref",r,this),a=s.get("tagName",r,t),i=this.toFormattedString(s),l={},o=s.get("className",r,t),c=s.get("target",r,t),d=s.get("rel",r,t),h=s.getObj("attributes",r,t),m=s.getObj("events",r,t);return l.href=n,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),h&&Object.assign(l,h),{tagName:a,attributes:l,content:i,eventListeners:m}}};function ipe(s,t){class r extends Mit{constructor(a,i){super(a,i),this.t=s}}for(const n in t)r.prototype[n]=t[n];return r.t=s,r}const aBe=ipe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),iBe=ipe("text"),WKt=ipe("nl"),o$=ipe("url",{isLink:!0,toHref(s=L8.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==I8&&s[1].t===gw}}),Mx=s=>new Uf(s);function KKt({groups:s}){const t=s.domain.concat([wue,Nue,iw,kue,Sue,Cue,Tue,Eue,Fx,z3e,bO,Aue,Mue,Iue,E0,Pue,wO,Lue]),r=[jue,gw,U3e,T0,q3e,bO,_O,V3e,H3e,hue,mue,yO,vO,cue,lue,due,uue,fue,pue,xue,gue,yue,vue,bue,_ue],n=[wue,jue,Nue,kue,Sue,Cue,Tue,Eue,Fx,yO,vO,bO,Aue,Mue,Iue,_O,E0,Pue,wO,Lue],a=Mx(),i=xn(a,wO);Xi(i,n,i),Xi(i,s.domain,i);const l=Mx(),o=Mx(),c=Mx();Xi(a,s.domain,l),Xi(a,s.scheme,o),Xi(a,s.slashscheme,c),Xi(l,n,i),Xi(l,s.domain,l);const d=xn(l,iw);xn(i,iw,d),xn(o,iw,d),xn(c,iw,d);const h=xn(i,T0);Xi(h,n,i),Xi(h,s.domain,i);const m=Mx();Xi(d,s.domain,m),Xi(m,s.domain,m);const x=xn(m,T0);Xi(x,s.domain,m);const y=Mx(aBe);Xi(x,s.tld,y),Xi(x,s.utld,y),xn(d,I8,y);const v=xn(m,Fx);xn(v,Fx,v),Xi(v,s.domain,m),Xi(y,s.domain,m),xn(y,T0,x),xn(y,Fx,v);const w=xn(y,gw);Xi(w,s.numeric,aBe);const b=xn(l,Fx),N=xn(l,T0);xn(b,Fx,b),Xi(b,s.domain,l),Xi(N,n,i),Xi(N,s.domain,l);const S=Mx(o$);Xi(N,s.tld,S),Xi(N,s.utld,S),Xi(S,s.domain,l),Xi(S,n,i),xn(S,T0,N),xn(S,Fx,b),xn(S,iw,d);const T=xn(S,gw),A=Mx(o$);Xi(T,s.numeric,A);const I=Mx(o$),D=Mx();Xi(I,t,I),Xi(I,r,D),Xi(D,t,I),Xi(D,r,D),xn(S,E0,I),xn(A,E0,I);const R=xn(o,gw),$=xn(c,gw),F=xn($,E0),z=xn(F,E0);Xi(o,s.domain,l),xn(o,T0,N),xn(o,Fx,b),Xi(c,s.domain,l),xn(c,T0,N),xn(c,Fx,b),Xi(R,s.domain,I),xn(R,E0,I),xn(R,_O,I),Xi(z,s.domain,I),Xi(z,t,I),xn(z,E0,I);const Q=[[yO,vO],[lue,cue],[due,uue],[hue,mue],[fue,pue],[xue,gue],[yue,vue],[bue,_ue]];for(let K=0;K=0&&x++,a++,h++;if(x<0)a-=h,a0&&(i.push(v1e(iBe,t,l)),l=[]),a-=x,h-=x;const y=m.t,v=r.slice(a-h,a);i.push(v1e(y,t,v))}}return l.length>0&&i.push(v1e(iBe,t,l)),i}function v1e(s,t,r){const n=r[0].s,a=r[r.length-1].e,i=t.slice(n,a);return new s(i,r)}const ZKt=typeof console<"u"&&console&&console.warn||(()=>{}),XKt="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Nc={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function QKt(){return Uf.groups={},Nc.scanner=null,Nc.parser=null,Nc.tokenQueue=[],Nc.pluginQueue=[],Nc.customSchemes=[],Nc.initialized=!1,Nc}function oBe(s,t=!1){if(Nc.initialized&&ZKt(`linkifyjs: already initialized - will not register custom scheme "${s}" ${XKt}`),!/^[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`);Nc.customSchemes.push([s,t])}function JKt(){Nc.scanner=HKt(Nc.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!r.doc.eq(n.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=n,o=MGt(r.doc,[...t]);if(FGt(o).forEach(({newRange:d})=>{const h=LGt(n.doc,d,y=>y.isTextblock);let m,x;if(h.length>1)m=h[0],x=n.doc.textBetween(m.pos,m.pos+m.node.nodeSize,void 0," ");else if(h.length){const y=n.doc.textBetween(d.from,d.to," "," ");if(!tYt.test(y))return;m=h[0],x=n.doc.textBetween(m.pos,d.to,void 0," ")}if(m&&x){const y=x.split(eYt).filter(Boolean);if(y.length<=0)return!1;const v=y[y.length-1],w=m.pos+x.lastIndexOf(v);if(!v)return!1;const b=W3e(v).map(N=>N.toObject(s.defaultProtocol));if(!rYt(b))return!1;b.filter(N=>N.isLink).map(N=>({...N,from:w+N.start+1,to:w+N.end+1})).filter(N=>n.schema.marks.code?!n.doc.rangeHasMark(N.from,N.to,n.schema.marks.code):!0).filter(N=>s.validate(N.value)).filter(N=>s.shouldAutoLink(N.value)).forEach(N=>{I3e(N.from,N.to,n.doc).some(S=>S.mark.type===s.type)||l.addMark(N.from,N.to,s.type.create({href:N.href}))})}}),!!l.steps.length)return l}})}function aYt(s){return new Ju({key:new Tm("handleClickLink"),props:{handleClick:(t,r,n)=>{var a,i;if(n.button!==0||!t.editable)return!1;let l=n.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(x=>x.nodeName==="A"))return!1;const c=pit(t.state,s.type.name),d=n.target,h=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,m=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&h?(window.open(h,m),!0):!1}}})}function iYt(s){return new Ju({key:new Tm("handlePasteLink"),props:{handlePaste:(t,r,n)=>{const{state:a}=t,{selection:i}=a,{empty:l}=i;if(l)return!1;let o="";n.content.forEach(d=>{o+=d.textContent});const c=Iit(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 wN(s,t){const r=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(n=>{const a=typeof n=="string"?n:n.scheme;a&&r.push(a)}),!s||s.replace(sYt,"").match(new RegExp(`^(?:(?:${r.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const Y3e=Oy.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"){oBe(s);return}oBe(s.scheme,s.optionalSlashes)})},onDestroy(){QKt()},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)=>!!wN(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:r=>!!wN(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:t=>!!wN(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Wc(this.options.HTMLAttributes,s),0]:["a",Wc(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!wN(n,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:r}=s;return this.options.isAllowedUri(r,{defaultValidate:n=>!!wN(n,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[B3({find:s=>{const t=[];if(s){const{protocols:r,defaultProtocol:n}=this.options,a=Iit(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!wN(l,r),protocols:r,defaultProtocol:n}));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:r}=this.options;return this.options.autolink&&s.push(nYt({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:a=>!!wN(a,t),protocols:t,defaultProtocol:r}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(aYt({type:this.type})),this.options.linkOnPaste&&s.push(iYt({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),Z3e=nm.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(r=>t.updateAttributes(r,{textAlign:s})).every(r=>r):!1,unsetTextAlign:()=>({commands:s})=>this.options.types.map(t=>s.resetAttributes(t,"textAlign")).every(t=>t),toggleTextAlign:s=>({editor:t,commands:r})=>this.options.alignments.includes(s)?t.isActive({textAlign:s})?r.unsetTextAlign():r.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")}}}),oYt=s=>{if(!s.children.length)return;const t=s.querySelectorAll("span");t&&t.forEach(r=>{var n,a;const i=r.getAttribute("style"),l=(a=(n=r.parentElement)===null||n===void 0?void 0:n.closest("span"))===null||a===void 0?void 0:a.getAttribute("style");r.setAttribute("style",`${l};${i}`)})},X3e=Oy.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&oYt(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Wc(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(r,n)=>{if(r.isTextblock)return!0;r.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(n,n+r.nodeSize,this.type)}),!0}}}}),lYt=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,cYt=Em.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",Wc(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[xit({find:lYt,type:this.type,getAttributes:s=>{const[,,t,r,n]=s;return{src:r,alt:t,title:n}}})]}});let _2e,w2e;if(typeof WeakMap<"u"){let s=new WeakMap;_2e=t=>s.get(t),w2e=(t,r)=>(s.set(t,r),r)}else{const s=[];let r=0;_2e=n=>{for(let a=0;a(r==10&&(r=0),s[r++]=n,s[r++]=a)}var Td=class{constructor(s,t,r,n){this.width=s,this.height=t,this.map=r,this.problems=n}findCell(s){for(let t=0;t=r){(i||(i=[])).push({type:"overlong_rowspan",pos:h,n:N-T});break}const A=a+T*t;for(let I=0;In&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(r=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function hYt(s,t,r){s.problems||(s.problems=[]);const n={};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 fYt(s){for(let t=s.depth;t>0;t--){const r=s.node(t).type.spec.tableRole;if(r==="cell"||r==="header_cell")return s.node(t)}return null}function $y(s){const t=s.selection.$head;for(let r=t.depth;r>0;r--)if(t.node(r).type.spec.tableRole=="row")return!0;return!1}function ope(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 r=z3(t.$head)||pYt(t.$head);if(r)return r;throw new RangeError(`No cell found around position ${t.head}`)}function pYt(s){for(let t=s.nodeAfter,r=s.pos;t;t=t.firstChild,r++){const n=t.type.spec.tableRole;if(n=="cell"||n=="header_cell")return s.doc.resolve(r)}for(let t=s.nodeBefore,r=s.pos;t;t=t.lastChild,r--){const n=t.type.spec.tableRole;if(n=="cell"||n=="header_cell")return s.doc.resolve(r-t.nodeSize)}}function j2e(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function xYt(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function Q3e(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function Lit(s,t,r){const n=s.node(-1),a=Td.get(n),i=s.start(-1),l=a.nextCell(s.pos-i,t,r);return l==null?null:s.node(0).resolve(i+l)}function $3(s,t,r=1){const n={...s,colspan:s.colspan-r};return n.colwidth&&(n.colwidth=n.colwidth.slice(),n.colwidth.splice(t,r),n.colwidth.some(a=>a>0)||(n.colwidth=null)),n}function Pit(s,t,r=1){const n={...s,colspan:s.colspan+r};if(n.colwidth){n.colwidth=n.colwidth.slice();for(let a=0;ah!=r.pos-i);c.unshift(r.pos-i);const d=c.map(h=>{const m=n.nodeAt(h);if(!m)throw new RangeError(`No cell with offset ${h} found`);const x=i+h+1;return new fat(o.resolve(x),o.resolve(x+m.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=r}map(t,r){const n=t.resolve(r.map(this.$anchorCell.pos)),a=t.resolve(r.map(this.$headCell.pos));if(j2e(n)&&j2e(a)&&Q3e(n,a)){const i=this.$anchorCell.node(-1)!=n.node(-1);return i&&this.isRowSelection()?F1.rowSelection(n,a):i&&this.isColSelection()?F1.colSelection(n,a):new F1(n,a)}return oi.between(n,a)}content(){const t=this.$anchorCell.node(-1),r=Td.get(t),n=this.$anchorCell.start(-1),a=r.rectBetween(this.$anchorCell.pos-n,this.$headCell.pos-n),i={},l=[];for(let c=a.top;c0||b>0){let N=v.attrs;if(w>0&&(N=$3(N,0,w)),b>0&&(N=$3(N,N.colspan-b,b)),y.lefta.bottom){const N={...v.attrs,rowspan:Math.min(y.bottom,a.bottom)-Math.max(y.top,a.top)};y.top0)return!1;const n=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=r+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(n,a)==this.$headCell.node(-1).childCount}static colSelection(t,r=t){const n=t.node(-1),a=Td.get(n),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(r.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(r=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)==r.width}eq(t){return t instanceof F1&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,r=t){const n=t.node(-1),a=Td.get(n),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(r.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&&(r=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(df.node(n,n+r.nodeSize,{class:"selectedCell"}))}),Sd.create(s.doc,t)}function bYt({$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--,n--);return r==n&&/row|table/.test(s.node(a).type.spec.tableRole)}function _Yt({$from:s,$to:t}){let r,n;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"){r=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"){n=i;break}}return r!==n&&t.parentOffset===0}function wYt(s,t,r){const n=(t||s).selection,a=(t||s).doc;let i,l;if(n instanceof Xa&&(l=n.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=pc.create(a,n.from);else if(l=="row"){const o=a.resolve(n.from+1);i=pc.rowSelection(o,o)}else if(!r){const o=Td.get(n.node),c=n.from+1,d=c+o.map[o.width*o.height-1];i=pc.create(a,c+1,d)}}else n instanceof oi&&bYt(n)?i=oi.create(a,n.from):n instanceof oi&&_Yt(n)&&(i=oi.create(a,n.$from.start(),n.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const jYt=new Tm("fix-tables");function Rit(s,t,r,n){const a=s.childCount,i=t.childCount;e:for(let l=0,o=0;l{a.type.spec.tableRole=="table"&&(r=NYt(s,a,i,r))};return t?t.doc!=s.doc&&Rit(t.doc,s.doc,0,n):s.doc.descendants(n),r}function NYt(s,t,r,n){const a=Td.get(t);if(!a.problems)return n;n||(n=s.tr);const i=[];for(let c=0;c0){let y="cell";h.firstChild&&(y=h.firstChild.type.spec.tableRole);const v=[];for(let b=0;b0?-1:0;gYt(t,n,a+i)&&(i=a==0||a==t.width?null:0);for(let l=0;l0&&a0&&t.map[o-1]==c||a0?-1:0;EYt(t,n,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,h=t.width*a;d0&&a0&&m==t.map[h-t.width]){const x=r.nodeAt(m).attrs;s.setNodeMarkup(s.mapping.slice(o).map(m+n),null,{...x,rowspan:x.rowspan-1}),d+=x.colspan-1}else if(a0&&r[i]==r[i-1]||n.right0&&r[a]==r[a-s]||n.bottom0){const h=c+1+d.content.size,m=lBe(d)?c+1:h;i.replaceWith(m+n.tableStart,h+n.tableStart,o)}i.setSelection(new pc(i.doc.resolve(c+n.tableStart))),t(i)}return!0}function dBe(s,t){const r=km(s.schema);return DYt(({node:n})=>r[n.type.spec.tableRole])(s,t)}function DYt(s){return(t,r)=>{const n=t.selection;let a,i;if(n instanceof pc){if(n.$anchorCell.pos!=n.$headCell.pos)return!1;a=n.$anchorCell.nodeAfter,i=n.$anchorCell.pos}else{var l;if(a=fYt(n.$from),!a)return!1;i=(l=z3(n.$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(r){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const h=Ov(t),m=t.tr;for(let y=0;y{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),n(i)}return!0}}function OYt(s){return function(t,r){if(!$y(t))return!1;if(r){const n=km(t.schema),a=Ov(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 y=x+i.tableStart,v=l.doc.nodeAt(y);v&&l.setNodeMarkup(y,m,v.attrs)}),n(l)}return!0}}P8("row",{useDeprecatedLogic:!0});P8("column",{useDeprecatedLogic:!0});const FYt=P8("cell",{useDeprecatedLogic:!0});function BYt(s,t){if(t<0){const r=s.nodeBefore;if(r)return s.pos-r.nodeSize;for(let n=s.index(-1)-1,a=s.before();n>=0;n--){const i=s.node(-1).child(n),l=i.lastChild;if(l)return a-1-l.nodeSize;a-=i.nodeSize}}else{if(s.index()0;n--)if(r.node(n).type.spec.tableRole=="table")return t&&t(s.tr.delete(r.before(n),r.after(n)).scrollIntoView()),!0;return!1}function l$(s,t){const r=s.selection;if(!(r instanceof pc))return!1;if(t){const n=s.tr,a=km(s.schema).cell.createAndFill().content;r.forEachCell((i,l)=>{i.content.eq(a)||n.replace(n.mapping.map(l+1),n.mapping.map(l+i.nodeSize-1),new Un(a,0,0))}),n.docChanged&&t(n)}return!0}function $Yt(s){if(s.size===0)return null;let{content:t,openStart:r,openEnd:n}=s;for(;t.childCount==1&&(r>0&&n>0||t.child(0).type.spec.tableRole=="table");)r--,n--,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(dn.empty),r[a]n&&(x=x.type.createChecked($3(x.attrs,x.attrs.colspan,h+x.attrs.colspan-n),x.content)),d.push(x),h+=x.attrs.colspan;for(let y=1;ya&&(m=m.type.create({...m.attrs,rowspan:Math.max(1,a-m.attrs.rowspan)},m.content)),c.push(m)}i.push(dn.from(c))}r=i,t=a}return{width:s,height:t,rows:r}}function VYt(s,t,r,n,a,i,l){const o=s.doc.type.schema,c=km(o);let d,h;if(a>t.width)for(let m=0,x=0;mt.height){const m=[];for(let v=0,w=(t.height-1)*t.width;v=t.width?!1:r.nodeAt(t.map[w+v]).type==c.header_cell;m.push(b?h||(h=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const x=c.row.create(null,dn.from(m)),y=[];for(let v=t.height;v{if(!a)return!1;const i=r.selection;if(i instanceof pc)return _ce(r,n,pi.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=zit(a,s,t);if(l==null)return!1;if(s=="horiz")return _ce(r,n,pi.near(r.doc.resolve(i.head+t),t));{const o=r.doc.resolve(l),c=Lit(o,s,t);let d;return c?d=pi.near(c,1):t<0?d=pi.near(r.doc.resolve(o.before(-1)),-1):d=pi.near(r.doc.resolve(o.after(-1)),1),_ce(r,n,d)}}}function d$(s,t){return(r,n,a)=>{if(!a)return!1;const i=r.selection;let l;if(i instanceof pc)l=i;else{const c=zit(a,s,t);if(c==null)return!1;l=new pc(r.doc.resolve(c))}const o=Lit(l.$headCell,s,t);return o?_ce(r,n,new pc(l.$anchorCell,o)):!1}}function GYt(s,t){const r=s.state.doc,n=z3(r.resolve(t));return n?(s.dispatch(s.state.tr.setSelection(new pc(n))),!0):!1}function WYt(s,t,r){if(!$y(s.state))return!1;let n=$Yt(r);const a=s.state.selection;if(a instanceof pc){n||(n={width:1,height:1,rows:[dn.from(N2e(km(s.state.schema).cell,r))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=Td.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return n=qYt(n,o.right-o.left,o.bottom-o.top),pBe(s.state,s.dispatch,l,o,n),!0}else if(n){const i=ope(s.state),l=i.start(-1);return pBe(s.state,s.dispatch,l,Td.get(i.node(-1)).findCell(i.pos-l),n),!0}else return!1}function KYt(s,t){var r;if(t.button!=0||t.ctrlKey||t.metaKey)return;const n=xBe(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof pc)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&n&&(a=z3(s.state.selection.$anchor))!=null&&((r=b1e(s,t))===null||r===void 0?void 0:r.pos)!=a.pos)i(a,t),t.preventDefault();else if(!n)return;function i(c,d){let h=b1e(s,d);const m=yw.getState(s.state)==null;if(!h||!Q3e(c,h))if(m)h=c;else return;const x=new pc(c,h);if(m||!s.state.selection.eq(x)){const y=s.state.tr.setSelection(x);m&&y.setMeta(yw,c.pos),s.dispatch(y)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),yw.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(yw,-1))}function o(c){const d=c,h=yw.getState(s.state);let m;if(h!=null)m=s.state.doc.resolve(h);else if(xBe(s,d.target)!=n&&(m=b1e(s,t),!m))return l();m&&i(m,d)}s.root.addEventListener("mouseup",l),s.root.addEventListener("dragstart",l),s.root.addEventListener("mousemove",o)}function zit(s,t,r){if(!(s.state.selection instanceof oi))return null;const{$head:n}=s.state.selection;for(let a=n.depth-1;a>=0;a--){const i=n.node(a);if((r<0?n.index(a):n.indexAfter(a))!=(r<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const l=n.before(a),o=t=="vert"?r>0?"down":"up":r>0?"right":"left";return s.endOfTextblock(o)?l:null}}return null}function xBe(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function b1e(s,t){const r=s.posAtCoords({left:t.clientX,top:t.clientY});if(!r)return null;let{inside:n,pos:a}=r;return n>=0&&z3(s.state.doc.resolve(n))||z3(s.state.doc.resolve(a))}var YYt=class{constructor(t,r){this.node=t,this.defaultCellMinWidth=r,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",`${r}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),k2e(t,this.colgroup,this.table,r),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,k2e(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function k2e(s,t,r,n,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let m=0,x=0;mnew n(m,r,x)),new XYt(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=Fp.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{QYt(l,o,s,a)},mouseleave:l=>{JYt(l)},mousedown:(l,o)=>{eZt(l,o,t,r)}},decorations:l=>{const o=Fp.getState(l);if(o&&o.activeHandle>-1)return aZt(l,o.activeHandle)},nodeViews:{}}});return i}var XYt=class wce{constructor(t,r){this.activeHandle=t,this.dragging=r}apply(t){const r=this,n=t.getMeta(Fp);if(n&&n.setHandle!=null)return new wce(n.setHandle,!1);if(n&&n.setDragging!==void 0)return new wce(r.activeHandle,n.setDragging);if(r.activeHandle>-1&&t.docChanged){let a=t.mapping.map(r.activeHandle,-1);return j2e(t.doc.resolve(a))||(a=-1),new wce(a,r.dragging)}return r}};function QYt(s,t,r,n){if(!s.editable)return;const a=Fp.getState(s.state);if(a&&!a.dragging){const i=sZt(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=r?l=gBe(s,t,"left",r):c-t.clientX<=r&&(l=gBe(s,t,"right",r))}if(l!=a.activeHandle){if(!n&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=Td.get(c),h=o.start(-1);if(d.colCount(o.pos-h)+o.nodeAfter.attrs.colspan-1==d.width-1)return}$it(s,l)}}}function JYt(s){if(!s.editable)return;const t=Fp.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&$it(s,-1)}function eZt(s,t,r,n){var a;if(!s.editable)return!1;const i=(a=s.dom.ownerDocument.defaultView)!==null&&a!==void 0?a:window,l=Fp.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=tZt(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(Fp,{setDragging:{startX:t.clientX,startWidth:c}}));function d(m){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",h);const x=Fp.getState(s.state);x!=null&&x.dragging&&(rZt(s,x.activeHandle,yBe(x.dragging,m,r)),s.dispatch(s.state.tr.setMeta(Fp,{setDragging:null})))}function h(m){if(!m.which)return d(m);const x=Fp.getState(s.state);if(x&&x.dragging){const y=yBe(x.dragging,m,r);vBe(s,x.activeHandle,y,n)}}return vBe(s,l.activeHandle,c,n),i.addEventListener("mouseup",d),i.addEventListener("mousemove",h),t.preventDefault(),!0}function tZt(s,t,{colspan:r,colwidth:n}){const a=n&&n[n.length-1];if(a)return a;const i=s.domAtPos(t);let l=i.node.childNodes[i.offset].offsetWidth,o=r;if(n)for(let c=0;c{const n=s.nodes[r];n.spec.tableRole&&(t[n.spec.tableRole]=n)}),s.cached.tableNodeTypes=t,t}function dZt(s,t,r,n,a){const i=cZt(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!uZt(t))return!1;let r=0;const n=fit(t.ranges[0].$from,i=>i.type.name==="table");return n==null||n.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(r+=1)}),r===t.ranges.length?(s.commands.deleteTable(),!0):!1},hZt=Em.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:oZt,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:s,HTMLAttributes:t}){const{colgroup:r,tableWidth:n,tableMinWidth:a}=lZt(s,this.options.cellMinWidth),i=["table",Wc(this.options.HTMLAttributes,t,{style:n?`width: ${n}`:`min-width: ${a}`}),r,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:r=!0}={})=>({tr:n,dispatch:a,editor:i})=>{const l=dZt(i.schema,s,t,r);if(a){const o=n.selection.from+1;n.replaceSelectionWith(l).scrollIntoView().setSelection(oi.near(n.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>kYt(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>SYt(s,t),deleteColumn:()=>({state:s,dispatch:t})=>TYt(s,t),addRowBefore:()=>({state:s,dispatch:t})=>AYt(s,t),addRowAfter:()=>({state:s,dispatch:t})=>MYt(s,t),deleteRow:()=>({state:s,dispatch:t})=>LYt(s,t),deleteTable:()=>({state:s,dispatch:t})=>zYt(s,t),mergeCells:()=>({state:s,dispatch:t})=>cBe(s,t),splitCell:()=>({state:s,dispatch:t})=>dBe(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>P8("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>P8("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>FYt(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>cBe(s,t)?!0:dBe(s,t),setCellAttribute:(s,t)=>({state:r,dispatch:n})=>RYt(s,t)(r,n),goToNextCell:()=>({state:s,dispatch:t})=>hBe(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>hBe(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&Oit(s),!0),setCellSelection:s=>({tr:t,dispatch:r})=>{if(r){const n=pc.create(t.doc,s.anchorCell,s.headCell);t.setSelection(n)}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:u$,"Mod-Backspace":u$,Delete:u$,"Mod-Delete":u$}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[ZYt({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],iZt({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Qi(ja(s,"tableRole",t))}}}),mZt=Em.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Wc(this.options.HTMLAttributes,s),0]}}),fZt=Em.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(n=>parseInt(n,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",Wc(this.options.HTMLAttributes,s),0]}}),pZt=Em.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(n=>parseInt(n,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",Wc(this.options.HTMLAttributes,s),0]}});function Uy({content:s,onChange:t,placeholder:r="Enter content...",minHeight:n="150px",compact:a=!1}){const[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,h]=k.useState(!0),m=O3e({extensions:[B3e,Y3e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Z3e.configure({types:["heading","paragraph"]}),X3e,cYt.extend({addAttributes(){var w;return{...(w=this.parent)==null?void 0:w.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),hZt.extend({addAttributes(){var w;return{...(w=this.parent)==null?void 0:w.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),mZt.extend({addAttributes(){var w;return{...(w=this.parent)==null?void 0:w.call(this),style:{default:null}}}}),fZt.extend({addAttributes(){var w;return{...(w=this.parent)==null?void 0:w.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),pZt.extend({addAttributes(){var w;return{...(w=this.parent)==null?void 0:w.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:w})=>{t(w.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":r},handlePaste:(w,b)=>{var S;const N=(S=b.clipboardData)==null?void 0:S.items;if(!N)return!1;for(const T of Array.from(N))if(T.type.startsWith("image/")){b.preventDefault();const A=T.getAsFile();if(!A)continue;const I=new FileReader;return I.onload=D=>{var $;const R=($=D.target)==null?void 0:$.result;w.dispatch(w.state.tr.replaceSelectionWith(w.state.schema.nodes.image.create({src:R})))},I.readAsDataURL(A),!0}return!1}}});k.useEffect(()=>{m&&s!==m.getHTML()&&m.commands.setContent(s)},[s,m]);const x=()=>{if(!m)return;const w=m.getAttributes("link").href||"",b=m.getAttributes("link").target;c(w),h(b==="_blank"),l(!0)},y=()=>{m&&(o===""?m.chain().focus().extendMarkRange("link").unsetLink().run():m.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},v=()=>{m&&m.chain().focus().extendMarkRange("link").unsetLink().run()};return m?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(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:1}).run(),className:m.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(pA,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleHeading({level:2}).run(),className:m.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(xA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBold().run(),className:m.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(Yw,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleItalic().run(),className:m.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(tj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleBulletList().run(),className:m.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(em,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().toggleOrderedList().run(),className:m.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(Cy,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("left").run(),className:m.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(E4,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("center").run(),className:m.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(T4,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().setTextAlign("right").run(),className:m.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(A4,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:x,className:m.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(po,{className:"h-4 w-4"})}),m.isActive("link")&&e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:v,title:"Remove Link",children:e.jsx(po,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().undo().run(),disabled:!m.can().undo(),title:"Undo",children:e.jsx(cj,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>m.chain().focus().redo().run(),disabled:!m.can().redo(),title:"Redo",children:e.jsx(oj,{className:"h-4 w-4"})})]}),e.jsx(D3e,{editor:m,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:n}})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"link-url",children:"URL"}),e.jsx(Ne,{id:"link-url",value:o,onChange:w=>c(w.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_r,{id:"link-new-tab",checked:d,onCheckedChange:h}),e.jsx(he,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(an,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:y,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var xZt=Object.defineProperty,gZt=(s,t,r)=>t in s?xZt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,Rc=(s,t,r)=>gZt(s,typeof t!="symbol"?t+"":t,r);const Due={x:0,y:0,width:0,height:0,unit:"px"},eE=(s,t,r)=>Math.min(Math.max(s,t),r),yZt=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),wBe=(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 vZt(s,t,r,n){const a=A0(s,r,n);return s.width&&(a.height=a.width/t),s.height&&(a.width=a.height*t),a.y+a.height>n&&(a.height=n-a.y,a.width=a.height*t),a.x+a.width>r&&(a.width=r-a.x,a.height=a.width/t),s.unit==="%"?ow(a,r,n):a}function bZt(s,t,r){const n=A0(s,t,r);return n.x=(t-n.width)/2,n.y=(r-n.height)/2,s.unit==="%"?ow(n,t,r):n}function ow(s,t,r){return s.unit==="%"?{...Due,...s,unit:"%"}:{unit:"%",x:s.x?s.x/t*100:0,y:s.y?s.y/r*100:0,width:s.width?s.width/t*100:0,height:s.height?s.height/r*100:0}}function A0(s,t,r){return s.unit?s.unit==="px"?{...Due,...s,unit:"px"}:{unit:"px",x:s.x?s.x*t/100:0,y:s.y?s.y*r/100:0,width:s.width?s.width*t/100:0,height:s.height?s.height*r/100:0}:{...Due,...s,unit:"px"}}function jBe(s,t,r,n,a,i=0,l=0,o=n,c=a){const d={...s};let h=Math.min(i,n),m=Math.min(l,a),x=Math.min(o,n),y=Math.min(c,a);t&&(t>1?(h=l?l*t:h,m=h/t,x=o*t):(m=i?i/t:m,h=m*t,y=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,m),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,h),d.x=0);const v=n-(d.x+d.width);v<0&&(d.x=Math.min(d.x,n-h),d.width+=v);const w=a-(d.y+d.height);if(w<0&&(d.y=Math.min(d.y,a-m),d.height+=w),d.widthx&&((r==="sw"||r=="nw")&&(d.x-=x-d.width),d.width=x),d.height>y&&((r==="nw"||r=="ne")&&(d.y-=y-d.height),d.height=y),t){const b=d.width/d.height;if(bt){const N=Math.max(d.height*t,h);(r==="sw"||r=="nw")&&(d.x-=N-d.width),d.width=N}}return d}function _Zt(s,t,r,n){const a={...s};return t==="ArrowLeft"?n==="nw"?(a.x-=r,a.y-=r,a.width+=r,a.height+=r):n==="w"?(a.x-=r,a.width+=r):n==="sw"?(a.x-=r,a.width+=r,a.height+=r):n==="ne"?(a.y+=r,a.width-=r,a.height-=r):n==="e"?a.width-=r:n==="se"&&(a.width-=r,a.height-=r):t==="ArrowRight"&&(n==="nw"?(a.x+=r,a.y+=r,a.width-=r,a.height-=r):n==="w"?(a.x+=r,a.width-=r):n==="sw"?(a.x+=r,a.width-=r,a.height-=r):n==="ne"?(a.y-=r,a.width+=r,a.height+=r):n==="e"?a.width+=r:n==="se"&&(a.width+=r,a.height+=r)),t==="ArrowUp"?n==="nw"?(a.x-=r,a.y-=r,a.width+=r,a.height+=r):n==="n"?(a.y-=r,a.height+=r):n==="ne"?(a.y-=r,a.width+=r,a.height+=r):n==="sw"?(a.x+=r,a.width-=r,a.height-=r):n==="s"?a.height-=r:n==="se"&&(a.width-=r,a.height-=r):t==="ArrowDown"&&(n==="nw"?(a.x+=r,a.y+=r,a.width-=r,a.height-=r):n==="n"?(a.y+=r,a.height-=r):n==="ne"?(a.y+=r,a.width-=r,a.height-=r):n==="sw"?(a.x-=r,a.width+=r,a.height+=r):n==="s"?a.height+=r:n==="se"&&(a.width+=r,a.height+=r)),a}const tE={capture:!0,passive:!1};let wZt=0;const Q_=class ty extends k.PureComponent{constructor(){super(...arguments),Rc(this,"docMoveBound",!1),Rc(this,"mouseDownOnCrop",!1),Rc(this,"dragStarted",!1),Rc(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Rc(this,"componentRef",k.createRef()),Rc(this,"mediaRef",k.createRef()),Rc(this,"resizeObserver"),Rc(this,"initChangeCalled",!1),Rc(this,"instanceId",`rc-${wZt++}`),Rc(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Rc(this,"onCropPointerDown",t=>{const{crop:r,disabled:n}=this.props,a=this.getBox();if(!r)return;const i=A0(r,a.width,a.height);if(n)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,h=i.x,m=i.y;if(l){const x=t.clientX-a.x,y=t.clientY-a.y;let v=0,w=0;l==="ne"||l=="e"?(v=x-(i.x+i.width),w=y-i.y,h=i.x,m=i.y+i.height):l==="se"||l==="s"?(v=x-(i.x+i.width),w=y-(i.y+i.height),h=i.x,m=i.y):l==="sw"||l=="w"?(v=x-i.x,w=y-(i.y+i.height),h=i.x+i.width,m=i.y):(l==="nw"||l=="n")&&(v=x-i.x,w=y-i.y,h=i.x+i.width,m=i.y+i.height),c=h+a.x+v,d=m+a.y+w}this.evData={startClientX:c,startClientY:d,startCropX:h,startCropY:m,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),Rc(this,"onComponentPointerDown",t=>{const{crop:r,disabled:n,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(n||a||i&&r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,h={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(A0(h,o.width,o.height),ow(h,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Rc(this,"onDocPointerMove",t=>{const{crop:r,disabled:n,onChange:a,onDragStart:i}=this.props,l=this.getBox();if(n||!r||!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(),wBe(r,c)||a(A0(c,l.width,l.height),ow(c,l.width,l.height))}),Rc(this,"onComponentKeyDown",t=>{const{crop:r,disabled:n,onChange:a,onComplete:i}=this.props;if(n)return;const l=t.key;let o=!1;if(!r)return;const c=this.getBox(),d=this.makePixelCrop(c),h=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?ty.nudgeStepLarge:t.shiftKey?ty.nudgeStepMedium:ty.nudgeStep;if(l==="ArrowLeft"?(d.x-=h,o=!0):l==="ArrowRight"?(d.x+=h,o=!0):l==="ArrowUp"?(d.y-=h,o=!0):l==="ArrowDown"&&(d.y+=h,o=!0),o){t.cancelable&&t.preventDefault(),d.x=eE(d.x,0,c.width-d.width),d.y=eE(d.y,0,c.height-d.height);const m=A0(d,c.width,c.height),x=ow(d,c.width,c.height);a(m,x),i&&i(m,x)}}),Rc(this,"onHandlerKeyDown",(t,r)=>{const{aspect:n=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:h,onComplete:m}=this.props,x=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 y=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?ty.nudgeStepLarge:t.shiftKey?ty.nudgeStepMedium:ty.nudgeStep,v=A0(a,x.width,x.height),w=_Zt(v,t.key,y,r),b=jBe(w,n,r,x.width,x.height,l,o,c,d);if(!wBe(a,b)){const N=ow(b,x.width,x.height);h(b,N),m&&m(b,N)}}),Rc(this,"onDocPointerDone",t=>{const{crop:r,disabled:n,onComplete:a,onDragEnd:i}=this.props,l=this.getBox();this.unbindDocMove(),!(n||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,i&&i(t),a&&a(A0(r,l.width,l.height),ow(r,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Rc(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:r,y:n,width:a,height:i}=t.getBoundingClientRect();return{x:r,y:n,width:a,height:i}}componentDidUpdate(t){const{crop:r,onComplete:n}=this.props;if(n&&!t.crop&&r){const{width:a,height:i}=this.getBox();a&&i&&n(A0(r,a,i),ow(r,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,tE),this.document.addEventListener("pointerup",this.onDocPointerDone,tE),this.document.addEventListener("pointercancel",this.onDocPointerDone,tE),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,tE),this.document.removeEventListener("pointerup",this.onDocPointerDone,tE),this.document.removeEventListener("pointercancel",this.onDocPointerDone,tE),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,r=this.getBox(),n=this.makePixelCrop(r),a=t.clientX-t.startClientX,i=t.clientY-t.startClientY;return n.x=eE(t.startCropX+a,0,r.width-n.width),n.y=eE(t.startCropY+i,0,r.height-n.height),n}getPointRegion(t,r,n,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&r?c=r==="nw"||r==="n"||r==="ne":c=o1?i?[i,i/r]:[l*r,l]:l?[l*r,l]:[i,i/r]}resizeCrop(){const{evData:t}=this,{aspect:r=0,maxWidth:n,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,r,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),h=t.ord||d;let m=t.clientX-t.startClientX,x=t.clientY-t.startClientY;(l&&h==="nw"||h==="w"||h==="sw")&&(m=Math.min(m,-l)),(o&&h==="nw"||h==="n"||h==="ne")&&(x=Math.min(x,-o));const y={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(y.x=t.startCropX,y.width=m,r?(y.height=y.width/r,y.y=t.startCropY-y.height):(y.height=Math.abs(x),y.y=t.startCropY-y.height)):d==="se"?(y.x=t.startCropX,y.y=t.startCropY,y.width=m,r?y.height=y.width/r:y.height=x):d==="sw"?(y.x=t.startCropX+m,y.y=t.startCropY,y.width=Math.abs(m),r?y.height=y.width/r:y.height=x):d==="nw"&&(y.x=t.startCropX+m,y.width=Math.abs(m),r?(y.height=y.width/r,y.y=t.startCropY-y.height):(y.height=Math.abs(x),y.y=t.startCropY+x));const v=jBe(y,r,d,i.width,i.height,l,o,n,a);return r||ty.xyOrds.indexOf(h)>-1?c=v:ty.xOrds.indexOf(h)>-1?(c.x=v.x,c.width=v.width):ty.yOrds.indexOf(h)>-1&&(c.y=v.y,c.height=v.height),c.x=eE(c.x,0,i.width-c.width),c.y=eE(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=ty.defaultProps.ariaLabels,disabled:r,locked:n,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return wt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!n&&wt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},wt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),wt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),wt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),wt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),wt.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"}),wt.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"}),wt.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"}),wt.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"}),wt.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"}),wt.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"}),wt.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"}),wt.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&&wt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&wt.createElement(wt.Fragment,null,wt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),wt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const r={...Due,...this.props.crop||{}};return A0(r,t.width,t.height)}render(){const{aspect:t,children:r,circularCrop:n,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:h,newCropIsBeingDrawn:m}=this.state,x=i?this.renderCropSelection():null,y=yZt("ReactCrop",a,h&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",m&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&n&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",n&&"ReactCrop--no-animate");return wt.createElement("div",{ref:this.componentRef,className:y,style:c},wt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),i?wt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},wt.createElement("defs",null,wt.createElement("mask",{id:`hole-${this.instanceId}`},wt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),n?wt.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"}):wt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),wt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,x)}};Rc(Q_,"xOrds",["e","w"]),Rc(Q_,"yOrds",["n","s"]),Rc(Q_,"xyOrds",["nw","ne","se","sw"]),Rc(Q_,"nudgeStep",1),Rc(Q_,"nudgeStepMedium",10),Rc(Q_,"nudgeStepLarge",100),Rc(Q_,"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 jZt=Q_;var Uit=["PageUp","PageDown"],qit=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Vit={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},YI="Slider",[C2e,NZt,kZt]=BF(YI),[Hit,UUs]=pd(YI,[kZt]),[SZt,lpe]=Hit(YI),Git=k.forwardRef((s,t)=>{const{name:r,min:n=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[n],value:h,onValueChange:m=()=>{},onValueCommit:x=()=>{},inverted:y=!1,form:v,...w}=s,b=k.useRef(new Set),N=k.useRef(0),T=l==="horizontal"?CZt:TZt,[A=[],I]=Sh({prop:h,defaultProp:d,onChange:Q=>{var X;(X=[...b.current][N.current])==null||X.focus(),m(Q)}}),D=k.useRef(A);function R(Q){const K=LZt(A,Q);z(Q,K)}function $(Q){z(Q,N.current)}function F(){const Q=D.current[N.current];A[N.current]!==Q&&x(A)}function z(Q,K,{commit:X}={commit:!1}){const Z=OZt(i),re=FZt(Math.round((Q-n)/i)*i+n,Z),le=f8(re,[n,a]);I((oe=[])=>{const ne=MZt(oe,le,K);if(RZt(ne,c*i)){N.current=ne.indexOf(le);const ie=String(ne)!==String(oe);return ie&&X&&x(ne),ie?ne:oe}else return oe})}return e.jsx(SZt,{scope:s.__scopeSlider,name:r,disabled:o,min:n,max:a,valueIndexToChangeRef:N,thumbs:b.current,values:A,orientation:l,form:v,children:e.jsx(C2e.Provider,{scope:s.__scopeSlider,children:e.jsx(C2e.Slot,{scope:s.__scopeSlider,children:e.jsx(T,{"aria-disabled":o,"data-disabled":o?"":void 0,...w,ref:t,onPointerDown:Vr(w.onPointerDown,()=>{o||(D.current=A)}),min:n,max:a,inverted:y,onSlideStart:o?void 0:R,onSlideMove:o?void 0:$,onSlideEnd:o?void 0:F,onHomeKeyDown:()=>!o&&z(n,0,{commit:!0}),onEndKeyDown:()=>!o&&z(a,A.length-1,{commit:!0}),onStepKeyDown:({event:Q,direction:K})=>{if(!o){const re=Uit.includes(Q.key)||Q.shiftKey&&qit.includes(Q.key)?10:1,le=N.current,oe=A[le],ne=i*re*K;z(oe+ne,le,{commit:!0})}}})})})})});Git.displayName=YI;var[Wit,Kit]=Hit(YI,{startEdge:"left",endEdge:"right",size:"width",direction:1}),CZt=k.forwardRef((s,t)=>{const{min:r,max:n,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...h}=s,[m,x]=k.useState(null),y=Ga(t,T=>x(T)),v=k.useRef(void 0),w=Kj(a),b=w==="ltr",N=b&&!i||!b&&i;function S(T){const A=v.current||m.getBoundingClientRect(),I=[0,A.width],R=J3e(I,N?[r,n]:[n,r]);return v.current=A,R(T-A.left)}return e.jsx(Wit,{scope:s.__scopeSlider,startEdge:N?"left":"right",endEdge:N?"right":"left",direction:N?1:-1,size:"width",children:e.jsx(Yit,{dir:w,"data-orientation":"horizontal",...h,ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:T=>{const A=S(T.clientX);l==null||l(A)},onSlideMove:T=>{const A=S(T.clientX);o==null||o(A)},onSlideEnd:()=>{v.current=void 0,c==null||c()},onStepKeyDown:T=>{const I=Vit[N?"from-left":"from-right"].includes(T.key);d==null||d({event:T,direction:I?-1:1})}})})}),TZt=k.forwardRef((s,t)=>{const{min:r,max:n,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,h=k.useRef(null),m=Ga(t,h),x=k.useRef(void 0),y=!a;function v(w){const b=x.current||h.current.getBoundingClientRect(),N=[0,b.height],T=J3e(N,y?[n,r]:[r,n]);return x.current=b,T(w-b.top)}return e.jsx(Wit,{scope:s.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1,children:e.jsx(Yit,{"data-orientation":"vertical",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:w=>{const b=v(w.clientY);i==null||i(b)},onSlideMove:w=>{const b=v(w.clientY);l==null||l(b)},onSlideEnd:()=>{x.current=void 0,o==null||o()},onStepKeyDown:w=>{const N=Vit[y?"from-bottom":"from-top"].includes(w.key);c==null||c({event:w,direction:N?-1:1})}})})}),Yit=k.forwardRef((s,t)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,h=lpe(YI,r);return e.jsx(wn.span,{...d,ref:t,onKeyDown:Vr(s.onKeyDown,m=>{m.key==="Home"?(l(m),m.preventDefault()):m.key==="End"?(o(m),m.preventDefault()):Uit.concat(qit).includes(m.key)&&(c(m),m.preventDefault())}),onPointerDown:Vr(s.onPointerDown,m=>{const x=m.target;x.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(x)?x.focus():n(m)}),onPointerMove:Vr(s.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&a(m)}),onPointerUp:Vr(s.onPointerUp,m=>{const x=m.target;x.hasPointerCapture(m.pointerId)&&(x.releasePointerCapture(m.pointerId),i(m))})})}),Zit="SliderTrack",Xit=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=lpe(Zit,r);return e.jsx(wn.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...n,ref:t})});Xit.displayName=Zit;var T2e="SliderRange",Qit=k.forwardRef((s,t)=>{const{__scopeSlider:r,...n}=s,a=lpe(T2e,r),i=Kit(T2e,r),l=k.useRef(null),o=Ga(t,l),c=a.values.length,d=a.values.map(x=>tot(x,a.min,a.max)),h=c>1?Math.min(...d):0,m=100-Math.max(...d);return e.jsx(wn.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...n,ref:o,style:{...s.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}})});Qit.displayName=T2e;var E2e="SliderThumb",Jit=k.forwardRef((s,t)=>{const r=NZt(s.__scopeSlider),[n,a]=k.useState(null),i=Ga(t,o=>a(o)),l=k.useMemo(()=>n?r().findIndex(o=>o.ref.current===n):-1,[r,n]);return e.jsx(EZt,{...s,ref:i,index:l})}),EZt=k.forwardRef((s,t)=>{const{__scopeSlider:r,index:n,name:a,...i}=s,l=lpe(E2e,r),o=Kit(E2e,r),[c,d]=k.useState(null),h=Ga(t,S=>d(S)),m=c?l.form||!!c.closest("form"):!0,x=UF(c),y=l.values[n],v=y===void 0?0:tot(y,l.min,l.max),w=IZt(n,l.values.length),b=x==null?void 0:x[o.size],N=b?PZt(b,v,o.direction):0;return k.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(${v}% + ${N}px)`},children:[e.jsx(C2e.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(wn.span,{role:"slider","aria-label":s["aria-label"]||w,"aria-valuemin":l.min,"aria-valuenow":y,"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:h,style:y===void 0?{display:"none"}:s.style,onFocus:Vr(s.onFocus,()=>{l.valueIndexToChangeRef.current=n})})}),m&&e.jsx(eot,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:y},n)]})});Jit.displayName=E2e;var AZt="RadioBubbleInput",eot=k.forwardRef(({__scopeSlider:s,value:t,...r},n)=>{const a=k.useRef(null),i=Ga(a,n),l=sB(t);return k.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,h=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&h){const m=new Event("input",{bubbles:!0});h.call(o,t),o.dispatchEvent(m)}},[l,t]),e.jsx(wn.input,{style:{display:"none"},...r,ref:i,defaultValue:t})});eot.displayName=AZt;function MZt(s=[],t,r){const n=[...s];return n[r]=t,n.sort((a,i)=>a-i)}function tot(s,t,r){const i=100/(r-t)*(s-t);return f8(i,[0,100])}function IZt(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function LZt(s,t){if(s.length===1)return 0;const r=s.map(a=>Math.abs(a-t)),n=Math.min(...r);return r.indexOf(n)}function PZt(s,t,r){const n=s/2,i=J3e([0,50],[0,n]);return(n-i(t)*r)*r}function DZt(s){return s.slice(0,-1).map((t,r)=>s[r+1]-t)}function RZt(s,t){if(t>0){const r=DZt(s);return Math.min(...r)>=t}return!0}function J3e(s,t){return r=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const n=(t[1]-t[0])/(s[1]-s[0]);return t[0]+n*(r-s[0])}}function OZt(s){return(String(s).split(".")[1]||"").length}function FZt(s,t){const r=Math.pow(10,t);return Math.round(s*r)/r}var sot=Git,BZt=Xit,zZt=Qit,$Zt=Jit;const _y=k.forwardRef(({className:s,...t},r)=>e.jsxs(sot,{ref:r,className:It("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(BZt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(zZt,{className:"absolute h-full bg-primary"})}),e.jsx($Zt,{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"})]}));_y.displayName=sot.displayName;function UZt(s,t,r){return bZt(vZt({unit:"%",width:90},r,s,t),s,t)}const e5e=({open:s,onClose:t,imageSrc:r,onCropComplete:n,aspectRatio:a=1})=>{const i=k.useRef(null),[l,o]=k.useState(),[c,d]=k.useState(),[h,m]=k.useState(1),[x,y]=k.useState(0),v=k.useCallback(N=>{const{width:S,height:T}=N.currentTarget;o(UZt(S,T,a))},[a]),w=k.useCallback(async()=>{const N=i.current;if(!N||!c)return;const S=document.createElement("canvas"),T=S.getContext("2d");if(!T)return;const A=N.naturalWidth/N.width,I=N.naturalHeight/N.height,D=400;S.width=D,S.height=D,T.imageSmoothingQuality="high";const R=c.x*A,$=c.y*I,F=c.width*A,z=c.height*I,Q=x*Math.PI/180,K=S.width/2,X=S.height/2;return T.save(),T.translate(K,X),T.rotate(Q),T.scale(h,h),T.translate(-K,-X),T.drawImage(N,R,$,F,z,0,0,D,D),T.restore(),new Promise((Z,re)=>{S.toBlob(le=>{le?Z(le):re(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,h,x]),b=async()=>{try{const N=await w();N&&(n(N),t())}catch(N){console.error("Error cropping image:",N)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsx(ys,{children:e.jsx(gs,{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(jZt,{crop:l,onChange:(N,S)=>o(S),onComplete:N=>d(N),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:r,alt:"Crop preview",style:{transform:`scale(${h}) rotate(${x}deg)`,maxHeight:"400px",width:"auto"},onLoad:v})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(EA,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(_y,{value:[h],min:.5,max:3,step:.1,onValueChange:([N])=>m(N),className:"flex-1"}),e.jsx(dj,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Q4,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(_y,{value:[x],min:-180,max:180,step:1,onValueChange:([N])=>y(N),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[x,"°"]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(G,{onClick:b,children:"Save Photo"})]})]})})},qZt=()=>{const{user:s}=js(),{toast:t}=Ma(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(null);k.useEffect(()=>{s&&c()},[s]);const c=async()=>{n(!0);try{const{data:m}=await V.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();m&&o({status:m.subscription_status||"none",productId:m.subscription_product_id,endDate:m.subscription_end_date,isGrandfathered:m.is_grandfathered||!1})}catch(m){console.error("Error loading subscription:",m)}finally{n(!1)}},d=async()=>{i(!0);try{const{data:{session:m}}=await V.auth.getSession();if(!m)throw new Error("Not authenticated");const{data:x,error:y}=await V.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${m.access_token}`}});if(y)throw y;x!=null&&x.url&&window.open(x.url,"_blank")}catch(m){console.error("Error opening customer portal:",m),t({title:"Error",description:m.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},h=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Ge,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Ge,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Ge,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Ge,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Ge,{variant:"secondary",children:"Canceled"});default:return e.jsx(Ge,{variant:"outline",children:"No Subscription"})}};return r?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Vp,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Vp,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Nr,{children:"Manage your subscription and billing"})]}),e.jsxs(Pe,{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:h()})]}),(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(G,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Qr,{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."})]})]})},VZt=()=>{const{user:s}=js(),t=br(),{toast:r}=Ma(),[n]=Ac(),a=n.get("setup")==="true",i=n.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:h}=Nrt(),[m,x]=k.useState(!1),[y,v]=k.useState(""),[w,b]=k.useState(!1),[N,S]=k.useState(!1),[T,A]=k.useState(""),[I,D]=k.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[R,$]=k.useState(!1),[F,z]=k.useState(!1),[Q,K]=k.useState({newPassword:"",confirmPassword:""});k.useEffect(()=>{s&&X()},[s]),k.useEffect(()=>{i&&s&&setTimeout(()=>{var ne;(ne=document.getElementById("change-password-section"))==null||ne.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const X=async()=>{var ne,ie,ye;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:ce,error:ve}=await V.from("profiles").select("name, email, phone, digest_opt_out, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(ve)throw console.error("Profile query error:",ve),ve;ce?(console.log("Profile loaded successfully:",ce),D({name:ce.name||"",email:ce.email||"",phone:ce.phone||"",title:ce.title||"",bio:ce.bio||"",areas_served:ce.areas_served||"",years_experience:((ne=ce.years_experience)==null?void 0:ne.toString())||"",instagram_url:ce.instagram_url||"",facebook_url:ce.facebook_url||"",linkedin_url:ce.linkedin_url||"",email_signature:ce.email_signature||"",use_email_signature:ce.use_email_signature||!1}),$(ce.digest_opt_out||!1)):(console.warn("No profile found for user"),D({name:((ie=s.user_metadata)==null?void 0:ie.name)||((ye=s.email)==null?void 0:ye.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}));const{data:be}=await V.storage.from("avatars").list(`${s.id}`);if(be&&be.length>0){const{data:Ue}=V.storage.from("avatars").getPublicUrl(`${s.id}/${be[0].name}`);v(Ue.publicUrl)}}catch(ce){console.error("Error loading profile:",ce),r({title:"Error",description:ce.message||"Failed to load profile",variant:"destructive"})}},Z=ne=>{var ce;const ie=(ce=ne.target.files)==null?void 0:ce[0];if(!ie)return;const ye=new FileReader;ye.onloadend=()=>{A(ye.result),S(!0)},ye.readAsDataURL(ie),ne.target.value=""},re=async ne=>{if(s){b(!0);try{const{data:ie}=await V.storage.from("avatars").list(`${s.id}`);ie&&ie.length>0&&await V.storage.from("avatars").remove(ie.map(Be=>`${s.id}/${Be.name}`));const ce=`${s.id}/avatar.jpg`,{error:ve}=await V.storage.from("avatars").upload(ce,ne,{upsert:!0,contentType:"image/jpeg"});if(ve)throw ve;const{data:be}=V.storage.from("avatars").getPublicUrl(ce),Ue=be.publicUrl;v(`${Ue}?t=${Date.now()}`),await V.from("profiles").update({avatar_url:Ue}).eq("id",s.id),r({title:"Success",description:"Profile photo updated successfully"})}catch(ie){console.error("Error uploading avatar:",ie),r({title:"Error",description:ie.message||"Failed to upload photo",variant:"destructive"})}finally{b(!1)}}},le=async()=>{if(!I.name.trim()||!I.email.trim()){r({title:"Error",description:"Name and email are required",variant:"destructive"});return}x(!0);try{const{error:ne}=await V.from("profiles").update({name:I.name.trim(),email:I.email.trim(),phone:I.phone.trim()||null,title:I.title.trim()||null,bio:I.bio.trim()||null,areas_served:I.areas_served.trim()||null,years_experience:I.years_experience?parseInt(I.years_experience):null,instagram_url:I.instagram_url.trim()||null,facebook_url:I.facebook_url.trim()||null,linkedin_url:I.linkedin_url.trim()||null,email_signature:I.email_signature||"",use_email_signature:I.use_email_signature}).eq("id",s==null?void 0:s.id);if(ne)throw ne;r({title:"Success",description:"Profile updated successfully"})}catch(ne){console.error("Error updating profile:",ne),r({title:"Error",description:ne.message||"Failed to update profile",variant:"destructive"})}finally{x(!1)}},oe=async()=>{if(!Q.newPassword){r({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(Q.newPassword.length<6){r({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(Q.newPassword!==Q.confirmPassword){r({title:"Error",description:"Passwords do not match",variant:"destructive"});return}x(!0);try{const{error:ne}=await V.auth.updateUser({password:Q.newPassword});if(ne)throw ne;r({title:"Success",description:"Password updated successfully"}),K({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ne){console.error("Error updating password:",ne),r({title:"Error",description:ne.message||"Failed to update password",variant:"destructive"})}finally{x(!1)}};return e.jsx(ws,{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(G,{variant:"outline",onClick:()=>{var ne;(ne=document.getElementById("change-password-section"))==null||ne.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(z4,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Profile Photo"}),e.jsx(Nr,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Pe,{className:"flex items-center gap-6",children:[e.jsxs(Nn,{className:"h-24 w-24",children:[e.jsx(ya,{src:y}),e.jsx(kn,{className:"text-2xl",children:I.name.split(" ").map(ne=>ne[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:Z,disabled:w}),e.jsxs(G,{variant:"outline",onClick:()=>{var ne;return(ne=document.getElementById("avatar-upload"))==null?void 0:ne.click()},disabled:w,children:[e.jsx(da,{className:"mr-2 h-4 w-4"}),w?"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(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Personal Information"}),e.jsx(Nr,{children:"Update your profile details"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",value:I.name,onChange:ne=>D({...I,name:ne.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:I.email,onChange:ne=>D({...I,email:ne.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"phone",children:"Phone Number"}),e.jsx(Ne,{id:"phone",type:"tel",value:I.phone,onChange:ne=>D({...I,phone:ne.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(he,{htmlFor:"title",children:"Job Title"}),e.jsx(Ne,{id:"title",value:I.title,onChange:ne=>D({...I,title:ne.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"bio",children:"Bio"}),e.jsx(or,{id:"bio",value:I.bio,onChange:ne=>D({...I,bio:ne.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(he,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(Ne,{id:"areas_served",value:I.areas_served,onChange:ne=>D({...I,areas_served:ne.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(Ne,{id:"years_experience",type:"number",min:"0",value:I.years_experience,onChange:ne=>D({...I,years_experience:ne.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(Ne,{value:I.linkedin_url,onChange:ne=>D({...I,linkedin_url:ne.target.value}),placeholder:"LinkedIn URL"}),e.jsx(Ne,{value:I.instagram_url,onChange:ne=>D({...I,instagram_url:ne.target.value}),placeholder:"Instagram URL"}),e.jsx(Ne,{value:I.facebook_url,onChange:ne=>D({...I,facebook_url:ne.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(G,{onClick:le,disabled:m,children:[e.jsx(Bl,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(D0,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Nr,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Pe,{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:I.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(_r,{checked:I.use_email_signature,onCheckedChange:ne=>D({...I,use_email_signature:ne})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Signature"}),e.jsx(Uy,{content:I.email_signature,onChange:ne=>D({...I,email_signature:ne}),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(G,{onClick:le,disabled:m,children:[e.jsx(Bl,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(ke,{id:"change-password-section",children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:a?"Set Your Password":"Change Password"}),e.jsx(Nr,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"newPassword",children:"New Password"}),e.jsx(Ne,{id:"newPassword",type:"password",value:Q.newPassword,onChange:ne=>K({...Q,newPassword:ne.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(Ne,{id:"confirmPassword",type:"password",value:Q.confirmPassword,onChange:ne=>K({...Q,confirmPassword:ne.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(G,{onClick:oe,disabled:m,children:[e.jsx(Bl,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(G,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[o?e.jsx(_m,{className:"h-5 w-5"}):e.jsx(ev,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Nr,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Pe,{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(_r,{checked:o,onCheckedChange:ne=>{ne?d():h()},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(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[R?e.jsx(_A,{className:"h-5 w-5"}):e.jsx(Vs,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Nr,{children:"Manage your email subscription settings"})]}),e.jsx(Pe,{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:R?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(_r,{checked:!R,onCheckedChange:async ne=>{z(!0);try{const{error:ie}=await V.from("profiles").update({digest_opt_out:!ne}).eq("id",s==null?void 0:s.id);if(ie)throw ie;$(!ne),r({title:ne?"Subscribed":"Unsubscribed",description:ne?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(ie){r({title:"Error",description:ie.message||"Failed to update preference",variant:"destructive"})}finally{z(!1)}},disabled:F})]})})]}),e.jsx(fUt,{}),e.jsx(qZt,{})]}),e.jsx(e5e,{open:N,onClose:()=>S(!1),imageSrc:T,onCropComplete:re,aspectRatio:1})]})})};var HZt="AspectRatio",rot=k.forwardRef((s,t)=>{const{ratio:r=1/1,style:n,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/r}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(wn.div,{...a,ref:t,style:{...n,position:"absolute",top:0,right:0,bottom:0,left:0}})})});rot.displayName=HZt;var GZt=rot;const WZt=GZt;function KZt(){const{user:s}=js(),t=Xt(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),{data:l,isLoading:o}=mt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:w}=await V.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(w)throw w;return v},enabled:!!s&&a}),c=Ct({mutationFn:async()=>{const v=new Uint8Array(12);crypto.getRandomValues(v);const w=btoa(String.fromCharCode(...v)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:b}=await V.from("profiles").update({calendar_token:w}).eq("id",s==null?void 0:s.id);if(b)throw b;return w},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ue.success("Calendar subscription URL generated!")},onError:v=>{ue.error("Failed to generate calendar URL: "+v.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,h=async()=>{d&&(await navigator.clipboard.writeText(d),n(!0),ue.success("Calendar URL copied to clipboard!"),setTimeout(()=>n(!1),2e3))},m=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},x=()=>{if(d){const v=d.replace("https://","webcal://"),w=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(v)}`;window.open(w,"_blank")}},y=()=>{if(d){const v=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(v,"_blank")}};return e.jsxs(fs,{open:a,onOpenChange:i,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Hr,{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(es,{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(Ne,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(G,{variant:"outline",size:"icon",onClick:h,children:r?e.jsx(Kn,{className:"h-4 w-4 text-green-500"}):e.jsx(Ra,{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(G,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,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(Qr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(G,{variant:"outline",className:"w-full justify-start gap-2",onClick:x,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(Qr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(G,{variant:"outline",className:"w-full justify-start gap-2",onClick:y,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(Qr,{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(G,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const YZt={first_timer:Xn,regular:xb,dedicated:Yl,veteran:Gi,streak_master:mc,century:Gi},ZZt={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 NBe(s){return s===1?e.jsx(Gi,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(xb,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Yl,{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 not({showUserStats:s=!0,compact:t=!1,brokerageId:r,title:n="Event Leaderboard"}){const{user:a}=js(),{data:i,isLoading:l}=dnt(t?5:10,r),{data:o}=unt(a==null?void 0:a.id),{data:c}=mnt(a==null?void 0:a.id),{data:d}=hnt(a==null?void 0:a.id);return l?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((h,m)=>e.jsx(Fs,{className:"h-12 w-full"},m))})})]}):e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5 text-yellow-500"}),n]})}),e.jsxs(Pe,{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(Ge,{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(mc,{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(h=>{const m=YZt[h.badge_type]||Xn;return e.jsxs(Ge,{variant:"outline",className:`text-xs ${ZZt[h.badge_type]||""}`,title:h.badge_description||"",children:[e.jsx(m,{className:"h-3 w-3 mr-1"}),h.badge_name]},h.id)}),d.length>4&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(On,{defaultValue:"points",className:"w-full",children:[e.jsxs(Rn,{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(ts,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((h,m)=>{var x,y,v;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${h.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:NBe(m+1)}),e.jsx(Nn,{className:"h-8 w-8",children:e.jsx(kn,{className:"text-xs",children:((y=(x=h.profile)==null?void 0:x.name)==null?void 0:y.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((v=h.profile)==null?void 0:v.name)||"Unknown",h.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:[h.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:h.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},h.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(ts,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((h,m)=>m.total_events_attended-h.total_events_attended).map((h,m)=>{var x,y,v;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${h.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${m===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:NBe(m+1)}),e.jsx(Nn,{className:"h-8 w-8",children:e.jsx(kn,{className:"text-xs",children:((y=(x=h.profile)==null?void 0:x.name)==null?void 0:y.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((v=h.profile)==null?void 0:v.name)||"Unknown",h.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:[h.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:h.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},h.user_id)})})})]})]})]})}function XZt(){const s=br(),{user:t,isAdmin:r}=js(),n=Xt(),{data:a,isLoading:i}=mt({queryKey:["public-events"],queryFn:async()=>{const{data:w,error:b}=await V.from("events").select("*").order("event_date",{ascending:!0});if(b)throw b;return w}}),{data:l}=mt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:w,error:b}=await V.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(b)throw b;return w},enabled:!!t}),{data:o}=mt({queryKey:["event-registration-counts"],queryFn:async()=>{let w=[],b=0;const N=1e3;for(;;){const{data:T,error:A}=await V.from("event_registrations").select("event_id").range(b,b+N-1);if(A)throw A;if(!T||T.length===0||(w=w.concat(T),T.length{S[T.event_id]=(S[T.event_id]||0)+1}),S}}),c=Ct({mutationFn:async w=>{await V.auth.refreshSession();const{data:b,error:N}=await V.functions.invoke("zoom-register",{body:{event_id:w}});if(N)throw N;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:w=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),w!=null&&w.join_url?ue.success("Successfully registered! You'll receive a Zoom confirmation email."):ue.success("Successfully registered for the event!")},onError:w=>{ue.error("Failed to register: "+w.message)}}),d=Ct({mutationFn:async w=>{const{data:b,error:N}=await V.functions.invoke("zoom-unregister",{body:{event_id:w}});if(N)throw N;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{n.invalidateQueries({queryKey:["my-registrations"]}),n.invalidateQueries({queryKey:["event-registration-counts"]}),ue.success("Registration cancelled and removed from Zoom")},onError:w=>{ue.error("Failed to cancel: "+w.message)}}),h=w=>l==null?void 0:l.some(b=>b.event_id===w),m=w=>{const b=l==null?void 0:l.find(N=>N.event_id===w);return b==null?void 0:b.zoom_join_url},x=w=>w.capacity?((o==null?void 0:o[w.id])||0)>=w.capacity:!1,y=(a==null?void 0:a.filter(w=>OA(w.event_date)!=="ended"))||[],v=(a==null?void 0:a.filter(w=>OA(w.event_date)==="ended"))||[];return e.jsx(ws,{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(KZt,{}),r&&e.jsx(G,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${r?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:r?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):y.length===0?e.jsx(ke,{className:"text-center py-12",children:e.jsx(Pe,{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:y.map(w=>{const b=OA(w.event_date),N=n3e(w.event_date),S=b==="live",T=b==="starting_soon";return e.jsxs(ke,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${S?"border-red-500 ring-2 ring-red-500/20":T?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${w.id}`),children:[N&&e.jsxs("div",{className:`${S?"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"})]}),S?e.jsxs(e.Fragment,{children:[e.jsx(gb,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(fn,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),w.image_url&&e.jsx(WZt,{ratio:3/2,className:"overflow-hidden",children:e.jsx("img",{src:w.image_url,alt:w.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"})}),e.jsxs(Mt,{children:[e.jsx(Dt,{className:"line-clamp-2",children:w.title}),w.description&&e.jsx(Nr,{className:"line-clamp-2",children:w.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Pe,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(on,{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(w.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fn,{className:"h-4 w-4"}),_8(new Date(w.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(pr,{className:"h-4 w-4"}),(o==null?void 0:o[w.id])||0," registered",w.capacity&&` / ${w.capacity} spots`]})]}),e.jsx(sO,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:h(w.id)?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(w.id),disabled:d.isPending,children:[e.jsx(vr,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(G,{className:"flex-1",onClick:()=>window.open(m(w.id)||w.zoom_link,"_blank"),children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(G,{className:"w-full",onClick:()=>c.mutate(w.id),disabled:c.isPending||x(w),children:x(w)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Kn,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},w.id)})}),v.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:v.map(w=>e.jsx(ke,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${w.id}`),children:e.jsxs(Mt,{children:[e.jsx(Dt,{className:"text-base line-clamp-1",children:w.title}),e.jsx(Nr,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(w.event_date))})]})},w.id))})]})]}),r&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(not,{showUserStats:!0})})]})]})})}const _1e=[{value:"all",label:"All Roles",icon:pr},{value:"newest",label:"Newest Members",icon:fn},{value:"brokerage_manager",label:"Brokerage Managers",icon:WR},{value:"admin",label:"Admins",icon:Wu}];function QZt({open:s,onOpenChange:t,resourceType:r,resourceId:n,resourceTitle:a}){var Ie,Te;const{user:i,isAdmin:l,isBrokerageManager:o}=js(),[c,d]=k.useState([]),[h,m]=k.useState([]),[x,y]=k.useState([]),[v,w]=k.useState([]),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,I]=k.useState(""),[D,R]=k.useState(!1),[$,F]=k.useState(!1),[z,Q]=k.useState("agents"),[K,X]=k.useState("all"),[Z,re]=k.useState({}),le=l||o;k.useEffect(()=>{s&&i&&(l?oe():ne())},[s,i,l]),k.useEffect(()=>{s||(y([]),w([]),N(""),T(""),I(""),Q("agents"),X("all"))},[s]);const oe=async()=>{if(i){R(!0);try{const{data:xe,error:et}=await V.from("brokerages").select("id, name").order("name");if(et)throw et;const fe=1e3,it={};let Oe=0,Ye=!0;for(;Ye;){const{data:Re,error:tt}=await V.from("profiles").select("brokerage_id").range(Oe*fe,(Oe+1)*fe-1);if(tt)throw tt;Re==null||Re.forEach(Ke=>{Ke.brokerage_id&&(it[Ke.brokerage_id]=(it[Ke.brokerage_id]||0)+1)}),Ye=(Re==null?void 0:Re.length)===fe,Oe++}m((xe==null?void 0:xe.map(Re=>({...Re,agent_count:it[Re.id]||0})))||[]);const We=[];for(Oe=0,Ye=!0;Ye;){const{data:Re,error:tt}=await V.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Oe*fe,(Oe+1)*fe-1);if(tt)throw tt;Re&&We.push(...Re),Ye=(Re==null?void 0:Re.length)===fe,Oe++}const _e={};for(Oe=0,Ye=!0;Ye;){const{data:Re,error:tt}=await V.from("user_roles").select("user_id, role").range(Oe*fe,(Oe+1)*fe-1);if(tt)throw tt;Re==null||Re.forEach(Ke=>{_e[Ke.user_id]||(_e[Ke.user_id]=[]),_e[Ke.user_id].push(Ke.role)}),Ye=(Re==null?void 0:Re.length)===fe,Oe++}re(_e),d(We.map(Re=>{var tt;return{id:Re.id,name:Re.name,email:Re.email,brokerage_name:((tt=Re.brokerages)==null?void 0:tt.name)||"No Brokerage",roles:_e[Re.id]||[],created_at:Re.created_at}}))}catch(xe){console.error("Error loading data:",xe),ue.error("Failed to load agents and brokerages")}finally{R(!1)}}},ne=async()=>{if(i){R(!0);try{const{data:xe}=await V.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(xe!=null&&xe.brokerage_id)){ue.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:et,error:fe}=await V.from("profiles").select("id, name, email").eq("brokerage_id",xe.brokerage_id).neq("id",i.id).order("name");if(fe)throw fe;d(et||[])}catch(xe){console.error("Error loading agents:",xe),ue.error("Failed to load agents")}finally{R(!1)}}},ie=c.filter(xe=>{var fe;const et=xe.name.toLowerCase().includes(b.toLowerCase())||xe.email.toLowerCase().includes(b.toLowerCase())||((fe=xe.brokerage_name)==null?void 0:fe.toLowerCase().includes(b.toLowerCase()));if(l&&K!=="all"&&K!=="newest"){const it=Z[xe.id]||[];return et&&it.includes(K)}return et}).sort((xe,et)=>K==="newest"?(et.created_at||"").localeCompare(xe.created_at||""):0),ye=h.filter(xe=>xe.name.toLowerCase().includes(S.toLowerCase())),ce=()=>{x.length===ie.length?y([]):y(ie.map(xe=>xe.id))},ve=()=>{v.length===ye.length?w([]):w(ye.map(xe=>xe.id))},be=xe=>{if(!le){y([xe]);return}y(et=>et.includes(xe)?et.filter(fe=>fe!==xe):[...et,xe])},Ue=xe=>{w(et=>et.includes(xe)?et.filter(fe=>fe!==xe):[...et,xe])},Be=async()=>{if(!(x.length>0||v.length>0)){ue.error("Please select at least one agent or brokerage to share with");return}F(!0);try{const{data:et,error:fe}=await V.functions.invoke("send-share-notification",{body:{recipientIds:x,brokerageIds:v,resourceType:r,resourceId:n,resourceTitle:a,message:A.trim()||void 0}});if(fe)throw fe;const it=(et==null?void 0:et.sharesCreated)||x.length;ue.success(`Shared with ${it} agent${it!==1?"s":""}`),t(!1)}catch(et){console.error("Error sharing resource:",et),ue.error("Failed to share resource")}finally{F(!1)}},De=xe=>xe.split(" ").map(et=>et[0]).join("").toUpperCase().slice(0,2),Ae=xe=>{const et=Z[xe]||[];return et.includes("admin")?e.jsx(Ge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):et.includes("brokerage_manager")?e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},He=x.length+v.length,Le=K!=="all"&&K!=="newest"?ie.length:null;return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(ys,{className:"flex-shrink-0",children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Hr,{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(On,{value:z,onValueChange:Q,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Rn,{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(pr,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),x.length>0&&e.jsx(Ge,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:x.length})]}),e.jsxs(Kt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),v.length>0&&e.jsx(Ge,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:v.length})]})]}),e.jsxs(ts,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or brokerage...",value:b,onChange:xe=>N(xe.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:K,onValueChange:X,children:[e.jsxs(As,{className:"w-[180px]",children:[e.jsx(Sy,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Ls,{placeholder:"Filter by role"})]}),e.jsx(Ms,{children:_1e.map(xe=>e.jsx(ct,{value:xe.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xe.icon,{className:"h-4 w-4"}),e.jsx("span",{children:xe.label})]})},xe.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:ce,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1.5"}),x.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Le!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Le," ",(Ie=_1e.find(xe=>xe.value===K))==null?void 0:Ie.label]}),e.jsxs("span",{className:"font-medium",children:[x.length," selected"]})]})]}),e.jsx(Qa,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(pr,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:K!=="all"?`No ${(Te=_1e.find(xe=>xe.value===K))==null?void 0:Te.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ie.map(xe=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${x.includes(xe.id)?"bg-accent":""}`,onClick:()=>be(xe.id),children:[e.jsx(Si,{checked:x.includes(xe.id),onCheckedChange:()=>be(xe.id),className:"flex-shrink-0"}),e.jsx(Nn,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(kn,{className:"text-xs bg-primary/10 text-primary",children:De(xe.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:xe.name}),Ae(xe.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[xe.email,xe.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",xe.brokerage_name]})]})]})]},xe.id))})})]}),e.jsxs(ts,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search brokerages...",value:S,onChange:xe=>T(xe.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:ve,className:"text-xs h-8",disabled:ye.length===0,children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1.5"}),v.length===ye.length&&ye.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[v.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(Qa,{className:"h-[250px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ye.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Sa,{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:ye.map(xe=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${v.includes(xe.id)?"bg-accent":""}`,onClick:()=>Ue(xe.id),children:[e.jsx(Si,{checked:v.includes(xe.id),onCheckedChange:()=>Ue(xe.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(Sa,{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:xe.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[xe.agent_count," agent",xe.agent_count!==1?"s":""]})]})]},xe.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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:b,onChange:xe=>N(xe.target.value),className:"pl-9"})]}),le&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:ce,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1.5"}),x.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[x.length," selected"]})]}),e.jsx(Qa,{className:"h-[300px] border rounded-lg",children:D?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(pr,{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:ie.map(xe=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${x.includes(xe.id)?"bg-accent":""}`,onClick:()=>be(xe.id),children:[e.jsx(Si,{checked:x.includes(xe.id),onCheckedChange:()=>be(xe.id),className:"flex-shrink-0"}),e.jsx(Nn,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(kn,{className:"text-xs bg-primary/10 text-primary",children:De(xe.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:xe.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:xe.email})]})]},xe.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(he,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(or,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:xe=>I(xe.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:Be,disabled:He===0||$,children:$?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function ZI({resourceType:s,resourceId:t,resourceTitle:r,variant:n="outline",size:a="sm",className:i=""}){const[l,o]=k.useState(!1),{user:c}=js();return c?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:n,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(QZt,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:r})]}):null}function JZt(){const{eventId:s}=Ki(),t=br(),{user:r}=js(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(0),[d,h]=k.useState(!0),[m,x]=k.useState(!1);k.useEffect(()=>{s&&y()},[s,r]);const y=async()=>{try{const{data:T,error:A}=await V.from("events").select("*").eq("id",s).single();if(A)throw A;a(T);const{count:I}=await V.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(I||0),r){const{data:D}=await V.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",r.id).maybeSingle();l(D)}}catch(T){console.error("Error loading event:",T),ue.error("Failed to load event"),t("/events")}finally{h(!1)}},v=async()=>{if(!(!r||!n)){x(!0);try{const{error:T}=await V.auth.refreshSession();if(T){console.error("Session refresh failed:",T),ue.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await V.functions.invoke("zoom-unregister",{body:{event_id:n.id}});if(A)throw A;ue.success("Successfully cancelled registration"),l(null),c(I=>I-1)}else{const{data:A,error:I}=await V.functions.invoke("zoom-register",{body:{event_id:n.id}});if(I)throw I;ue.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(D=>D+1)}}catch(T){console.error("Registration error:",T),ue.error(i?"Failed to cancel registration":"Failed to register for event")}finally{x(!1)}}},w=T=>{var A,I,D;if(T.includes("iframe.mediadelivery.net")||T.includes("video.bunnycdn.com")){const R=T.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(R)return`https://iframe.mediadelivery.net/embed/${R[1]}/${R[2]}?autoplay=false&preload=true`}if(T.includes("youtube.com")||T.includes("youtu.be")){const R=T.includes("youtu.be")?(A=T.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(I=T.split("v=")[1])==null?void 0:I.split("&")[0];if(R)return`https://www.youtube.com/embed/${R}`}if(T.includes("vimeo.com")){const R=(D=T.split("vimeo.com/")[1])==null?void 0:D.split("?")[0];if(R)return`https://player.vimeo.com/video/${R}`}return T};if(d)return e.jsx(ws,{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(!n)return e.jsx(ws,{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(G,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const b=hv(new Date(n.event_date)),N=n.capacity&&o>=n.capacity,S=(i==null?void 0:i.zoom_join_url)||n.zoom_link;return e.jsx(ws,{title:n.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(G,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Events"]}),n.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:n.image_url,alt:n.title,className:"w-full h-full object-cover"}),b&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Ge,{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:n.title}),e.jsx(ZI,{resourceType:"event",resourceId:n.id,resourceTitle:n.title})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground dark:prose-invert",dangerouslySetInnerHTML:{__html:n.description}})]}),n.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(rf,{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:w(n.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(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(on,{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(n.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:_8(new Date(n.event_date))})]})]}),n.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(pr,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",n.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(di,{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:[!b&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(G,{className:"w-full gap-2",onClick:()=>window.open(S,"_blank"),children:[e.jsx(Qr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(G,{variant:"outline",className:"w-full",onClick:v,disabled:m,children:[m?e.jsx(es,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(G,{className:"w-full gap-2",onClick:v,disabled:m||(N??!1),children:m?e.jsx(es,{className:"h-4 w-4 animate-spin"}):N?"Event Full":"Register Now"})}),b&&i&&e.jsxs(G,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(n.zoom_link,"_blank"),children:[e.jsx(Qr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const eXt=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(Jr,{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(Vp,{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(Ty,{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(ln,{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(bh,{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(jr,{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(gh,{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(en,{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(D0,{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(AR,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"}],tXt=()=>{const{user:s,isAdmin:t}=js(),r=br(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,h]=k.useState("all"),[m,x]=k.useState(new Set),[y,v]=k.useState(new Set);k.useEffect(()=>{w()},[s]);const w=async()=>{try{const{data:F}=await V.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),z=(F==null?void 0:F.map(ie=>ie.tag))||[],{data:Q,error:K}=await V.from("app_tiles").select("*").order("name");if(K)throw K;const[{data:X},{data:Z}]=await Promise.all([V.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),V.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id)]),re=new Set((X==null?void 0:X.map(ie=>ie.app_id))||[]);x(re);const le=new Set((Z||[]).map(ie=>ie.tool_id));v(le);const ne=((Q==null?void 0:Q.filter(ie=>!ie.required_tags||ie.required_tags.length===0?!0:ie.required_tags.some(ye=>z.includes(ye))))||[]).sort((ie,ye)=>ie.name==="LevelUp Members Portal"?-1:ye.name==="LevelUp Members Portal"?1:0);a(ne)}catch(F){console.error("Error loading apps:",F),ue.error("Failed to load apps")}finally{l(!1)}},b=async F=>{var Q;const z=window.open("about:blank","_blank");try{const{data:K,error:X}=await V.auth.getSession();if(X||!K.session){z==null||z.close(),ue.error("Session expired. Please refresh the page and try again.");return}const Z=K.session.access_token;await V.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:F.app_id,app_name:F.name,user_agent:navigator.userAgent});const{data:re,error:le}=await V.functions.invoke("sso-launch",{body:{app_id:F.app_id},headers:{Authorization:`Bearer ${Z}`}});if(le)throw le;re!=null&&re.redirect_url?z&&!z.closed?(z.location.href=re.redirect_url,(Q=z.focus)==null||Q.call(z)):window.location.assign(re.redirect_url):(z==null||z.close(),ue.error("Launch link unavailable"))}catch(K){z==null||z.close(),console.error("Error launching app:",K),ue.error("Failed to launch app. Please try again.")}},N=async(F,z)=>{F.stopPropagation();const Q=m.has(z);try{if(Q){const{error:K}=await V.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",z);if(K)throw K;x(X=>{const Z=new Set(X);return Z.delete(z),Z}),ue.success("Removed from favorites")}else{const{error:K}=await V.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:z});if(K)throw K;x(X=>new Set(X).add(z)),ue.success("Added to favorites")}}catch(K){console.error("Error toggling favorite:",K),ue.error("Failed to update favorites")}},S=async(F,z)=>{F.stopPropagation();const Q=y.has(z);try{if(Q){const{error:K}=await V.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",z);if(K)throw K;v(X=>{const Z=new Set(X);return Z.delete(z),Z}),ue.success("Removed from favorites")}else{const{error:K}=await V.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:z});if(K)throw K;v(X=>new Set(X).add(z)),ue.success("Added to favorites")}}catch(K){console.error("Error toggling tool favorite:",K),ue.error("Failed to update favorites")}},T=n.filter(F=>{var Q;const z=F.name.toLowerCase().includes(o.toLowerCase())||((Q=F.description)==null?void 0:Q.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?z&&m.has(F.id):z}),A=eXt.filter(F=>{if(F.adminOnly&&!t)return!1;const z=F.name.toLowerCase().includes(o.toLowerCase())||F.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?z&&y.has(F.id):z}),I=A.reduce((F,z)=>(F[z.category]||(F[z.category]=[]),F[z.category].push(z),F),{}),D=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(ws,{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 R=d==="all"||d==="tools"||d==="favorites",$=d==="all"||d==="apps"||d==="favorites";return e.jsxs(ws,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:F=>c(F.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:D.map(F=>e.jsxs("button",{onClick:()=>h(F.id),className:It("pb-3 text-sm font-medium transition-colors relative",d===F.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[F.label,d===F.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},F.id))}),R&&Object.keys(I).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(Ay,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(I).map(([F,z])=>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:F})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:z.map(Q=>{const K=y.has(Q.id);return e.jsxs("div",{onClick:()=>r(Q.path),className:It("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",Q.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[Q.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:It("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",Q.color||"bg-primary/10 text-primary"),children:Q.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:[Q.name,Q.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:Q.description})]}),e.jsx("button",{className:It("flex-shrink-0 p-1 transition-colors",K?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:X=>S(X,Q.id),children:e.jsx(ag,{className:It("h-5 w-5",K&&"fill-current")})})]},Q.id)})})]},F))]}),$&&e.jsxs("div",{children:[d==="all"&&T.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(Qr,{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"&&A.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(ag,{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(Hc,{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(G,{className:"mt-4",onClick:()=>r("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:T.map(F=>{const z=m.has(F.id),Q=F.name.toLowerCase().includes("agent review")||F.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(F),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:F.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:F.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:F.description})]}),e.jsx("button",{className:It("flex-shrink-0 p-1 transition-colors",z?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:K=>N(K,F.id),children:e.jsx(ag,{className:It("h-5 w-5",z&&"fill-current")})})]}),Q&&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 →"})]},F.id)})})]}),R&&$&&T.length===0&&A.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(yn,{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"})]})]})},sXt=()=>{var T;const s=br(),{isAdmin:t}=js(),[r,n]=k.useState(""),[a,i]=k.useState("all"),[l,o]=k.useState("all"),[c,d]=k.useState("grid"),{data:h=[]}=mt({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:I}=await V.from("template_categories").select("*").order("name");if(I)throw I;return A}}),{data:m=[]}=mt({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:I}=await V.from("template_types").select("*").order("name");if(I)throw I;return A}}),{data:x=[],isLoading:y}=mt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:I}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(I)throw I;const{data:D,error:R}=await V.from("template_links").select("*").order("sort_order");if(R)throw R;const $=async re=>{let oe=0;const ne=[];for(;;){const{data:ie,error:ye}=await re().range(oe,oe+1e3-1);if(ye)throw ye;if(!ie||ie.length===0||(ne.push(...ie),ie.length<1e3))break;oe+=1e3}return ne},F=await $(()=>V.from("template_likes").select("template_id")),z=await $(()=>V.from("template_comments").select("template_id")),Q=new Map;F.forEach(re=>{Q.set(re.template_id,(Q.get(re.template_id)||0)+1)});const K=new Map;z.forEach(re=>{K.set(re.template_id,(K.get(re.template_id)||0)+1)});const X=new Map;return t&&(await $(()=>V.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(le=>{X.set(le.resource_id,(X.get(le.resource_id)||0)+1)}),(A||[]).map(re=>({...re,links:(D||[]).filter(le=>le.template_id===re.id)||[],likesCount:Q.get(re.id)||0,commentsCount:K.get(re.id)||0,viewsCount:X.get(re.id)||0}))}}),v=x.filter(A=>{var $;const I=A.name.toLowerCase().includes(r.toLowerCase())||(($=A.description)==null?void 0:$.toLowerCase().includes(r.toLowerCase())),D=a==="all"||A.category_id===a,R=l==="all"||A.type_id===l;return I&&D&&R}),w=()=>{n(""),i("all"),o("all")},b=r||a!=="all"||l!=="all",N=(T=[...x].sort((A,I)=>new Date(I.publish_date||I.created_at).getTime()-new Date(A.publish_date||A.created_at).getTime())[0])==null?void 0:T.id,S=A=>{s(`/templates/${A}`)};return e.jsx(ws,{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"})]}),!y&&x.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(Xn,{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:x.filter(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>S(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===N&&e.jsx(Ge,{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(Pe,{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:r8(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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search templates...",value:r,onChange:A=>n(A.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:a,onValueChange:i,children:[e.jsx(As,{className:"w-full sm:w-48",children:e.jsx(Ls,{placeholder:"All Categories"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Categories"}),h.map(A=>e.jsx(ct,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(Is,{value:l,onValueChange:o,children:[e.jsx(As,{className:"w-full sm:w-48",children:e.jsx(Ls,{placeholder:"All Types"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),m.map(A=>e.jsx(ct,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[b&&e.jsx(G,{variant:"outline",size:"sm",onClick:w,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(G,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(em,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[v.length," template",v.length!==1?"s":""," found"]}),y&&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,I)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(Fs,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Fs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Fs,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Fs,{className:"h-5 w-16"}),e.jsx(Fs,{className:"h-5 w-20"})]})]})},I))}),!y&&v.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:b?"No templates match your filters":"No templates available yet"}),b&&e.jsx(G,{variant:"outline",onClick:w,children:"Clear Filters"})]}),!y&&v.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:v.map(A=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>S(A.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[A.id===N&&e.jsx(Ge,{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(Ge,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(po,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(Pe,{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:r8(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(Ge,{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(jh,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jl,{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(bn,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(G,{size:"sm",className:"w-full gap-2",onClick:I=>{I.stopPropagation(),S(A.id)},children:[e.jsx(Qr,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var rXt="Separator",kBe="horizontal",nXt=["horizontal","vertical"],aot=k.forwardRef((s,t)=>{const{decorative:r,orientation:n=kBe,...a}=s,i=aXt(n)?n:kBe,o=r?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(wn.div,{"data-orientation":i,...o,...a,ref:t})});aot.displayName=rXt;function aXt(s){return nXt.includes(s)}var iot=aot;const fo=k.forwardRef(({className:s,orientation:t="horizontal",decorative:r=!0,...n},a)=>e.jsx(iot,{ref:a,decorative:r,orientation:t,className:It("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...n}));fo.displayName=iot.displayName;const iXt=()=>{const{templateId:s}=Ki(),t=br(),{user:r,isAdmin:n}=js(),{toast:a}=Ma(),i=Xt(),{trackEngagement:l}=GI(),[o,c]=k.useState(""),{data:d,isLoading:h}=mt({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:I}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(I)throw I;const{data:D}=await V.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:R}=await V.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:D||[],guides:R||[]}},enabled:!!s}),{data:m=[]}=mt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:I}=await V.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(I)throw I;return(A||[]).map(D=>D.resource_kits).filter(Boolean)},enabled:!!s});k.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:x=[]}=mt({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:I}=await V.from("template_likes").select("*").eq("template_id",s);if(I)throw I;return A},enabled:!!s}),{data:y=[]}=mt({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:I}=await V.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(I)throw I;const D=[...new Set(A.map(F=>F.user_id))],{data:R}=await V.from("profiles").select("id, name").in("id",D),$=new Map((R==null?void 0:R.map(F=>[F.id,F.name]))||[]);return A.map(F=>({...F,user_name:$.get(F.user_id)||"Unknown User"}))},enabled:!!s}),v=Ct({mutationFn:async A=>{const{error:I}=await V.from("template_comments").insert({template_id:s,user_id:r.id,content:A});if(I)throw I},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:A=>{a({title:"Error adding comment",description:A.message,variant:"destructive"})}}),w=Ct({mutationFn:async A=>{const{error:I}=await V.from("template_comments").delete().eq("id",A);if(I)throw I},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),b=Ct({mutationFn:async()=>{const A=x.find(I=>I.user_id===(r==null?void 0:r.id));if(A){const{error:I}=await V.from("template_likes").delete().eq("id",A.id);if(I)throw I}else{const{error:I}=await V.from("template_likes").insert({template_id:s,user_id:r.id});if(I)throw I}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),N=x.some(A=>A.user_id===(r==null?void 0:r.id)),S=A=>A.split(" ").map(I=>I[0]).join("").toUpperCase().slice(0,2),T=A=>{A.preventDefault(),!(!o.trim()||!r)&&v.mutate(o.trim())};return h?e.jsx(ws,{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(ws,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/templates",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Templates"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:d.name}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[d.category&&e.jsx(Ge,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Ge,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(G,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Yn,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(ZI,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(G,{variant:N?"default":"outline",className:"gap-2 rounded-full",onClick:()=>b.mutate(),disabled:!r||b.isPending,children:[e.jsx(jh,{className:`h-4 w-4 ${N?"fill-current":""}`}),x.length," ",x.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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(po,{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(G,{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(Qr,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>e.jsxs(G,{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(ln,{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(Ya,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),m.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Il,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:m.map(A=>e.jsxs(G,{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(Il,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Jl,{className:"h-5 w-5"}),"Comments (",y.length,")"]}),r?e.jsxs("form",{onSubmit:T,className:"flex gap-2",children:[e.jsx(or,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||v.isPending,children:e.jsx(en,{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:y.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):y.map(A=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(kn,{className:"text-sm",children:S(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:rl(new Date(A.created_at),{addSuffix:!0})}),A.user_id===(r==null?void 0:r.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>w.mutate(A.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(ws,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(po,{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(G,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/templates",children:"Back to Templates"})})]})})},oXt=()=>{const{user:s}=js(),[t,r]=k.useState(""),[n,a]=k.useState("all"),{data:i=[]}=mt({queryKey:["academy-categories"],queryFn:async()=>{const{data:x,error:y}=await V.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(y)throw y;return x}}),{data:l=[],isLoading:o}=mt({queryKey:["academy-videos"],queryFn:async()=>{const{data:x,error:y}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;const{data:v,error:w}=await V.from("academy_resources").select("*").order("sort_order");if(w)throw w;return x.map(N=>({...N,resources:(v==null?void 0:v.filter(S=>S.video_id===N.id))||[]}))}}),{data:c=[]}=mt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:x,error:y}=await V.from("academy_video_likes").select("video_id, user_id");if(y)throw y;return x}}),d=l.filter(x=>{var w;const y=t===""||x.title.toLowerCase().includes(t.toLowerCase())||((w=x.description)==null?void 0:w.toLowerCase().includes(t.toLowerCase())),v=n==="all"||x.category_id===n;return y&&v}),h=x=>c.filter(y=>y.video_id===x).length,m=x=>c.some(y=>y.video_id===x&&y.user_id===(s==null?void 0:s.id));return e.jsx(ws,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos...",value:t,onChange:x=>r(x.target.value),className:"pl-10"})]})}),e.jsx(On,{value:n,onValueChange:a,children:e.jsxs(Rn,{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(x=>e.jsx(Kt,{value:x.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:x.name},x.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(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Jr,{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(x=>e.jsx(Yn,{to:`/academy/${x.id}`,children:e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[x.thumbnail_url?e.jsx("img",{src:x.thumbnail_url,alt:x.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Jr,{className:"h-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(Uo,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),x.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(fn,{className:"h-3 w-3"}),x.duration]})]}),e.jsxs(Mt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Dt,{className:"text-lg line-clamp-2",children:x.title})}),x.category&&e.jsx(Ge,{variant:"secondary",className:"w-fit",children:x.category.name})]}),e.jsxs(Pe,{className:"pt-0",children:[x.description&&e.jsx(Nr,{className:"line-clamp-2",children:x.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(jh,{className:`h-4 w-4 ${m(x.id)?"fill-primary text-primary":""}`}),h(x.id)]}),x.resources&&x.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4"}),x.resources.length]})]})]})]})},x.id))})]})})};function oot({resourceType:s,resourceId:t}){const{data:r=[]}=mt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:n,error:a}=await V.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(n||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:n,error:a}=await V.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(n||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return r.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:r.map(n=>e.jsx(Yn,{to:`/templates/${n.id}`,children:e.jsxs(Ge,{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"}),n.name]})},n.id))})]})}const lXt=(s,t)=>{if(t==="bunny_stream"){let r=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return r.includes("?")||(r+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),r}if(t==="youtube"){const r=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,n=s.match(r);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const r=/vimeo\.com\/(?:video\/)?(\d+)/,n=s.match(r);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const r=/loom\.com\/share\/([a-zA-Z0-9]+)/,n=s.match(r);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},cXt=()=>{const{videoId:s}=Ki();br();const{user:t,isAdmin:r}=js(),{toast:n}=Ma(),a=Xt(),{trackEngagement:i}=GI(),[l,o]=k.useState(""),{data:c,isLoading:d}=mt({queryKey:["academy-video",s],queryFn:async()=>{const{data:T,error:A}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:I}=await V.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...T,resources:I||[]}},enabled:!!s});k.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:h=[]}=mt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:T,error:A}=await V.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return T},enabled:!!s}),{data:m=[]}=mt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:T,error:A}=await V.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const I=[...new Set(T.map($=>$.user_id))],{data:D}=await V.from("profiles").select("id, name").in("id",I),R=new Map((D==null?void 0:D.map($=>[$.id,$.name]))||[]);return T.map($=>({...$,user_name:R.get($.user_id)||"Unknown User"}))},enabled:!!s}),x=Ct({mutationFn:async T=>{const{error:A}=await V.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:T});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),n({title:"Comment added!"})},onError:T=>{n({title:"Error adding comment",description:T.message,variant:"destructive"})}}),y=Ct({mutationFn:async T=>{const{error:A}=await V.from("academy_video_comments").delete().eq("id",T);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),n({title:"Comment deleted"})}}),v=Ct({mutationFn:async()=>{const T=h.find(A=>A.user_id===(t==null?void 0:t.id));if(T){const{error:A}=await V.from("academy_video_likes").delete().eq("id",T.id);if(A)throw A}else{const{error:A}=await V.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),w=h.some(T=>T.user_id===(t==null?void 0:t.id)),b=T=>{switch(T==null?void 0:T.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},N=T=>T.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),S=T=>{T.preventDefault(),!(!l.trim()||!t)&&x.mutate(l.trim())};return d?e.jsx(ws,{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(ws,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/academy",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Academy"]})}),e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-black",style:{paddingTop:"56.25%"},children:["youtube","vimeo","loom","bunny_stream"].includes(c.video_type)?e.jsx("iframe",{src:lXt(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(Jr,{className:"h-16 w-16 opacity-50"}),e.jsx(G,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(Qr,{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(Ge,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsx(G,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Yn,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(ZI,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(G,{variant:w?"default":"outline",className:"gap-2 w-fit",onClick:()=>v.mutate(),disabled:!t||v.isPending,children:[e.jsx(jh,{className:`h-4 w-4 ${w?"fill-current":""}`}),h.length," ",h.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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(T=>e.jsxs("a",{href:T.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:b(T.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:T.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:T.file_type})]}),e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground"})]},T.id))})]})}),e.jsx(oot,{resourceType:"academy_video",resourceId:c.id}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Jl,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(or,{placeholder:"Add a comment...",value:l,onChange:T=>o(T.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||x.isPending,children:e.jsx(en,{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:m.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(T=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(kn,{className:"text-sm",children:N(T.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:T.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:rl(new Date(T.created_at),{addSuffix:!0})}),T.user_id===(t==null?void 0:t.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>y.mutate(T.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:T.content})]})]})})},T.id))})]})]})}):e.jsx(ws,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Jr,{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(G,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/academy",children:"Back to Academy"})})]})})};function dXt(){const s=br(),[t,r]=k.useState(""),{data:n,isLoading:a}=mt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:y,error:v}=await V.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return y}}),{data:i}=mt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:y,error:v}=await V.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(v)throw v;return y}}),{data:l}=mt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:y,error:v}=await V.from("resource_kit_likes").select("kit_id");if(v)throw v;return y}}),{data:o}=mt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:y,error:v}=await V.from("resource_kit_comments").select("kit_id");if(v)throw v;return y}}),c=n==null?void 0:n.filter(y=>{var v;return y.name.toLowerCase().includes(t.toLowerCase())||((v=y.description)==null?void 0:v.toLowerCase().includes(t.toLowerCase()))}),d=y=>(i==null?void 0:i.filter(v=>v.kit_id===y))||[],h=y=>(l==null?void 0:l.filter(v=>v.kit_id===y).length)||0,m=y=>(o==null?void 0:o.filter(v=>v.kit_id===y).length)||0,x=y=>{s(`/toolbox/${y}`)};return e.jsx(ws,{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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search resource kits...",value:t,onChange:y=>r(y.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((y,v)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(Fs,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Fs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Fs,{className:"h-4 w-full mb-4"}),e.jsx(Fs,{className:"h-4 w-2/3"})]})},v))}):(c==null?void 0:c.length)===0?e.jsxs(ke,{className:"p-12 text-center",children:[e.jsx(Il,{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(y=>{const v=d(y.id).length,w=h(y.id),b=m(y.id);return e.jsxs(ke,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>x(y.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:y.featured_image_url?e.jsx("img",{src:y.featured_image_url,alt:y.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(Il,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:y.name}),y.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:r8(y.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(ln,{className:"h-4 w-4"}),v," file",v!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jh,{className:"h-3.5 w-3.5"}),w]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),b]})]})]})]})]},y.id)})})]})})}const uXt=()=>{const{kitId:s}=Ki(),{user:t,isAdmin:r}=js(),{toast:n}=Ma(),a=Xt(),{trackEngagement:i}=GI(),[l,o]=k.useState(""),{data:c,isLoading:d}=mt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:T,error:A}=await V.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:I}=await V.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:D}=await V.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...T,files:I||[],links:D||[]}},enabled:!!s});k.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:h=[]}=mt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:T,error:A}=await V.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return T},enabled:!!s}),{data:m=[]}=mt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:T,error:A}=await V.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const I=[...new Set(T.map($=>$.user_id))],{data:D}=await V.from("profiles").select("id, name").in("id",I),R=new Map((D==null?void 0:D.map($=>[$.id,$.name]))||[]);return T.map($=>({...$,user_name:R.get($.user_id)||"Unknown User"}))},enabled:!!s}),x=Ct({mutationFn:async T=>{const{error:A}=await V.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:T});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),n({title:"Comment added!"})},onError:T=>{n({title:"Error adding comment",description:T.message,variant:"destructive"})}}),y=Ct({mutationFn:async T=>{const{error:A}=await V.from("resource_kit_comments").delete().eq("id",T);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),n({title:"Comment deleted"})}}),v=Ct({mutationFn:async()=>{const T=h.find(A=>A.user_id===(t==null?void 0:t.id));if(T){const{error:A}=await V.from("resource_kit_likes").delete().eq("id",T.id);if(A)throw A}else{const{error:A}=await V.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),w=h.some(T=>T.user_id===(t==null?void 0:t.id)),b=T=>T.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),N=T=>T?T<1024?T+" B":T<1024*1024?(T/1024).toFixed(1)+" KB":(T/(1024*1024)).toFixed(1)+" MB":"",S=T=>{T.preventDefault(),!(!l.trim()||!t)&&x.mutate(l.trim())};return d?e.jsx(ws,{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(ws,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/toolbox",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(G,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Yn,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(ZI,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(G,{variant:w?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!t||v.isPending,children:[e.jsx(jh,{className:`h-4 w-4 ${w?"fill-current":""}`}),h.length," ",h.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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(T=>e.jsxs("a",{href:T.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(ln,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:T.name}),T.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:N(T.file_size)})]})]}),e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},T.id))})]})}),c.links&&c.links.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Qr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(T=>e.jsxs("a",{href:T.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(Qr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:T.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},T.id))})]})}),e.jsx(oot,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Jl,{className:"h-5 w-5"}),"Comments (",m.length,")"]}),t?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(or,{placeholder:"Add a comment...",value:l,onChange:T=>o(T.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||x.isPending,children:e.jsx(en,{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:m.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):m.map(T=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(kn,{className:"text-sm",children:b(T.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:T.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:rl(new Date(T.created_at),{addSuffix:!0})}),T.user_id===(t==null?void 0:t.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>y.mutate(T.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:T.content})]})]})})},T.id))})]})]})}):e.jsx(ws,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Il,{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(G,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/toolbox",children:"Back to Toolbox"})})]})})},hXt=()=>{const s=br(),[t,r]=k.useState(""),[n,a]=k.useState("grid"),{data:i=[],isLoading:l}=mt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:h}=await V.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(h)throw h;const{data:m,error:x}=await V.from("social_swag_links").select("*").order("sort_order");if(x)throw x;const{data:y}=await V.from("social_swag_likes").select("swag_id"),{data:v}=await V.from("social_swag_comments").select("swag_id"),w=new Map;y==null||y.forEach(S=>{w.set(S.swag_id,(w.get(S.swag_id)||0)+1)});const b=new Map;return v==null||v.forEach(S=>{b.set(S.swag_id,(b.get(S.swag_id)||0)+1)}),(d||[]).map(S=>({...S,links:(m||[]).filter(T=>T.swag_id===S.id)||[],likesCount:w.get(S.id)||0,commentsCount:b.get(S.id)||0}))}}),o=i.filter(d=>{var m;return d.title.toLowerCase().includes(t.toLowerCase())||((m=d.description)==null?void 0:m.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(ws,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search social swag...",value:t,onChange:d=>r(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(G,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(em,{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: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(8)].map((d,h)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(Fs,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Fs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Fs,{className:"h-4 w-full mb-4"})]})},h))}),!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(G,{variant:"outline",onClick:()=>r(""),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(d=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${n==="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(Ge,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(po,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Pe,{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: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(jh,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(G,{size:"sm",className:"w-full gap-2",onClick:h=>{h.stopPropagation(),c(d.id)},children:[e.jsx(Qr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var yi=function(){return yi=Object.assign||function(t){for(var r,n=1,a=arguments.length;n1&&(c||!d),m=t>1&&(d||!c),x=function(){n&&i(n)},y=function(){a&&i(a)};return e.jsx(HXt,{displayMonth:s.displayMonth,hideNext:h,hidePrevious:m,nextMonth:a,previousMonth:n,onPreviousClick:x,onNextClick:y})}function GXt(s){var t,r=xc(),n=r.classNames,a=r.disableNavigation,i=r.styles,l=r.captionLayout,o=r.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:dot,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(SBe,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(SBe,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(CBe,{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(CBe,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:n.caption,style:i.caption,children:d})}function WXt(s){var t=xc(),r=t.footer,n=t.styles,a=t.classNames.tfoot;return r?e.jsx("tfoot",{className:a,style:n.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:r})})}):e.jsx(e.Fragment,{})}function KXt(s,t,r){for(var n=r?Ib(new Date):jm(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Vl(n,i);a.push(l)}return a}function YXt(){var s=xc(),t=s.classNames,r=s.styles,n=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=KXt(a,i,l);return e.jsxs("tr",{style:r.head_row,className:t.head_row,children:[n&&e.jsx("td",{style:r.head_cell,className:t.head_cell}),d.map(function(h,m){return e.jsx("th",{scope:"col",className:t.head_cell,style:r.head_cell,"aria-label":c(h,{locale:a}),children:o(h,{locale:a})},m)})]})}function ZXt(){var s,t=xc(),r=t.classNames,n=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:YXt;return e.jsx("thead",{style:n.head,className:r.head,children:e.jsx(i,{})})}function XXt(s){var t=xc(),r=t.locale,n=t.formatters.formatDay;return e.jsx(e.Fragment,{children:n(s.date,{locale:r})})}var t5e=k.createContext(void 0);function QXt(s){if(!xB(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(t5e.Provider,{value:t,children:s.children})}return e.jsx(JXt,{initialProps:s.initialProps,children:s.children})}function JXt(s){var t=s.initialProps,r=s.children,n=t.selected,a=t.min,i=t.max,l=function(d,h,m){var x,y;(x=t.onDayClick)===null||x===void 0||x.call(t,d,h,m);var v=!!(h.selected&&a&&(n==null?void 0:n.length)===a);if(!v){var w=!!(!h.selected&&i&&(n==null?void 0:n.length)===i);if(!w){var b=n?lot([],n):[];if(h.selected){var N=b.findIndex(function(S){return Ol(d,S)});b.splice(N,1)}else b.push(d);(y=t.onSelect)===null||y===void 0||y.call(t,b,d,h,m)}}},o={disabled:[]};n&&o.disabled.push(function(d){var h=i&&n.length>i-1,m=n.some(function(x){return Ol(x,d)});return!!(h&&!m)});var c={selected:n,onDayClick:l,modifiers:o};return e.jsx(t5e.Provider,{value:c,children:r})}function s5e(){var s=k.useContext(t5e);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function eQt(s,t){var r=t||{},n=r.from,a=r.to;return n&&a?Ol(a,s)&&Ol(n,s)?void 0:Ol(a,s)?{from:a,to:void 0}:Ol(n,s)?void 0:M3(n,s)?{from:s,to:a}:{from:n,to:s}:a?M3(s,a)?{from:a,to:s}:{from:s,to:a}:n?I3(s,n)?{from:s,to:n}:{from:n,to:s}:{from:s,to:void 0}}var r5e=k.createContext(void 0);function tQt(s){if(!gB(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(r5e.Provider,{value:t,children:s.children})}return e.jsx(sQt,{initialProps:s.initialProps,children:s.children})}function sQt(s){var t=s.initialProps,r=s.children,n=t.selected,a=n||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(y,v,w){var b,N;(b=t.onDayClick)===null||b===void 0||b.call(t,y,v,w);var S=eQt(y,n);(N=t.onSelect)===null||N===void 0||N.call(t,S,y,v,w)},h={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(h.range_start=[i],l?(h.range_end=[l],Ol(i,l)||(h.range_middle=[{after:i,before:l}])):h.range_end=[i]):l&&(h.range_start=[l],h.range_end=[l]),o&&(i&&!l&&h.disabled.push({after:ace(i,o-1),before:Vl(i,o-1)}),i&&l&&h.disabled.push({after:i,before:Vl(i,o-1)}),!i&&l&&h.disabled.push({after:ace(l,o-1),before:Vl(l,o-1)})),c){if(i&&!l&&(h.disabled.push({before:Vl(i,-c+1)}),h.disabled.push({after:Vl(i,c-1)})),i&&l){var m=$p(l,i)+1,x=c-m;h.disabled.push({before:ace(i,x)}),h.disabled.push({after:Vl(l,x)})}!i&&l&&(h.disabled.push({before:Vl(l,-c+1)}),h.disabled.push({after:Vl(l,c-1)}))}return e.jsx(r5e.Provider,{value:{selected:n,onDayClick:d,modifiers:h},children:r})}function n5e(){var s=k.useContext(r5e);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function jce(s){return Array.isArray(s)?lot([],s):s!==void 0?[s]:[]}function rQt(s){var t={};return Object.entries(s).forEach(function(r){var n=r[0],a=r[1];t[n]=jce(a)}),t}var Fy;(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"})(Fy||(Fy={}));var nQt=Fy.Selected,M1=Fy.Disabled,aQt=Fy.Hidden,iQt=Fy.Today,w1e=Fy.RangeEnd,j1e=Fy.RangeMiddle,N1e=Fy.RangeStart,oQt=Fy.Outside;function lQt(s,t,r){var n,a=(n={},n[nQt]=jce(s.selected),n[M1]=jce(s.disabled),n[aQt]=jce(s.hidden),n[iQt]=[s.today],n[w1e]=[],n[j1e]=[],n[N1e]=[],n[oQt]=[],n);return s.fromDate&&a[M1].push({before:s.fromDate}),s.toDate&&a[M1].push({after:s.toDate}),xB(s)?a[M1]=a[M1].concat(t.modifiers[M1]):gB(s)&&(a[M1]=a[M1].concat(r.modifiers[M1]),a[N1e]=r.modifiers[N1e],a[j1e]=r.modifiers[j1e],a[w1e]=r.modifiers[w1e]),a}var mot=k.createContext(void 0);function cQt(s){var t=xc(),r=s5e(),n=n5e(),a=lQt(t,r,n),i=rQt(t.modifiers),l=yi(yi({},a),i);return e.jsx(mot.Provider,{value:l,children:s.children})}function fot(){var s=k.useContext(mot);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function dQt(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function uQt(s){return!!(s&&typeof s=="object"&&"from"in s)}function hQt(s){return!!(s&&typeof s=="object"&&"after"in s)}function mQt(s){return!!(s&&typeof s=="object"&&"before"in s)}function fQt(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function pQt(s,t){var r,n=t.from,a=t.to;if(n&&a){var i=$p(a,n)<0;i&&(r=[a,n],n=r[0],a=r[1]);var l=$p(s,n)>=0&&$p(a,s)>=0;return l}return a?Ol(a,s):n?Ol(n,s):!1}function xQt(s){return XCe(s)}function gQt(s){return Array.isArray(s)&&s.every(XCe)}function yQt(s,t){return t.some(function(r){if(typeof r=="boolean")return r;if(xQt(r))return Ol(s,r);if(gQt(r))return r.includes(s);if(uQt(r))return pQt(s,r);if(fQt(r))return r.dayOfWeek.includes(s.getDay());if(dQt(r)){var n=$p(r.before,s),a=$p(r.after,s),i=n>0,l=a<0,o=M3(r.before,r.after);return o?l&&i:i||l}return hQt(r)?$p(s,r.after)>0:mQt(r)?$p(r.before,s)>0:typeof r=="function"?r(s):!1})}function a5e(s,t,r){var n=Object.keys(t).reduce(function(i,l){var o=t[l];return yQt(s,o)&&i.push(l),i},[]),a={};return n.forEach(function(i){return a[i]=!0}),r&&!yfe(s,r)&&(a.outside=!0),a}function vQt(s,t){for(var r=$c(s[0]),n=qx(s[s.length-1]),a,i,l=r;l<=n;){var o=a5e(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Vl(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Vl(l,1)}return i||a}var bQt=365;function pot(s,t){var r=t.moveBy,n=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,h=a.toDate,m=a.locale,x={day:Vl,week:e4,month:gf,year:lIt,startOfWeek:function(b){return a.ISOWeek?Ib(b):jm(b,{locale:m,weekStartsOn:c})},endOfWeek:function(b){return a.ISOWeek?ZJe(b):xfe(b,{locale:m,weekStartsOn:c})}},y=x[r](s,n==="after"?1:-1);n==="before"&&d?y=cIt([d,y]):n==="after"&&h&&(y=dIt([h,y]));var v=!0;if(i){var w=a5e(y,i);v=!w.disabled&&!w.hidden}return v?y:o.count>bQt?o.lastFocused:pot(y,{moveBy:r,direction:n,context:a,modifiers:i,retry:yi(yi({},o),{count:o.count+1})})}var xot=k.createContext(void 0);function _Qt(s){var t=yB(),r=fot(),n=k.useState(),a=n[0],i=n[1],l=k.useState(),o=l[0],c=l[1],d=vQt(t.displayMonths,r),h=a??(o&&t.isDateDisplayed(o))?o:d,m=function(){c(a),i(void 0)},x=function(b){i(b)},y=xc(),v=function(b,N){if(a){var S=pot(a,{moveBy:b,direction:N,context:y,modifiers:r});Ol(a,S)||(t.goToDate(S,a),x(S))}},w={focusedDay:a,focusTarget:h,blur:m,focus:x,focusDayAfter:function(){return v("day","after")},focusDayBefore:function(){return v("day","before")},focusWeekAfter:function(){return v("week","after")},focusWeekBefore:function(){return v("week","before")},focusMonthBefore:function(){return v("month","before")},focusMonthAfter:function(){return v("month","after")},focusYearBefore:function(){return v("year","before")},focusYearAfter:function(){return v("year","after")},focusStartOfWeek:function(){return v("startOfWeek","before")},focusEndOfWeek:function(){return v("endOfWeek","after")}};return e.jsx(xot.Provider,{value:w,children:s.children})}function i5e(){var s=k.useContext(xot);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function wQt(s,t){var r=fot(),n=a5e(s,r,t);return n}var o5e=k.createContext(void 0);function jQt(s){if(!cpe(s.initialProps)){var t={selected:void 0};return e.jsx(o5e.Provider,{value:t,children:s.children})}return e.jsx(NQt,{initialProps:s.initialProps,children:s.children})}function NQt(s){var t=s.initialProps,r=s.children,n=function(i,l,o){var c,d,h;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}(h=t.onSelect)===null||h===void 0||h.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:n};return e.jsx(o5e.Provider,{value:a,children:r})}function got(){var s=k.useContext(o5e);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function kQt(s,t){var r=xc(),n=got(),a=s5e(),i=n5e(),l=i5e(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,h=l.focusWeekBefore,m=l.blur,x=l.focus,y=l.focusMonthBefore,v=l.focusMonthAfter,w=l.focusYearBefore,b=l.focusYearAfter,N=l.focusStartOfWeek,S=l.focusEndOfWeek,T=function(oe){var ne,ie,ye,ce;cpe(r)?(ne=n.onDayClick)===null||ne===void 0||ne.call(n,s,t,oe):xB(r)?(ie=a.onDayClick)===null||ie===void 0||ie.call(a,s,t,oe):gB(r)?(ye=i.onDayClick)===null||ye===void 0||ye.call(i,s,t,oe):(ce=r.onDayClick)===null||ce===void 0||ce.call(r,s,t,oe)},A=function(oe){var ne;x(s),(ne=r.onDayFocus)===null||ne===void 0||ne.call(r,s,t,oe)},I=function(oe){var ne;m(),(ne=r.onDayBlur)===null||ne===void 0||ne.call(r,s,t,oe)},D=function(oe){var ne;(ne=r.onDayMouseEnter)===null||ne===void 0||ne.call(r,s,t,oe)},R=function(oe){var ne;(ne=r.onDayMouseLeave)===null||ne===void 0||ne.call(r,s,t,oe)},$=function(oe){var ne;(ne=r.onDayPointerEnter)===null||ne===void 0||ne.call(r,s,t,oe)},F=function(oe){var ne;(ne=r.onDayPointerLeave)===null||ne===void 0||ne.call(r,s,t,oe)},z=function(oe){var ne;(ne=r.onDayTouchCancel)===null||ne===void 0||ne.call(r,s,t,oe)},Q=function(oe){var ne;(ne=r.onDayTouchEnd)===null||ne===void 0||ne.call(r,s,t,oe)},K=function(oe){var ne;(ne=r.onDayTouchMove)===null||ne===void 0||ne.call(r,s,t,oe)},X=function(oe){var ne;(ne=r.onDayTouchStart)===null||ne===void 0||ne.call(r,s,t,oe)},Z=function(oe){var ne;(ne=r.onDayKeyUp)===null||ne===void 0||ne.call(r,s,t,oe)},re=function(oe){var ne;switch(oe.key){case"ArrowLeft":oe.preventDefault(),oe.stopPropagation(),r.dir==="rtl"?o():c();break;case"ArrowRight":oe.preventDefault(),oe.stopPropagation(),r.dir==="rtl"?c():o();break;case"ArrowDown":oe.preventDefault(),oe.stopPropagation(),d();break;case"ArrowUp":oe.preventDefault(),oe.stopPropagation(),h();break;case"PageUp":oe.preventDefault(),oe.stopPropagation(),oe.shiftKey?w():y();break;case"PageDown":oe.preventDefault(),oe.stopPropagation(),oe.shiftKey?b():v();break;case"Home":oe.preventDefault(),oe.stopPropagation(),N();break;case"End":oe.preventDefault(),oe.stopPropagation(),S();break}(ne=r.onDayKeyDown)===null||ne===void 0||ne.call(r,s,t,oe)},le={onClick:T,onFocus:A,onBlur:I,onKeyDown:re,onKeyUp:Z,onMouseEnter:D,onMouseLeave:R,onPointerEnter:$,onPointerLeave:F,onTouchCancel:z,onTouchEnd:Q,onTouchMove:K,onTouchStart:X};return le}function SQt(){var s=xc(),t=got(),r=s5e(),n=n5e(),a=cpe(s)?t.selected:xB(s)?r.selected:gB(s)?n.selected:void 0;return a}function CQt(s){return Object.values(Fy).includes(s)}function TQt(s,t){var r=[s.classNames.day];return Object.keys(t).forEach(function(n){var a=s.modifiersClassNames[n];if(a)r.push(a);else if(CQt(n)){var i=s.classNames["day_".concat(n)];i&&r.push(i)}}),r}function EQt(s,t){var r=yi({},s.styles.day);return Object.keys(t).forEach(function(n){var a;r=yi(yi({},r),(a=s.modifiersStyles)===null||a===void 0?void 0:a[n])}),r}function AQt(s,t,r){var n,a,i,l=xc(),o=i5e(),c=wQt(s,t),d=kQt(s,c),h=SQt(),m=!!(l.onDayClick||l.mode!=="default");k.useEffect(function(){var D;c.outside||o.focusedDay&&m&&Ol(o.focusedDay,s)&&((D=r.current)===null||D===void 0||D.focus())},[o.focusedDay,s,r,m,c.outside]);var x=TQt(l,c).join(" "),y=EQt(l,c),v=!!(c.outside&&!l.showOutsideDays||c.hidden),w=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:XXt,b=e.jsx(w,{date:s,displayMonth:t,activeModifiers:c}),N={style:y,className:x,children:b,role:"gridcell"},S=o.focusTarget&&Ol(o.focusTarget,s)&&!c.outside,T=o.focusedDay&&Ol(o.focusedDay,s),A=yi(yi(yi({},N),(n={disabled:c.disabled,role:"gridcell"},n["aria-selected"]=c.selected,n.tabIndex=T||S?0:-1,n)),d),I={isButton:m,isHidden:v,activeModifiers:c,selectedDays:h,buttonProps:A,divProps:N};return I}function MQt(s){var t=k.useRef(null),r=AQt(s.date,s.displayMonth,t);return r.isHidden?e.jsx("div",{role:"gridcell"}):r.isButton?e.jsx(Rue,yi({name:"day",ref:t},r.buttonProps)):e.jsx("div",yi({},r.divProps))}function IQt(s){var t=s.number,r=s.dates,n=xc(),a=n.onWeekNumberClick,i=n.styles,l=n.classNames,o=n.locale,c=n.labels.labelWeekNumber,d=n.formatters.formatWeekNumber,h=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:h});var m=c(Number(t),{locale:o}),x=function(y){a(t,r,y)};return e.jsx(Rue,{name:"week-number","aria-label":m,className:l.weeknumber,style:i.weeknumber,onClick:x,children:h})}function LQt(s){var t,r,n=xc(),a=n.styles,i=n.classNames,l=n.showWeekNumber,o=n.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:MQt,d=(r=o==null?void 0:o.WeekNumber)!==null&&r!==void 0?r:IQt,h;return l&&(h=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:[h,s.dates.map(function(m){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:m})},mLt(m))})]})}function TBe(s,t,r){for(var n=r!=null&&r.ISOWeek?ZJe(t):xfe(t,r),a=r!=null&&r.ISOWeek?Ib(s):jm(s,r),i=$p(n,a),l=[],o=0;o<=i;o++)l.push(Vl(a,o));var c=l.reduce(function(d,h){var m=r!=null&&r.ISOWeek?QCe(h):e4e(h,r),x=d.find(function(y){return y.weekNumber===m});return x?(x.dates.push(h),d):(d.push({weekNumber:m,dates:[h]}),d)},[]);return c}function PQt(s,t){var r=TBe($c(s),qx(s),t);if(t!=null&&t.useFixedWeeks){var n=pLt(s,t);if(n<6){var a=r[r.length-1],i=a.dates[a.dates.length-1],l=e4(i,6-n),o=TBe(e4(i,1),l,t);r.push.apply(r,o)}}return r}function DQt(s){var t,r,n,a=xc(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,h=a.components,m=a.weekStartsOn,x=a.firstWeekContainsDate,y=a.ISOWeek,v=PQt(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:y,locale:i,weekStartsOn:m,firstWeekContainsDate:x}),w=(t=h==null?void 0:h.Head)!==null&&t!==void 0?t:ZXt,b=(r=h==null?void 0:h.Row)!==null&&r!==void 0?r:LQt,N=(n=h==null?void 0:h.Footer)!==null&&n!==void 0?n:WXt;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(w,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:v.map(function(S){return e.jsx(b,{displayMonth:s.displayMonth,dates:S.dates,weekNumber:S.weekNumber},S.weekNumber)})}),e.jsx(N,{displayMonth:s.displayMonth})]})}function RQt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var OQt=RQt()?k.useLayoutEffect:k.useEffect,k1e=!1,FQt=0;function EBe(){return"react-day-picker-".concat(++FQt)}function BQt(s){var t,r=s??(k1e?EBe():null),n=k.useState(r),a=n[0],i=n[1];return OQt(function(){a===null&&i(EBe())},[]),k.useEffect(function(){k1e===!1&&(k1e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function zQt(s){var t,r,n=xc(),a=n.dir,i=n.classNames,l=n.styles,o=n.components,c=yB().displayMonths,d=BQt(n.id?"".concat(n.id,"-").concat(s.displayIndex):void 0),h=n.id?"".concat(n.id,"-grid-").concat(s.displayIndex):void 0,m=[i.month],x=l.month,y=s.displayIndex===0,v=s.displayIndex===c.length-1,w=!y&&!v;a==="rtl"&&(t=[y,v],v=t[0],y=t[1]),y&&(m.push(i.caption_start),x=yi(yi({},x),l.caption_start)),v&&(m.push(i.caption_end),x=yi(yi({},x),l.caption_end)),w&&(m.push(i.caption_between),x=yi(yi({},x),l.caption_between));var b=(r=o==null?void 0:o.Caption)!==null&&r!==void 0?r:GXt;return e.jsxs("div",{className:m.join(" "),style:x,children:[e.jsx(b,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(DQt,{id:h,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function $Qt(s){var t=xc(),r=t.classNames,n=t.styles;return e.jsx("div",{className:r.months,style:n.months,children:s.children})}function UQt(s){var t,r,n=s.initialProps,a=xc(),i=i5e(),l=yB(),o=k.useState(!1),c=o[0],d=o[1];k.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var h=[a.classNames.root,a.className];a.numberOfMonths>1&&h.push(a.classNames.multiple_months),a.showWeekNumber&&h.push(a.classNames.with_weeknumber);var m=yi(yi({},a.styles.root),a.style),x=Object.keys(n).filter(function(v){return v.startsWith("data-")}).reduce(function(v,w){var b;return yi(yi({},v),(b={},b[w]=n[w],b))},{}),y=(r=(t=n.components)===null||t===void 0?void 0:t.Months)!==null&&r!==void 0?r:$Qt;return e.jsx("div",yi({className:h.join(" "),style:m,dir:a.dir,id:a.id,nonce:n.nonce,title:n.title,lang:n.lang},x,{children:e.jsx(y,{children:l.displayMonths.map(function(v,w){return e.jsx(zQt,{displayIndex:w,displayMonth:v},w)})})}))}function qQt(s){var t=s.children,r=mXt(s,["children"]);return e.jsx(IXt,{initialProps:r,children:e.jsx(UXt,{children:e.jsx(jQt,{initialProps:r,children:e.jsx(QXt,{initialProps:r,children:e.jsx(tQt,{initialProps:r,children:e.jsx(cQt,{children:e.jsx(_Qt,{children:t})})})})})})})}function VQt(s){return e.jsx(qQt,yi({},s,{children:e.jsx(UQt,{initialProps:s})}))}function Yp({className:s,classNames:t,showOutsideDays:r=!0,...n}){return e.jsx(VQt,{showOutsideDays:r,className:It("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:It(jM({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:It(jM({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($o,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(va,{className:"h-4 w-4"})},...n})}Yp.displayName="Calendar";var dpe="Popover",[yot,qUs]=pd(dpe,[Pv]),vB=Pv(),[HQt,i2]=yot(dpe),vot=s=>{const{__scopePopover:t,children:r,open:n,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=vB(t),c=k.useRef(null),[d,h]=k.useState(!1),[m,x]=Sh({prop:n,defaultProp:a??!1,onChange:i,caller:dpe});return e.jsx(qF,{...o,children:e.jsx(HQt,{scope:t,contentId:Yu(),triggerRef:c,open:m,onOpenChange:x,onOpenToggle:k.useCallback(()=>x(y=>!y),[x]),hasCustomAnchor:d,onCustomAnchorAdd:k.useCallback(()=>h(!0),[]),onCustomAnchorRemove:k.useCallback(()=>h(!1),[]),modal:l,children:r})})};vot.displayName=dpe;var bot="PopoverAnchor",GQt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=i2(bot,r),i=vB(r),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return k.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(PI,{...i,...n,ref:t})});GQt.displayName=bot;var _ot="PopoverTrigger",wot=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=i2(_ot,r),i=vB(r),l=Ga(t,a.triggerRef),o=e.jsx(wn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Cot(a.open),...n,ref:l,onClick:Vr(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(PI,{asChild:!0,...i,children:o})});wot.displayName=_ot;var l5e="PopoverPortal",[WQt,KQt]=yot(l5e,{forceMount:void 0}),jot=s=>{const{__scopePopover:t,forceMount:r,children:n,container:a}=s,i=i2(l5e,t);return e.jsx(WQt,{scope:t,forceMount:r,children:e.jsx(ru,{present:r||i.open,children:e.jsx(AI,{asChild:!0,container:a,children:n})})})};jot.displayName=l5e;var zM="PopoverContent",Not=k.forwardRef((s,t)=>{const r=KQt(zM,s.__scopePopover),{forceMount:n=r.forceMount,...a}=s,i=i2(zM,s.__scopePopover);return e.jsx(ru,{present:n||i.open,children:i.modal?e.jsx(ZQt,{...a,ref:t}):e.jsx(XQt,{...a,ref:t})})});Not.displayName=zM;var YQt=kj("PopoverContent.RemoveScroll"),ZQt=k.forwardRef((s,t)=>{const r=i2(zM,s.__scopePopover),n=k.useRef(null),a=Ga(t,n),i=k.useRef(!1);return k.useEffect(()=>{const l=n.current;if(l)return Jme(l)},[]),e.jsx(ZF,{as:YQt,allowPinchZoom:!0,children:e.jsx(kot,{...s,ref:a,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Vr(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:Vr(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:Vr(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),XQt=k.forwardRef((s,t)=>{const r=i2(zM,s.__scopePopover),n=k.useRef(!1),a=k.useRef(!1);return e.jsx(kot,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(n.current||(o=r.triggerRef.current)==null||o.focus(),i.preventDefault()),n.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(n.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),kot=k.forwardRef((s,t)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:h,...m}=s,x=i2(zM,r),y=vB(r);return Zme(),e.jsx(KF,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(Hj,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:h,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>x.onOpenChange(!1),children:e.jsx(VF,{"data-state":Cot(x.open),role:"dialog",id:x.contentId,...y,...m,ref:t,style:{...m.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)"}})})})}),Sot="PopoverClose",QQt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=i2(Sot,r);return e.jsx(wn.button,{type:"button",...n,ref:t,onClick:Vr(s.onClick,()=>a.onOpenChange(!1))})});QQt.displayName=Sot;var JQt="PopoverArrow",eJt=k.forwardRef((s,t)=>{const{__scopePopover:r,...n}=s,a=vB(r);return e.jsx(HF,{...a,...n,ref:t})});eJt.displayName=JQt;function Cot(s){return s?"open":"closed"}var tJt=vot,sJt=wot,rJt=jot,Tot=Not;const To=tJt,Eo=sJt,_o=k.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(rJt,{children:e.jsx(Tot,{ref:a,align:t,sideOffset:r,className:It("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),...n})}));_o.displayName=Tot.displayName;const nJt=r5("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"}}),c5e=k.forwardRef(({className:s,variant:t,...r},n)=>e.jsx("div",{ref:n,role:"alert",className:It(nJt({variant:t}),s),...r}));c5e.displayName="Alert";const aJt=k.forwardRef(({className:s,...t},r)=>e.jsx("h5",{ref:r,className:It("mb-1 font-medium leading-none tracking-tight",s),...t}));aJt.displayName="AlertTitle";const d5e=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,className:It("text-sm [&_p]:leading-relaxed",s),...t}));d5e.displayName="AlertDescription";function iJt({open:s,onOpenChange:t,imageUrl:r,imageId:n,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Xt(),[c,d]=k.useState(a),[h,m]=k.useState([]),[x,y]=k.useState(null),[v,w]=k.useState("now"),[b,N]=k.useState(yRe(NRe(new Date),1)),[S,T]=k.useState("12"),[A,I]=k.useState("00"),[D,R]=k.useState("PM");k.useEffect(()=>{if(s){d(a),w("now"),m([]);const be=yRe(NRe(new Date),1);N(be);const Ue=be.getHours();T(String(Ue>12?Ue-12:Ue===0?12:Ue)),I("00"),R(Ue>=12?"PM":"AM")}},[s,a]);const $=()=>{if(!b)return null;let be=parseInt(S);const Ue=parseInt(A);return D==="PM"&&be!==12&&(be+=12),D==="AM"&&be===12&&(be=0),nO(rO(b,be),Ue)},{data:F,isLoading:z}=mt({queryKey:["social-accounts-for-post"],queryFn:async()=>{const{data:{user:be}}=await V.auth.getUser();if(!be)return[];const{data:Ue,error:Be}=await V.from("social_accounts").select("*").eq("user_id",be.id).eq("is_active",!0).order("platform",{ascending:!0});if(Be)throw Be;return console.log("Fetched social accounts for posting:",Ue),Ue},enabled:s,staleTime:0}),Q=Ct({mutationFn:async({accountId:be,platform:Ue})=>{y(be);const{data:Be,error:De}=await V.functions.invoke("social-post",{body:{platform:Ue,accountId:be,imageUrl:r,caption:c}});if(De)throw De;if(Be!=null&&Be.error)throw new Error(Be.error);return Be},onSuccess:be=>{const Ue=be.platform==="facebook"?"Facebook":be.platform==="instagram"?"Instagram":be.platform==="linkedin"?"LinkedIn":"Google Business";ue.success(`Posted to ${Ue}!`)},onError:be=>{ue.error(`Failed to post: ${be.message}`)},onSettled:()=>{y(null)}}),K=Ct({mutationFn:async({accountId:be,platform:Ue,scheduledFor:Be})=>{const{data:{user:De}}=await V.auth.getUser();if(!De)throw new Error("Not authenticated");const{error:Ae}=await V.from("scheduled_posts").insert({user_id:De.id,social_account_id:be,platform:Ue,image_url:r,caption:c,swag_item_id:i||null,reel_id:l||null,scheduled_for:Be.toISOString(),status:"scheduled"});if(Ae)throw Ae;return{platform:Ue}},onSuccess:be=>{const Ue=be.platform==="facebook"?"Facebook":be.platform==="instagram"?"Instagram":"LinkedIn";ue.success(`Post scheduled for ${Ue}!`)},onError:be=>{ue.error(`Failed to schedule: ${be.message}`)}}),X=async()=>{if(h.length===0){ue.error("Please select at least one account");return}if(v==="schedule"){const be=$();if(!be||be<=new Date){ue.error("Please select a future date and time");return}for(const Ue of h){const Be=F==null?void 0:F.find(De=>De.id===Ue);Be&&await K.mutateAsync({accountId:Ue,platform:Be.platform,scheduledFor:be})}o.invalidateQueries({queryKey:["scheduled-posts"]}),ue.success(`${h.length} post(s) scheduled for ${_s(be,"PPp")}`)}else for(const be of h){const Ue=F==null?void 0:F.find(Be=>Be.id===be);Ue&&await Q.mutateAsync({accountId:be,platform:Ue.platform})}o.invalidateQueries({queryKey:["scheduled-posts"]}),d(""),m([]),t(!1)},Z=be=>{m(Ue=>Ue.includes(be)?Ue.filter(Be=>Be!==be):[...Ue,be])},re=(F==null?void 0:F.filter(be=>be.platform==="facebook"))||[],le=(F==null?void 0:F.filter(be=>be.platform==="instagram"))||[],oe=(F==null?void 0:F.filter(be=>be.platform==="linkedin"))||[],ne=(F==null?void 0:F.filter(be=>be.platform==="google_business"))||[],ie=((F==null?void 0:F.length)||0)>0,ye=Q.isPending||K.isPending,ce=Array.from({length:12},(be,Ue)=>String(Ue+1)),ve=["00","15","30","45"];return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create Social Post"}),e.jsx(Hr,{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:r,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"caption",children:"Caption"}),e.jsx(or,{id:"caption",placeholder:"Write a caption for your post...",value:c,onChange:be=>d(be.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(he,{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:()=>w("now"),className:It("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>w("schedule"),className:It("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",v==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),v==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(fn,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),b?_s(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:b,onSelect:N,disabled:be=>bee.jsx(ct,{value:be,children:be},be))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Is,{value:A,onValueChange:I,children:[e.jsx(As,{className:"w-[70px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:ve.map(be=>e.jsx(ct,{value:be,children:be},be))})]}),e.jsxs(Is,{value:D,onValueChange:be=>R(be),children:[e.jsx(As,{className:"w-[70px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"AM",children:"AM"}),e.jsx(ct,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",_s($()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Post to"}),z&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(es,{className:"h-6 w-6 animate-spin"})}),!z&&!ie&&e.jsxs(c5e,{children:[e.jsx(Oi,{className:"h-4 w-4"}),e.jsxs(d5e,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Yn,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(oo,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),re.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(yu,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),re.map(be=>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(Si,{checked:h.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:x===be.id}),e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:be.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(yu,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.page_name||be.platform_username}),x===be.id&&e.jsx(es,{className:"h-4 w-4 animate-spin"})]},be.id))]}),le.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Jd,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),le.map(be=>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(Si,{checked:h.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:x===be.id}),e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:be.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Jd,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",be.platform_username]}),x===be.id&&e.jsx(es,{className:"h-4 w-4 animate-spin"})]},be.id))]}),oe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Jh,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),oe.map(be=>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(Si,{checked:h.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:x===be.id}),e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:be.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Jh,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.platform_username}),x===be.id&&e.jsx(es,{className:"h-4 w-4 animate-spin"})]},be.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(Ca,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ne.map(be=>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(Si,{checked:h.includes(be.id),onCheckedChange:()=>Z(be.id),disabled:x===be.id}),e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:be.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Ca,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:be.page_name||be.platform_username}),x===be.id&&e.jsx(es,{className:"h-4 w-4 animate-spin"})]},be.id))]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:X,disabled:h.length===0||ye,className:"gap-2",children:[ye?e.jsx(es,{className:"h-4 w-4 animate-spin"}):v==="schedule"?e.jsx(on,{className:"h-4 w-4"}):e.jsx(en,{className:"h-4 w-4"}),v==="schedule"?`Schedule ${h.length} post${h.length!==1?"s":""}`:`Post to ${h.length} account${h.length!==1?"s":""}`]})]})]})})}function oJt(){const s=Xt(),[t,r]=k.useState(void 0),[n,a]=k.useState("all"),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,h]=k.useState(void 0),[m,x]=k.useState("12"),[y,v]=k.useState("00"),[w,b]=k.useState("PM"),{data:N=[],isLoading:S}=mt({queryKey:["scheduled-posts"],queryFn:async()=>{const{data:ne,error:ie}=await V.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).order("scheduled_for",{ascending:!1});if(ie)throw ie;return ne}}),T=N.filter(ne=>{if(n!=="all"&&ne.status!==n)return!1;if(t&&ne.scheduled_for){const ie=new Date(ne.scheduled_for);if(!Ol(ie,t))return!1}return!0}),A=N.filter(ne=>ne.scheduled_for).map(ne=>yf(new Date(ne.scheduled_for))),I=Ct({mutationFn:async ne=>{const{error:ie}=await V.from("scheduled_posts").update({caption:ne.caption,scheduled_for:ne.scheduled_for}).eq("id",ne.id);if(ie)throw ie},onSuccess:()=>{ue.success("Post updated!"),s.invalidateQueries({queryKey:["scheduled-posts"]}),l(null)},onError:ne=>{ue.error(`Failed to update: ${ne.message}`)}}),D=Ct({mutationFn:async ne=>{const{error:ie}=await V.from("scheduled_posts").update({status:"cancelled"}).eq("id",ne);if(ie)throw ie},onSuccess:()=>{ue.success("Post cancelled"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ne=>{ue.error(`Failed to cancel: ${ne.message}`)}}),R=Ct({mutationFn:async ne=>{const{error:ie}=await V.from("scheduled_posts").delete().eq("id",ne);if(ie)throw ie},onSuccess:()=>{ue.success("Post deleted"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ne=>{ue.error(`Failed to delete: ${ne.message}`)}}),$=Ct({mutationFn:async ne=>{const{data:ie,error:ye}=await V.functions.invoke("social-post",{body:{platform:ne.platform,accountId:ne.social_account_id,imageUrl:ne.image_url,caption:ne.caption}});if(ye)throw ye;if(ie!=null&&ie.error)throw new Error(ie.error);return await V.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ie.postId}).eq("id",ne.id),ie},onSuccess:ne=>{const ie=ne.platform==="facebook"?"Facebook":ne.platform==="instagram"?"Instagram":"LinkedIn";ue.success(`Posted to ${ie}!`),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:ne=>{ue.error(`Failed to post: ${ne.message}`)}}),F=ne=>{if(l(ne),c(ne.caption||""),ne.scheduled_for){const ie=new Date(ne.scheduled_for);h(ie);const ye=ie.getHours();x(String(ye>12?ye-12:ye===0?12:ye)),v(String(ie.getMinutes()).padStart(2,"0")),b(ye>=12?"PM":"AM")}},z=()=>{if(!i||!d)return;let ne=parseInt(m);const ie=parseInt(y);w==="PM"&&ne!==12&&(ne+=12),w==="AM"&&ne===12&&(ne=0);const ye=nO(rO(d,ne),ie);I.mutate({id:i.id,caption:o,scheduled_for:ye.toISOString()})},Q=ne=>{switch(ne){case"facebook":return e.jsx(yu,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Jd,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(Jh,{className:"h-4 w-4 text-blue-700"});default:return null}},K=ne=>{switch(ne){case"scheduled":return e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Ge,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(di,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Ge,{variant:"destructive",className:"gap-1",children:[e.jsx(Sc,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Ge,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Oi,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Ge,{variant:"outline",children:ne})}},X=Array.from({length:12},(ne,ie)=>String(ie+1)),Z=["00","15","30","45"],re=N.filter(ne=>ne.status==="scheduled").length,le=N.filter(ne=>ne.status==="posted").length,oe=N.filter(ne=>ne.status==="scheduled"&&ne.scheduled_for&&xLt(new Date(ne.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:re}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(ke,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:N.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(hd,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Yp,{mode:"single",selected:t,onSelect:r,className:It("pointer-events-auto"),modifiers:{hasPost:A},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),t&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>r(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(Sy,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ne=>e.jsx(G,{variant:n===ne?"default":"outline",size:"sm",onClick:()=>a(ne),className:"capitalize",children:ne},ne))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!S&&T.length===0&&e.jsxs(ke,{className:"p-8 text-center",children:[e.jsx(on,{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 ${_s(t,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:T.map(ne=>{var ie,ye;return e.jsx(ke,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:ne.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Pe,{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:[Q(ne.platform),e.jsx("span",{className:"font-medium",children:((ie=ne.social_accounts)==null?void 0:ie.page_name)||((ye=ne.social_accounts)==null?void 0:ye.platform_username)||"Unknown"}),K(ne.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ne.status==="scheduled"&&e.jsxs(Ub,{children:[e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>F(ne),children:e.jsx(Ea,{className:"h-4 w-4"})})}),e.jsx(Gl,{children:"Edit post"})]}),e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>$.mutate(ne),disabled:$.isPending,children:$.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"})})}),e.jsx(Gl,{children:"Post now"})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Cancel this scheduled post?"}),e.jsx(Bo,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Keep"}),e.jsx(Co,{onClick:()=>D.mutate(ne.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Co,{onClick:()=>R.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ne.status==="posted"||ne.status==="cancelled"||ne.status==="failed")&&e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete this post?"}),e.jsx(Bo,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>R.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ne.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ne.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),ne.status==="posted"&&ne.posted_at?`Posted ${_s(new Date(ne.posted_at),"PPp")}`:ne.scheduled_for?`Scheduled for ${_s(new Date(ne.scheduled_for),"PPp")}`:"Not scheduled"]}),ne.status==="failed"&&ne.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ne.error_message]})]})]})},ne.id)})})]})]}),e.jsx(fs,{open:!!i,onOpenChange:ne=>!ne&&l(null),children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Edit Scheduled Post"}),e.jsx(Hr,{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(he,{children:"Caption"}),e.jsx(or,{value:o,onChange:ne=>c(ne.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(he,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("justify-start text-left font-normal flex-1",!d&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),d?_s(d,"PPP"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:d,onSelect:h,disabled:ne=>nee.jsx(ct,{value:ne,children:ne},ne))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Is,{value:y,onValueChange:v,children:[e.jsx(As,{className:"w-[70px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:Z.map(ne=>e.jsx(ct,{value:ne,children:ne},ne))})]}),e.jsxs(Is,{value:w,onValueChange:ne=>b(ne),children:[e.jsx(As,{className:"w-[70px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"AM",children:"AM"}),e.jsx(ct,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(G,{onClick:z,disabled:I.isPending,children:[I.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function h$(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 Eot={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(r){s.exports=r()})(function(){return function r(n,a,i){function l(d,h){if(!a[d]){if(!n[d]){var m=typeof h$=="function"&&h$;if(!h&&m)return m(d,!0);if(o)return o(d,!0);var x=new Error("Cannot find module '"+d+"'");throw x.code="MODULE_NOT_FOUND",x}var y=a[d]={exports:{}};n[d][0].call(y.exports,function(v){var w=n[d][1][v];return l(w||v)},y,y.exports,r,n,a,i)}return a[d].exports}for(var o=typeof h$=="function"&&h$,c=0;c>2,y=(3&d)<<4|h>>4,v=1>6:64,w=2>4,h=(15&x)<<4|(y=o.indexOf(c.charAt(w++)))>>2,m=(3&y)<<6|(v=o.indexOf(c.charAt(w++))),S[b++]=d,y!==64&&(S[b++]=h),v!==64&&(S[b++]=m);return S}},{"./support":30,"./utils":32}],2:[function(r,n,a){var i=r("./external"),l=r("./stream/DataWorker"),o=r("./stream/Crc32Probe"),c=r("./stream/DataLengthProbe");function d(h,m,x,y,v){this.compressedSize=h,this.uncompressedSize=m,this.crc32=x,this.compression=y,this.compressedContent=v}d.prototype={getContentWorker:function(){var h=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),m=this;return h.on("end",function(){if(this.streamInfo.data_length!==m.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),h},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(h,m,x){return h.pipe(new o).pipe(new c("uncompressedSize")).pipe(m.compressWorker(x)).pipe(new c("compressedSize")).withStreamInfo("compression",m)},n.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,n,a){var i=r("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,n,a){var i=r("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var h=0;h<8;h++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();n.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,h,m,x){var y=l,v=x+m;d^=-1;for(var w=x;w>>8^y[255&(d^h[w])];return-1^d}(0|c,o,o.length,0):function(d,h,m,x){var y=l,v=x+m;d^=-1;for(var w=x;w>>8^y[255&(d^h.charCodeAt(w))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(r,n,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(r,n,a){var i=null;i=typeof Promise<"u"?Promise:r("lie"),n.exports={Promise:i}},{lie:37}],7:[function(r,n,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=r("pako"),o=r("./utils"),c=r("./stream/GenericWorker"),d=i?"uint8array":"array";function h(m,x){c.call(this,"FlateWorker/"+m),this._pako=null,this._pakoAction=m,this._pakoOptions=x,this.meta={}}a.magic="\b\0",o.inherits(h,c),h.prototype.processChunk=function(m){this.meta=m.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,m.data),!1)},h.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var m=this;this._pako.onData=function(x){m.push({data:x,meta:m.meta})}},a.compressWorker=function(m){return new h("Deflate",m)},a.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,n,a){function i(y,v){var w,b="";for(w=0;w>>=8;return b}function l(y,v,w,b,N,S){var T,A,I=y.file,D=y.compression,R=S!==d.utf8encode,$=o.transformTo("string",S(I.name)),F=o.transformTo("string",d.utf8encode(I.name)),z=I.comment,Q=o.transformTo("string",S(z)),K=o.transformTo("string",d.utf8encode(z)),X=F.length!==I.name.length,Z=K.length!==z.length,re="",le="",oe="",ne=I.dir,ie=I.date,ye={crc32:0,compressedSize:0,uncompressedSize:0};v&&!w||(ye.crc32=y.crc32,ye.compressedSize=y.compressedSize,ye.uncompressedSize=y.uncompressedSize);var ce=0;v&&(ce|=8),R||!X&&!Z||(ce|=2048);var ve=0,be=0;ne&&(ve|=16),N==="UNIX"?(be=798,ve|=function(Be,De){var Ae=Be;return Be||(Ae=De?16893:33204),(65535&Ae)<<16}(I.unixPermissions,ne)):(be=20,ve|=function(Be){return 63&(Be||0)}(I.dosPermissions)),T=ie.getUTCHours(),T<<=6,T|=ie.getUTCMinutes(),T<<=5,T|=ie.getUTCSeconds()/2,A=ie.getUTCFullYear()-1980,A<<=4,A|=ie.getUTCMonth()+1,A<<=5,A|=ie.getUTCDate(),X&&(le=i(1,1)+i(h($),4)+F,re+="up"+i(le.length,2)+le),Z&&(oe=i(1,1)+i(h(Q),4)+K,re+="uc"+i(oe.length,2)+oe);var Ue="";return Ue+=` \0`,Ue+=i(ce,2),Ue+=D.magic,Ue+=i(T,2),Ue+=i(A,2),Ue+=i(ye.crc32,4),Ue+=i(ye.compressedSize,4),Ue+=i(ye.uncompressedSize,4),Ue+=i($.length,2),Ue+=i(re.length,2),{fileRecord:m.LOCAL_FILE_HEADER+Ue+$+re,dirRecord:m.CENTRAL_FILE_HEADER+i(be,2)+Ue+i(Q.length,2)+"\0\0\0\0"+i(ve,4)+i(b,4)+$+re+Q}}var o=r("../utils"),c=r("../stream/GenericWorker"),d=r("../utf8"),h=r("../crc32"),m=r("../signature");function x(y,v,w,b){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=v,this.zipPlatform=w,this.encodeFileName=b,this.streamFiles=y,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(x,c),x.prototype.push=function(y){var v=y.meta.percent||0,w=this.entriesCount,b=this._sources.length;this.accumulate?this.contentBuffer.push(y):(this.bytesWritten+=y.data.length,c.prototype.push.call(this,{data:y.data,meta:{currentFile:this.currentFile,percent:w?(v+100*(w-b-1))/w:100}}))},x.prototype.openedSource=function(y){this.currentSourceOffset=this.bytesWritten,this.currentFile=y.file.name;var v=this.streamFiles&&!y.file.dir;if(v){var w=l(y,v,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:w.fileRecord,meta:{percent:0}})}else this.accumulate=!0},x.prototype.closedSource=function(y){this.accumulate=!1;var v=this.streamFiles&&!y.file.dir,w=l(y,v,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(w.dirRecord),v)this.push({data:function(b){return m.DATA_DESCRIPTOR+i(b.crc32,4)+i(b.compressedSize,4)+i(b.uncompressedSize,4)}(y),meta:{percent:100}});else for(this.push({data:w.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},x.prototype.flush=function(){for(var y=this.bytesWritten,v=0;v=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))}},n.exports=l},{"../utils":32}],19:[function(r,n,a){var i=r("./Uint8ArrayReader");function l(o){i.call(this,o)}r("../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},n.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,n,a){var i=r("./DataReader");function l(o){i.call(this,o)}r("../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},n.exports=l},{"../utils":32,"./DataReader":18}],21:[function(r,n,a){var i=r("./ArrayReader");function l(o){i.call(this,o)}r("../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},n.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(r,n,a){var i=r("../utils"),l=r("../support"),o=r("./ArrayReader"),c=r("./StringReader"),d=r("./NodeBufferReader"),h=r("./Uint8ArrayReader");n.exports=function(m){var x=i.getTypeOf(m);return i.checkSupport(x),x!=="string"||l.uint8array?x==="nodebuffer"?new d(m):l.uint8array?new h(i.transformTo("uint8array",m)):new o(i.transformTo("array",m)):new c(m)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,n,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(r,n,a){var i=r("./GenericWorker"),l=r("../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})},n.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(r,n,a){var i=r("./GenericWorker"),l=r("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},n.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,n,a){var i=r("../utils"),l=r("./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)},n.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(r,n,a){var i=r("../utils"),l=r("./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(h){d.dataIsReady=!0,d.data=h,d.max=h&&h.length||0,d.type=i.getTypeOf(h),d.isPaused||d._tickAndRepeat()},function(h){d.error(h)})}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}})},n.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(r,n,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}},n.exports=i},{}],29:[function(r,n,a){var i=r("../utils"),l=r("./ConvertWorker"),o=r("./GenericWorker"),c=r("../base64"),d=r("../support"),h=r("../external"),m=null;if(d.nodestream)try{m=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function x(v,w){return new h.Promise(function(b,N){var S=[],T=v._internalType,A=v._outputType,I=v._mimeType;v.on("data",function(D,R){S.push(D),w&&w(R)}).on("error",function(D){S=[],N(D)}).on("end",function(){try{var D=function(R,$,F){switch(R){case"blob":return i.newBlob(i.transformTo("arraybuffer",$),F);case"base64":return c.encode($);default:return i.transformTo(R,$)}}(A,function(R,$){var F,z=0,Q=null,K=0;for(F=0;F<$.length;F++)K+=$[F].length;switch(R){case"string":return $.join("");case"array":return Array.prototype.concat.apply([],$);case"uint8array":for(Q=new Uint8Array(K),F=0;F<$.length;F++)Q.set($[F],z),z+=$[F].length;return Q;case"nodebuffer":return Buffer.concat($);default:throw new Error("concat : unsupported type '"+R+"'")}}(T,S),I);b(D)}catch(R){N(R)}S=[]}).resume()})}function y(v,w,b){var N=w;switch(w){case"blob":case"arraybuffer":N="uint8array";break;case"base64":N="string"}try{this._internalType=N,this._outputType=w,this._mimeType=b,i.checkSupport(N),this._worker=v.pipe(new l(N)),v.lock()}catch(S){this._worker=new o("error"),this._worker.error(S)}}y.prototype={accumulate:function(v){return x(this,v)},on:function(v,w){var b=this;return v==="data"?this._worker.on(v,function(N){w.call(b,N.data,N.meta)}):this._worker.on(v,function(){i.delay(w,arguments,b)}),this},resume:function(){return i.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(v){if(i.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new m(this,{objectMode:this._outputType!=="nodebuffer"},v)}},n.exports=y},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(r,n,a){if(a.base64=!0,a.array=!0,a.string=!0,a.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",a.nodebuffer=typeof Buffer<"u",a.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"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=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,n,a){for(var i=r("./utils"),l=r("./support"),o=r("./nodejsUtils"),c=r("./stream/GenericWorker"),d=new Array(256),h=0;h<256;h++)d[h]=252<=h?6:248<=h?5:240<=h?4:224<=h?3:192<=h?2:1;d[254]=d[254]=1;function m(){c.call(this,"utf-8 decode"),this.leftOver=null}function x(){c.call(this,"utf-8 encode")}a.utf8encode=function(y){return l.nodebuffer?o.newBufferFrom(y,"utf-8"):function(v){var w,b,N,S,T,A=v.length,I=0;for(S=0;S>>6:(b<65536?w[T++]=224|b>>>12:(w[T++]=240|b>>>18,w[T++]=128|b>>>12&63),w[T++]=128|b>>>6&63),w[T++]=128|63&b);return w}(y)},a.utf8decode=function(y){return l.nodebuffer?i.transformTo("nodebuffer",y).toString("utf-8"):function(v){var w,b,N,S,T=v.length,A=new Array(2*T);for(w=b=0;w>10&1023,A[b++]=56320|1023&N)}return A.length!==b&&(A.subarray?A=A.subarray(0,b):A.length=b),i.applyFromCharCode(A)}(y=i.transformTo(l.uint8array?"uint8array":"array",y))},i.inherits(m,c),m.prototype.processChunk=function(y){var v=i.transformTo(l.uint8array?"uint8array":"array",y.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var w=v;(v=new Uint8Array(w.length+this.leftOver.length)).set(this.leftOver,0),v.set(w,this.leftOver.length)}else v=this.leftOver.concat(v);this.leftOver=null}var b=function(S,T){var A;for((T=T||S.length)>S.length&&(T=S.length),A=T-1;0<=A&&(192&S[A])==128;)A--;return A<0||A===0?T:A+d[S[A]]>T?A:T}(v),N=v;b!==v.length&&(l.uint8array?(N=v.subarray(0,b),this.leftOver=v.subarray(b,v.length)):(N=v.slice(0,b),this.leftOver=v.slice(b,v.length))),this.push({data:a.utf8decode(N),meta:y.meta})},m.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=m,i.inherits(x,c),x.prototype.processChunk=function(y){this.push({data:a.utf8encode(y.data),meta:y.meta})},a.Utf8EncodeWorker=x},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,n,a){var i=r("./support"),l=r("./base64"),o=r("./nodejsUtils"),c=r("./external");function d(w){return w}function h(w,b){for(var N=0;N>8;this.dir=!!(16&this.externalFileAttributes),y==0&&(this.dosPermissions=63&this.externalFileAttributes),y==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var y=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=y.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=y.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=y.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=y.readInt(4))}},readExtraFields:function(y){var v,w,b,N=y.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});y.index+4>>6:(y<65536?x[b++]=224|y>>>12:(x[b++]=240|y>>>18,x[b++]=128|y>>>12&63),x[b++]=128|y>>>6&63),x[b++]=128|63&y);return x},a.buf2binstring=function(m){return h(m,m.length)},a.binstring2buf=function(m){for(var x=new i.Buf8(m.length),y=0,v=x.length;y>10&1023,S[v++]=56320|1023&w)}return h(S,v)},a.utf8border=function(m,x){var y;for((x=x||m.length)>m.length&&(x=m.length),y=x-1;0<=y&&(192&m[y])==128;)y--;return y<0||y===0?x:y+c[m[y]]>x?y:x}},{"./common":41}],43:[function(r,n,a){n.exports=function(i,l,o,c){for(var d=65535&i|0,h=i>>>16&65535|0,m=0;o!==0;){for(o-=m=2e3>>1:l>>>1;o[c]=l}return o}();n.exports=function(l,o,c,d){var h=i,m=d+c;l^=-1;for(var x=d;x>>8^h[255&(l^o[x])];return-1^l}},{}],46:[function(r,n,a){var i,l=r("../utils/common"),o=r("./trees"),c=r("./adler32"),d=r("./crc32"),h=r("./messages"),m=0,x=4,y=0,v=-2,w=-1,b=4,N=2,S=8,T=9,A=286,I=30,D=19,R=2*A+1,$=15,F=3,z=258,Q=z+F+1,K=42,X=113,Z=1,re=2,le=3,oe=4;function ne(fe,it){return fe.msg=h[it],it}function ie(fe){return(fe<<1)-(4fe.avail_out&&(Oe=fe.avail_out),Oe!==0&&(l.arraySet(fe.output,it.pending_buf,it.pending_out,Oe,fe.next_out),fe.next_out+=Oe,it.pending_out+=Oe,fe.total_out+=Oe,fe.avail_out-=Oe,it.pending-=Oe,it.pending===0&&(it.pending_out=0))}function ve(fe,it){o._tr_flush_block(fe,0<=fe.block_start?fe.block_start:-1,fe.strstart-fe.block_start,it),fe.block_start=fe.strstart,ce(fe.strm)}function be(fe,it){fe.pending_buf[fe.pending++]=it}function Ue(fe,it){fe.pending_buf[fe.pending++]=it>>>8&255,fe.pending_buf[fe.pending++]=255&it}function Be(fe,it){var Oe,Ye,We=fe.max_chain_length,_e=fe.strstart,Re=fe.prev_length,tt=fe.nice_match,Ke=fe.strstart>fe.w_size-Q?fe.strstart-(fe.w_size-Q):0,Ze=fe.window,lt=fe.w_mask,xt=fe.prev,Xe=fe.strstart+z,Je=Ze[_e+Re-1],jt=Ze[_e+Re];fe.prev_length>=fe.good_match&&(We>>=2),tt>fe.lookahead&&(tt=fe.lookahead);do if(Ze[(Oe=it)+Re]===jt&&Ze[Oe+Re-1]===Je&&Ze[Oe]===Ze[_e]&&Ze[++Oe]===Ze[_e+1]){_e+=2,Oe++;do;while(Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&Ze[++_e]===Ze[++Oe]&&_eKe&&--We!=0);return Re<=fe.lookahead?Re:fe.lookahead}function De(fe){var it,Oe,Ye,We,_e,Re,tt,Ke,Ze,lt,xt=fe.w_size;do{if(We=fe.window_size-fe.lookahead-fe.strstart,fe.strstart>=xt+(xt-Q)){for(l.arraySet(fe.window,fe.window,xt,xt,0),fe.match_start-=xt,fe.strstart-=xt,fe.block_start-=xt,it=Oe=fe.hash_size;Ye=fe.head[--it],fe.head[it]=xt<=Ye?Ye-xt:0,--Oe;);for(it=Oe=xt;Ye=fe.prev[--it],fe.prev[it]=xt<=Ye?Ye-xt:0,--Oe;);We+=xt}if(fe.strm.avail_in===0)break;if(Re=fe.strm,tt=fe.window,Ke=fe.strstart+fe.lookahead,Ze=We,lt=void 0,lt=Re.avail_in,Ze=F)for(_e=fe.strstart-fe.insert,fe.ins_h=fe.window[_e],fe.ins_h=(fe.ins_h<=F&&(fe.ins_h=(fe.ins_h<=F)if(Ye=o._tr_tally(fe,fe.strstart-fe.match_start,fe.match_length-F),fe.lookahead-=fe.match_length,fe.match_length<=fe.max_lazy_match&&fe.lookahead>=F){for(fe.match_length--;fe.strstart++,fe.ins_h=(fe.ins_h<=F&&(fe.ins_h=(fe.ins_h<=F&&fe.match_length<=fe.prev_length){for(We=fe.strstart+fe.lookahead-F,Ye=o._tr_tally(fe,fe.strstart-1-fe.prev_match,fe.prev_length-F),fe.lookahead-=fe.prev_length-1,fe.prev_length-=2;++fe.strstart<=We&&(fe.ins_h=(fe.ins_h<fe.pending_buf_size-5&&(Oe=fe.pending_buf_size-5);;){if(fe.lookahead<=1){if(De(fe),fe.lookahead===0&&it===m)return Z;if(fe.lookahead===0)break}fe.strstart+=fe.lookahead,fe.lookahead=0;var Ye=fe.block_start+Oe;if((fe.strstart===0||fe.strstart>=Ye)&&(fe.lookahead=fe.strstart-Ye,fe.strstart=Ye,ve(fe,!1),fe.strm.avail_out===0)||fe.strstart-fe.block_start>=fe.w_size-Q&&(ve(fe,!1),fe.strm.avail_out===0))return Z}return fe.insert=0,it===x?(ve(fe,!0),fe.strm.avail_out===0?le:oe):(fe.strstart>fe.block_start&&(ve(fe,!1),fe.strm.avail_out),Z)}),new Le(4,4,8,4,Ae),new Le(4,5,16,8,Ae),new Le(4,6,32,32,Ae),new Le(4,4,16,16,He),new Le(8,16,32,32,He),new Le(8,16,128,128,He),new Le(8,32,128,256,He),new Le(32,128,258,1024,He),new Le(32,258,258,4096,He)],a.deflateInit=function(fe,it){return et(fe,it,S,15,8,0)},a.deflateInit2=et,a.deflateReset=xe,a.deflateResetKeep=Te,a.deflateSetHeader=function(fe,it){return fe&&fe.state?fe.state.wrap!==2?v:(fe.state.gzhead=it,y):v},a.deflate=function(fe,it){var Oe,Ye,We,_e;if(!fe||!fe.state||5>8&255),be(Ye,Ye.gzhead.time>>16&255),be(Ye,Ye.gzhead.time>>24&255),be(Ye,Ye.level===9?2:2<=Ye.strategy||Ye.level<2?4:0),be(Ye,255&Ye.gzhead.os),Ye.gzhead.extra&&Ye.gzhead.extra.length&&(be(Ye,255&Ye.gzhead.extra.length),be(Ye,Ye.gzhead.extra.length>>8&255)),Ye.gzhead.hcrc&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending,0)),Ye.gzindex=0,Ye.status=69):(be(Ye,0),be(Ye,0),be(Ye,0),be(Ye,0),be(Ye,0),be(Ye,Ye.level===9?2:2<=Ye.strategy||Ye.level<2?4:0),be(Ye,3),Ye.status=X);else{var Re=S+(Ye.w_bits-8<<4)<<8;Re|=(2<=Ye.strategy||Ye.level<2?0:Ye.level<6?1:Ye.level===6?2:3)<<6,Ye.strstart!==0&&(Re|=32),Re+=31-Re%31,Ye.status=X,Ue(Ye,Re),Ye.strstart!==0&&(Ue(Ye,fe.adler>>>16),Ue(Ye,65535&fe.adler)),fe.adler=1}if(Ye.status===69)if(Ye.gzhead.extra){for(We=Ye.pending;Ye.gzindex<(65535&Ye.gzhead.extra.length)&&(Ye.pending!==Ye.pending_buf_size||(Ye.gzhead.hcrc&&Ye.pending>We&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending-We,We)),ce(fe),We=Ye.pending,Ye.pending!==Ye.pending_buf_size));)be(Ye,255&Ye.gzhead.extra[Ye.gzindex]),Ye.gzindex++;Ye.gzhead.hcrc&&Ye.pending>We&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending-We,We)),Ye.gzindex===Ye.gzhead.extra.length&&(Ye.gzindex=0,Ye.status=73)}else Ye.status=73;if(Ye.status===73)if(Ye.gzhead.name){We=Ye.pending;do{if(Ye.pending===Ye.pending_buf_size&&(Ye.gzhead.hcrc&&Ye.pending>We&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending-We,We)),ce(fe),We=Ye.pending,Ye.pending===Ye.pending_buf_size)){_e=1;break}_e=Ye.gzindexWe&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending-We,We)),_e===0&&(Ye.gzindex=0,Ye.status=91)}else Ye.status=91;if(Ye.status===91)if(Ye.gzhead.comment){We=Ye.pending;do{if(Ye.pending===Ye.pending_buf_size&&(Ye.gzhead.hcrc&&Ye.pending>We&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending-We,We)),ce(fe),We=Ye.pending,Ye.pending===Ye.pending_buf_size)){_e=1;break}_e=Ye.gzindexWe&&(fe.adler=d(fe.adler,Ye.pending_buf,Ye.pending-We,We)),_e===0&&(Ye.status=103)}else Ye.status=103;if(Ye.status===103&&(Ye.gzhead.hcrc?(Ye.pending+2>Ye.pending_buf_size&&ce(fe),Ye.pending+2<=Ye.pending_buf_size&&(be(Ye,255&fe.adler),be(Ye,fe.adler>>8&255),fe.adler=0,Ye.status=X)):Ye.status=X),Ye.pending!==0){if(ce(fe),fe.avail_out===0)return Ye.last_flush=-1,y}else if(fe.avail_in===0&&ie(it)<=ie(Oe)&&it!==x)return ne(fe,-5);if(Ye.status===666&&fe.avail_in!==0)return ne(fe,-5);if(fe.avail_in!==0||Ye.lookahead!==0||it!==m&&Ye.status!==666){var tt=Ye.strategy===2?function(Ke,Ze){for(var lt;;){if(Ke.lookahead===0&&(De(Ke),Ke.lookahead===0)){if(Ze===m)return Z;break}if(Ke.match_length=0,lt=o._tr_tally(Ke,0,Ke.window[Ke.strstart]),Ke.lookahead--,Ke.strstart++,lt&&(ve(Ke,!1),Ke.strm.avail_out===0))return Z}return Ke.insert=0,Ze===x?(ve(Ke,!0),Ke.strm.avail_out===0?le:oe):Ke.last_lit&&(ve(Ke,!1),Ke.strm.avail_out===0)?Z:re}(Ye,it):Ye.strategy===3?function(Ke,Ze){for(var lt,xt,Xe,Je,jt=Ke.window;;){if(Ke.lookahead<=z){if(De(Ke),Ke.lookahead<=z&&Ze===m)return Z;if(Ke.lookahead===0)break}if(Ke.match_length=0,Ke.lookahead>=F&&0Ke.lookahead&&(Ke.match_length=Ke.lookahead)}if(Ke.match_length>=F?(lt=o._tr_tally(Ke,1,Ke.match_length-F),Ke.lookahead-=Ke.match_length,Ke.strstart+=Ke.match_length,Ke.match_length=0):(lt=o._tr_tally(Ke,0,Ke.window[Ke.strstart]),Ke.lookahead--,Ke.strstart++),lt&&(ve(Ke,!1),Ke.strm.avail_out===0))return Z}return Ke.insert=0,Ze===x?(ve(Ke,!0),Ke.strm.avail_out===0?le:oe):Ke.last_lit&&(ve(Ke,!1),Ke.strm.avail_out===0)?Z:re}(Ye,it):i[Ye.level].func(Ye,it);if(tt!==le&&tt!==oe||(Ye.status=666),tt===Z||tt===le)return fe.avail_out===0&&(Ye.last_flush=-1),y;if(tt===re&&(it===1?o._tr_align(Ye):it!==5&&(o._tr_stored_block(Ye,0,0,!1),it===3&&(ye(Ye.head),Ye.lookahead===0&&(Ye.strstart=0,Ye.block_start=0,Ye.insert=0))),ce(fe),fe.avail_out===0))return Ye.last_flush=-1,y}return it!==x?y:Ye.wrap<=0?1:(Ye.wrap===2?(be(Ye,255&fe.adler),be(Ye,fe.adler>>8&255),be(Ye,fe.adler>>16&255),be(Ye,fe.adler>>24&255),be(Ye,255&fe.total_in),be(Ye,fe.total_in>>8&255),be(Ye,fe.total_in>>16&255),be(Ye,fe.total_in>>24&255)):(Ue(Ye,fe.adler>>>16),Ue(Ye,65535&fe.adler)),ce(fe),0=Oe.w_size&&(_e===0&&(ye(Oe.head),Oe.strstart=0,Oe.block_start=0,Oe.insert=0),Ze=new l.Buf8(Oe.w_size),l.arraySet(Ze,it,lt-Oe.w_size,Oe.w_size,0),it=Ze,lt=Oe.w_size),Re=fe.avail_in,tt=fe.next_in,Ke=fe.input,fe.avail_in=lt,fe.next_in=0,fe.input=it,De(Oe);Oe.lookahead>=F;){for(Ye=Oe.strstart,We=Oe.lookahead-(F-1);Oe.ins_h=(Oe.ins_h<>>=F=$>>>24,T-=F,(F=$>>>16&255)===0)re[h++]=65535&$;else{if(!(16&F)){if(!(64&F)){$=A[(65535&$)+(S&(1<>>=F,T-=F),T<15&&(S+=Z[c++]<>>=F=$>>>24,T-=F,!(16&(F=$>>>16&255))){if(!(64&F)){$=I[(65535&$)+(S&(1<>>=F,T-=F,(F=h-m)>3,S&=(1<<(T-=z<<3))-1,i.next_in=c,i.next_out=h,i.avail_in=c>>24&255)+(K>>>8&65280)+((65280&K)<<8)+((255&K)<<24)}function S(){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 T(K){var X;return K&&K.state?(X=K.state,K.total_in=K.total_out=X.total=0,K.msg="",X.wrap&&(K.adler=1&X.wrap),X.mode=v,X.last=0,X.havedict=0,X.dmax=32768,X.head=null,X.hold=0,X.bits=0,X.lencode=X.lendyn=new i.Buf32(w),X.distcode=X.distdyn=new i.Buf32(b),X.sane=1,X.back=-1,x):y}function A(K){var X;return K&&K.state?((X=K.state).wsize=0,X.whave=0,X.wnext=0,T(K)):y}function I(K,X){var Z,re;return K&&K.state?(re=K.state,X<0?(Z=0,X=-X):(Z=1+(X>>4),X<48&&(X&=15)),X&&(X<8||15=oe.wsize?(i.arraySet(oe.window,X,Z-oe.wsize,oe.wsize,0),oe.wnext=0,oe.whave=oe.wsize):(re<(le=oe.wsize-oe.wnext)&&(le=re),i.arraySet(oe.window,X,Z-re,le,oe.wnext),(re-=le)?(i.arraySet(oe.window,X,Z-re,re,0),oe.wnext=re,oe.whave=oe.wsize):(oe.wnext+=le,oe.wnext===oe.wsize&&(oe.wnext=0),oe.whave>>8&255,Z.check=o(Z.check,_e,2,0),ve=ce=0,Z.mode=2;break}if(Z.flags=0,Z.head&&(Z.head.done=!1),!(1&Z.wrap)||(((255&ce)<<8)+(ce>>8))%31){K.msg="incorrect header check",Z.mode=30;break}if((15&ce)!=8){K.msg="unknown compression method",Z.mode=30;break}if(ve-=4,fe=8+(15&(ce>>>=4)),Z.wbits===0)Z.wbits=fe;else if(fe>Z.wbits){K.msg="invalid window size",Z.mode=30;break}Z.dmax=1<>8&1),512&Z.flags&&(_e[0]=255&ce,_e[1]=ce>>>8&255,Z.check=o(Z.check,_e,2,0)),ve=ce=0,Z.mode=3;case 3:for(;ve<32;){if(ie===0)break e;ie--,ce+=re[oe++]<>>8&255,_e[2]=ce>>>16&255,_e[3]=ce>>>24&255,Z.check=o(Z.check,_e,4,0)),ve=ce=0,Z.mode=4;case 4:for(;ve<16;){if(ie===0)break e;ie--,ce+=re[oe++]<>8),512&Z.flags&&(_e[0]=255&ce,_e[1]=ce>>>8&255,Z.check=o(Z.check,_e,2,0)),ve=ce=0,Z.mode=5;case 5:if(1024&Z.flags){for(;ve<16;){if(ie===0)break e;ie--,ce+=re[oe++]<>>8&255,Z.check=o(Z.check,_e,2,0)),ve=ce=0}else Z.head&&(Z.head.extra=null);Z.mode=6;case 6:if(1024&Z.flags&&(ie<(Be=Z.length)&&(Be=ie),Be&&(Z.head&&(fe=Z.head.extra_len-Z.length,Z.head.extra||(Z.head.extra=new Array(Z.head.extra_len)),i.arraySet(Z.head.extra,re,oe,Be,fe)),512&Z.flags&&(Z.check=o(Z.check,re,Be,oe)),ie-=Be,oe+=Be,Z.length-=Be),Z.length))break e;Z.length=0,Z.mode=7;case 7:if(2048&Z.flags){if(ie===0)break e;for(Be=0;fe=re[oe+Be++],Z.head&&fe&&Z.length<65536&&(Z.head.name+=String.fromCharCode(fe)),fe&&Be>9&1,Z.head.done=!0),K.adler=Z.check=0,Z.mode=12;break;case 10:for(;ve<32;){if(ie===0)break e;ie--,ce+=re[oe++]<>>=7&ve,ve-=7&ve,Z.mode=27;break}for(;ve<3;){if(ie===0)break e;ie--,ce+=re[oe++]<>>=1)){case 0:Z.mode=14;break;case 1:if(z(Z),Z.mode=20,X!==6)break;ce>>>=2,ve-=2;break e;case 2:Z.mode=17;break;case 3:K.msg="invalid block type",Z.mode=30}ce>>>=2,ve-=2;break;case 14:for(ce>>>=7&ve,ve-=7&ve;ve<32;){if(ie===0)break e;ie--,ce+=re[oe++]<>>16^65535)){K.msg="invalid stored block lengths",Z.mode=30;break}if(Z.length=65535&ce,ve=ce=0,Z.mode=15,X===6)break e;case 15:Z.mode=16;case 16:if(Be=Z.length){if(ie>>=5,ve-=5,Z.ndist=1+(31&ce),ce>>>=5,ve-=5,Z.ncode=4+(15&ce),ce>>>=4,ve-=4,286>>=3,ve-=3}for(;Z.have<19;)Z.lens[Re[Z.have++]]=0;if(Z.lencode=Z.lendyn,Z.lenbits=7,Oe={bits:Z.lenbits},it=d(0,Z.lens,0,19,Z.lencode,0,Z.work,Oe),Z.lenbits=Oe.bits,it){K.msg="invalid code lengths set",Z.mode=30;break}Z.have=0,Z.mode=19;case 19:for(;Z.have>>16&255,Ie=65535&We,!((He=We>>>24)<=ve);){if(ie===0)break e;ie--,ce+=re[oe++]<>>=He,ve-=He,Z.lens[Z.have++]=Ie;else{if(Ie===16){for(Ye=He+2;ve>>=He,ve-=He,Z.have===0){K.msg="invalid bit length repeat",Z.mode=30;break}fe=Z.lens[Z.have-1],Be=3+(3&ce),ce>>>=2,ve-=2}else if(Ie===17){for(Ye=He+3;ve>>=He)),ce>>>=3,ve-=3}else{for(Ye=He+7;ve>>=He)),ce>>>=7,ve-=7}if(Z.have+Be>Z.nlen+Z.ndist){K.msg="invalid bit length repeat",Z.mode=30;break}for(;Be--;)Z.lens[Z.have++]=fe}}if(Z.mode===30)break;if(Z.lens[256]===0){K.msg="invalid code -- missing end-of-block",Z.mode=30;break}if(Z.lenbits=9,Oe={bits:Z.lenbits},it=d(h,Z.lens,0,Z.nlen,Z.lencode,0,Z.work,Oe),Z.lenbits=Oe.bits,it){K.msg="invalid literal/lengths set",Z.mode=30;break}if(Z.distbits=6,Z.distcode=Z.distdyn,Oe={bits:Z.distbits},it=d(m,Z.lens,Z.nlen,Z.ndist,Z.distcode,0,Z.work,Oe),Z.distbits=Oe.bits,it){K.msg="invalid distances set",Z.mode=30;break}if(Z.mode=20,X===6)break e;case 20:Z.mode=21;case 21:if(6<=ie&&258<=ye){K.next_out=ne,K.avail_out=ye,K.next_in=oe,K.avail_in=ie,Z.hold=ce,Z.bits=ve,c(K,Ue),ne=K.next_out,le=K.output,ye=K.avail_out,oe=K.next_in,re=K.input,ie=K.avail_in,ce=Z.hold,ve=Z.bits,Z.mode===12&&(Z.back=-1);break}for(Z.back=0;Le=(We=Z.lencode[ce&(1<>>16&255,Ie=65535&We,!((He=We>>>24)<=ve);){if(ie===0)break e;ie--,ce+=re[oe++]<>Te)])>>>16&255,Ie=65535&We,!(Te+(He=We>>>24)<=ve);){if(ie===0)break e;ie--,ce+=re[oe++]<>>=Te,ve-=Te,Z.back+=Te}if(ce>>>=He,ve-=He,Z.back+=He,Z.length=Ie,Le===0){Z.mode=26;break}if(32&Le){Z.back=-1,Z.mode=12;break}if(64&Le){K.msg="invalid literal/length code",Z.mode=30;break}Z.extra=15&Le,Z.mode=22;case 22:if(Z.extra){for(Ye=Z.extra;ve>>=Z.extra,ve-=Z.extra,Z.back+=Z.extra}Z.was=Z.length,Z.mode=23;case 23:for(;Le=(We=Z.distcode[ce&(1<>>16&255,Ie=65535&We,!((He=We>>>24)<=ve);){if(ie===0)break e;ie--,ce+=re[oe++]<>Te)])>>>16&255,Ie=65535&We,!(Te+(He=We>>>24)<=ve);){if(ie===0)break e;ie--,ce+=re[oe++]<>>=Te,ve-=Te,Z.back+=Te}if(ce>>>=He,ve-=He,Z.back+=He,64&Le){K.msg="invalid distance code",Z.mode=30;break}Z.offset=Ie,Z.extra=15&Le,Z.mode=24;case 24:if(Z.extra){for(Ye=Z.extra;ve>>=Z.extra,ve-=Z.extra,Z.back+=Z.extra}if(Z.offset>Z.dmax){K.msg="invalid distance too far back",Z.mode=30;break}Z.mode=25;case 25:if(ye===0)break e;if(Be=Ue-ye,Z.offset>Be){if((Be=Z.offset-Be)>Z.whave&&Z.sane){K.msg="invalid distance too far back",Z.mode=30;break}De=Be>Z.wnext?(Be-=Z.wnext,Z.wsize-Be):Z.wnext-Be,Be>Z.length&&(Be=Z.length),Ae=Z.window}else Ae=le,De=ne-Z.offset,Be=Z.length;for(yeR?(F=De[Ae+b[X]],ve[be+b[X]]):(F=96,0),S=1<>ne)+(T-=S)]=$<<24|F<<16|z|0,T!==0;);for(S=1<>=1;if(S!==0?(ce&=S-1,ce+=S):ce=0,X++,--Ue[K]==0){if(K===re)break;K=m[x+b[X]]}if(le>>7)]}function be(We,_e){We.pending_buf[We.pending++]=255&_e,We.pending_buf[We.pending++]=_e>>>8&255}function Ue(We,_e,Re){We.bi_valid>N-Re?(We.bi_buf|=_e<>N-We.bi_valid,We.bi_valid+=Re-N):(We.bi_buf|=_e<>>=1,Re<<=1,0<--_e;);return Re>>>1}function Ae(We,_e,Re){var tt,Ke,Ze=new Array(b+1),lt=0;for(tt=1;tt<=b;tt++)Ze[tt]=lt=lt+Re[tt-1]<<1;for(Ke=0;Ke<=_e;Ke++){var xt=We[2*Ke+1];xt!==0&&(We[2*Ke]=De(Ze[xt]++,xt))}}function He(We){var _e;for(_e=0;_e>1;1<=Re;Re--)Te(We,Ze,Re);for(Ke=Xe;Re=We.heap[1],We.heap[1]=We.heap[We.heap_len--],Te(We,Ze,1),tt=We.heap[1],We.heap[--We.heap_max]=Re,We.heap[--We.heap_max]=tt,Ze[2*Ke]=Ze[2*Re]+Ze[2*tt],We.depth[Ke]=(We.depth[Re]>=We.depth[tt]?We.depth[Re]:We.depth[tt])+1,Ze[2*Re+1]=Ze[2*tt+1]=Ke,We.heap[1]=Ke++,Te(We,Ze,1),2<=We.heap_len;);We.heap[--We.heap_max]=We.heap[1],function(jt,ns){var Ns,Ys,rs,bt,cs,yt,is=ns.dyn_tree,Bs=ns.max_code,ps=ns.stat_desc.static_tree,lr=ns.stat_desc.has_stree,kr=ns.stat_desc.extra_bits,Lr=ns.stat_desc.extra_base,qr=ns.stat_desc.max_length,Ur=0;for(bt=0;bt<=b;bt++)jt.bl_count[bt]=0;for(is[2*jt.heap[jt.heap_max]+1]=0,Ns=jt.heap_max+1;Ns>=7;Ke>>=1)if(1&Je&&xt.dyn_ltree[2*Xe]!==0)return l;if(xt.dyn_ltree[18]!==0||xt.dyn_ltree[20]!==0||xt.dyn_ltree[26]!==0)return o;for(Xe=32;Xe>>3,(Ze=We.static_len+3+7>>>3)<=Ke&&(Ke=Ze)):Ke=Ze=Re+5,Re+4<=Ke&&_e!==-1?Ye(We,_e,Re,tt):We.strategy===4||Ze===Ke?(Ue(We,2+(tt?1:0),3),xe(We,Q,K)):(Ue(We,4+(tt?1:0),3),function(xt,Xe,Je,jt){var ns;for(Ue(xt,Xe-257,5),Ue(xt,Je-1,5),Ue(xt,jt-4,4),ns=0;ns>>8&255,We.pending_buf[We.d_buf+2*We.last_lit+1]=255&_e,We.pending_buf[We.l_buf+We.last_lit]=255&Re,We.last_lit++,_e===0?We.dyn_ltree[2*Re]++:(We.matches++,_e--,We.dyn_ltree[2*(Z[Re]+m+1)]++,We.dyn_dtree[2*ve(_e)]++),We.last_lit===We.lit_bufsize-1},a._tr_align=function(We){Ue(We,2,3),Be(We,T,Q),function(_e){_e.bi_valid===16?(be(_e,_e.bi_buf),_e.bi_buf=0,_e.bi_valid=0):8<=_e.bi_valid&&(_e.pending_buf[_e.pending++]=255&_e.bi_buf,_e.bi_buf>>=8,_e.bi_valid-=8)}(We)}},{"../utils/common":41}],53:[function(r,n,a){n.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(r,n,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,h,m,x=1,y={},v=!1,w=l.document,b=Object.getPrototypeOf&&Object.getPrototypeOf(l);b=b&&b.setTimeout?b:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){S(A)})}:function(){if(l.postMessage&&!l.importScripts){var A=!0,I=l.onmessage;return l.onmessage=function(){A=!1},l.postMessage("","*"),l.onmessage=I,A}}()?(m="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",T,!1):l.attachEvent("onmessage",T),function(A){l.postMessage(m+A,"*")}):l.MessageChannel?((h=new MessageChannel).port1.onmessage=function(A){S(A.data)},function(A){h.port2.postMessage(A)}):w&&"onreadystatechange"in w.createElement("script")?(d=w.documentElement,function(A){var I=w.createElement("script");I.onreadystatechange=function(){S(A),I.onreadystatechange=null,d.removeChild(I),I=null},d.appendChild(I)}):function(A){setTimeout(S,0,A)},b.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var I=new Array(arguments.length-1),D=0;D"u"?i===void 0?this:i:self)}).call(this,typeof Zd<"u"?Zd:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Eot);var lJt=Eot.exports;const cJt=Ao(lJt);function S1e(s,t=400,r=75){return s&&`${s.replace("/storage/v1/object/public/","/storage/v1/render/image/public/")}?width=${t}&quality=${r}&resize=contain`}const dJt=()=>{js();const[s,t]=k.useState(null),[r,n]=k.useState(null),[a,i]=k.useState("all"),[l,o]=k.useState(new Set),[c,d]=k.useState(!1),[h,m]=k.useState(!1),[x,y]=k.useState("images"),[v,w]=k.useState(null),{data:b=[],isLoading:N}=mt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:ne,error:ie}=await V.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ie)throw ie;return ne}}),{data:S=[]}=mt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:ne,error:ie}=await V.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ie)throw ie;return ne}}),{data:T=[]}=mt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:ne,error:ie}=await V.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ie)throw ie;return ne}}),{data:A=[]}=mt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:ne,error:ie}=await V.from("social_accounts").select("id, platform").eq("is_active",!0);if(ie)throw ie;return ne||[]}}),I=A.length>0,D=k.useMemo(()=>a==="all"?null:T.find(ne=>ne.month===a)||null,[a,T]),R=k.useMemo(()=>[...new Set(b.map(ie=>ie.month))].sort((ie,ye)=>ye.localeCompare(ie)),[b]);k.useEffect(()=>{R.length>0&&a==="all"&&i(R[0])},[R,a]);const $=ne=>{try{const ie=r4e(ne,"yyyy-MM",new Date);return _s(ie,"MMMM yyyy")}catch{return ne}},F=k.useMemo(()=>a==="all"?b:b.filter(ne=>ne.month===a),[a,b]),z=k.useMemo(()=>{var ne;return a==="all"?null:((ne=S.find(ie=>ie.month===a))==null?void 0:ne.canva_link)||null},[a,S]),Q=async ne=>{try{await navigator.clipboard.writeText(ne),ue.success("Caption copied to clipboard!")}catch{ue.error("Failed to copy caption")}},K=async(ne,ie)=>{try{const ce=await(await fetch(ne)).blob(),ve=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),be=navigator.canShare&&navigator.canShare({files:[new File([ce],"test.jpg",{type:"image/jpeg"})]});if(ve&&be){const Ue=new File([ce],`social-swag-${ie}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Ue],title:"Social Swag Image"}),ue.success("Image ready to save!")}else{const Ue=window.URL.createObjectURL(ce),Be=document.createElement("a");Be.href=Ue,Be.download=`social-swag-${ie}.jpg`,document.body.appendChild(Be),Be.click(),document.body.removeChild(Be),window.URL.revokeObjectURL(Ue),ue.success("Image downloaded!")}}catch(ye){ye.name!=="AbortError"&&ue.error("Failed to download image")}},X=ne=>{o(ie=>{const ye=new Set(ie);return ye.has(ne)?ye.delete(ne):ye.add(ne),ye})},Z=()=>{o(new Set(F.map(ne=>ne.id)))},re=()=>{o(new Set),d(!1)},le=async()=>{const ne=F.filter(ie=>l.has(ie.id));if(ne.length===0){ue.error("No images selected");return}m(!0),ue.info(`Preparing ${ne.length} images for download...`);try{const ie=new cJt,ye=[...ne].sort((Be,De)=>Be.sort_order-De.sort_order);for(let Be=0;Be{c?X(ne.id):t(ne)};return e.jsx(ws,{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(Ge,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(jr,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Ge,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(ml,{className:"h-3 w-3 mr-1"}),b.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(On,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(Rn,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Kt,{value:"gallery",className:"gap-2",children:[e.jsx(ml,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Kt,{value:"scheduled",className:"gap-2",children:[e.jsx(hd,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(ts,{value:"gallery",className:"space-y-6",children:[I?e.jsx(ke,{className:"border rounded-xl",children:e.jsx(Pe,{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(G,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(Yn,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(ke,{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(Pe,{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(yu,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Jd,{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(G,{asChild:!0,className:"gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600",children:e.jsxs(Yn,{to:"/social-connections",children:[e.jsx(tl,{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:R.map(ne=>e.jsx("button",{onClick:()=>i(ne),className:It("px-4 py-2 rounded-full text-sm font-medium transition-all",a===ne?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:$(ne)},ne))}),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 ",$(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 ",$(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:()=>{y("images"),re()},className:It("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(ml,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{y("reels"),re()},className:It("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(gh,{className:"h-4 w-4"}),"Reels"]})]}),x==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:c?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:Z,className:"gap-2",children:["Select All (",F.length,")"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:re,className:"gap-2",children:[e.jsx(vr,{className:"h-4 w-4"}),"Cancel"]}),l.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(G,{size:"sm",onClick:le,disabled:h,className:"gap-2",children:[e.jsx(Ya,{className:"h-4 w-4"}),h?"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(G,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"gap-2",children:[e.jsx(Kn,{className:"h-4 w-4"}),"Select Images"]})})]}),N&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!N&&x==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:F.map(ne=>{const ie=l.has(ne.id);return e.jsx(ke,{className:It("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&ie&&"ring-2 ring-primary ring-offset-2"),onClick:()=>oe(ne),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:S1e(ne.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"}),ne.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:_s(new Date(ne.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:It("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ie?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ie&&e.jsx(Kn,{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"})})]})},ne.id)})}),F.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ml,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!N&&x==="reels"&&e.jsx(e.Fragment,{children:D?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(ke,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>n(D),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:S1e(D.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(Ge,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(gh,{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(gh,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No reel available for this month yet."})]})})]}),e.jsx(fs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(ms,{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:S1e(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(on,{className:"h-4 w-4"}),_s(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(on,{className:"h-3.5 w-3.5"}),"Post on ",_s(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(G,{onClick:()=>{w({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(en,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(G,{variant:"outline",onClick:()=>Q(s.caption),className:"flex-1 gap-2",children:[e.jsx(Ra,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(G,{variant:"outline",onClick:()=>K(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(Ya,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(fs,{open:!!r,onOpenChange:()=>n(null),children:e.jsx(ms,{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:r&&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:r.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(gh,{className:"h-4 w-4"}),"Monthly Reel"]}),r.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:r.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[r.caption&&e.jsxs(G,{onClick:()=>Q(r.caption||""),className:"flex-1 gap-2",children:[e.jsx(Ra,{className:"h-4 w-4"}),"Copy Caption"]}),r.canva_link&&e.jsxs(G,{variant:"outline",onClick:()=>window.open(r.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Qr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(iJt,{open:!!v,onOpenChange:ne=>!ne&&w(null),imageUrl:(v==null?void 0:v.imageUrl)||"",imageId:(v==null?void 0:v.imageId)||"",defaultCaption:(v==null?void 0:v.caption)||"",swagItemId:v==null?void 0:v.imageId})]}),e.jsx(ts,{value:"scheduled",children:e.jsx(oJt,{})})]})]})})},uJt=()=>{const{swagId:s}=Ki(),{user:t}=js(),{toast:r}=Ma(),n=Xt(),{trackEngagement:a}=GI(),[i,l]=k.useState(""),{data:o,isLoading:c}=mt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:N,error:S}=await V.from("social_swag").select("*").eq("id",s).single();if(S)throw S;const{data:T}=await V.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...N,links:T||[]}},enabled:!!s});k.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=mt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:N,error:S}=await V.from("social_swag_likes").select("*").eq("swag_id",s);if(S)throw S;return N},enabled:!!s}),{data:h=[]}=mt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:N,error:S}=await V.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(S)throw S;const T=[...new Set(N.map(D=>D.user_id))],{data:A}=await V.from("profiles").select("id, name").in("id",T),I=new Map((A==null?void 0:A.map(D=>[D.id,D.name]))||[]);return N.map(D=>({...D,user_name:I.get(D.user_id)||"Unknown User"}))},enabled:!!s}),m=Ct({mutationFn:async N=>{const{error:S}=await V.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:N});if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),r({title:"Comment added!"})},onError:N=>{r({title:"Error adding comment",description:N.message,variant:"destructive"})}}),x=Ct({mutationFn:async N=>{const{error:S}=await V.from("social_swag_comments").delete().eq("id",N);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-comments",s]}),r({title:"Comment deleted"})}}),y=Ct({mutationFn:async()=>{const N=d.find(S=>S.user_id===(t==null?void 0:t.id));if(N){const{error:S}=await V.from("social_swag_likes").delete().eq("id",N.id);if(S)throw S}else{const{error:S}=await V.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-likes",s]})}}),v=d.some(N=>N.user_id===(t==null?void 0:t.id)),w=N=>N.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=N=>{N.preventDefault(),!(!i.trim()||!t)&&m.mutate(i.trim())};return c?e.jsx(ws,{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(ws,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/social-swag",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Social Swag"]})}),o.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:o.preview_image_url,alt:o.title,className:"w-full max-h-[500px] object-contain"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:o.title})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ZI,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(G,{variant:v?"default":"outline",className:"gap-2 w-fit",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx(jh,{className:`h-4 w-4 ${v?"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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(po,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(N=>e.jsxs(G,{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(N.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:N.title}),e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground"})]},N.id))})]})}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Jl,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(or,{placeholder:"Add a comment...",value:i,onChange:N=>l(N.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(G,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||m.isPending,children:e.jsx(en,{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(ke,{children:e.jsx(Pe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(N=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nn,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(kn,{className:"text-sm",children:w(N.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:N.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:rl(new Date(N.created_at),{addSuffix:!0})}),N.user_id===(t==null?void 0:t.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(N.id),children:e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]})]})})},N.id))})]})]})}):e.jsx(ws,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(po,{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(G,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/social-swag",children:"Back to Social Swag"})})]})})},hJt=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,h]=k.useState(!0),m=x=>x.split(" ").map(y=>y[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(G,{variant:r==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>n("all"),children:[e.jsx(Jw,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(Gp,{open:i,onOpenChange:l,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{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(Wi,{className:"h-4 w-4"}):e.jsx(va,{className:"h-4 w-4"})]})}),e.jsx(Kp,{className:"space-y-1 pl-2",children:s.map(x=>e.jsxs(G,{variant:r===x.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(x.id),children:[e.jsx("span",{className:"mr-2",children:x.icon||"📂"}),e.jsx("span",{className:"truncate",children:x.name})]},x.id))})]}),t.length>0&&e.jsxs(Gp,{open:o,onOpenChange:c,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{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(Hc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(Wi,{className:"h-4 w-4"}):e.jsx(va,{className:"h-4 w-4"})]})}),e.jsx(Kp,{className:"space-y-1 pl-2",children:t.map(x=>e.jsxs(G,{variant:r===`group:${x.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>n(`group:${x.id}`),children:[e.jsx("span",{className:"mr-2",children:x.icon||"🔒"}),e.jsx("span",{className:"truncate",children:x.name})]},x.id))})]}),e.jsxs(Gp,{open:d,onOpenChange:h,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{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(pr,{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(Wi,{className:"h-4 w-4"}):e.jsx(va,{className:"h-4 w-4"})]})}),e.jsx(Kp,{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(x=>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(Nn,{className:"h-7 w-7",children:[e.jsx(ya,{src:x.avatarUrl}),e.jsx(kn,{className:"text-xs",children:m(x.name)})]}),e.jsx(Ld,{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:x.name})]},x.id))})]})]})})})},mJt=({categories:s,privateGroups:t,selectedFilter:r,onFilterChange:n,onlineUsers:a})=>{const[i,l]=k.useState(!1),o=d=>d.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2),c=()=>{if(r==="all")return"All Posts";if(r.startsWith("group:")){const h=r.replace("group:",""),m=t.find(x=>x.id===h);return m?`🔒 ${m.name}`:"Private Group"}const d=s.find(h=>h.id===r);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Wi,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(xd,{className:"w-56 bg-background border",children:[e.jsxs(Pa,{onClick:()=>n("all"),children:[e.jsx(Jw,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(_v,{}),e.jsx(m8,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Pa,{onClick:()=>n(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(_v,{}),e.jsxs(m8,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Hc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Pa,{onClick:()=>n(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(Jj,{open:i,onOpenChange:l,children:[e.jsx(o4e,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(pr,{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(Vb,{children:[e.jsx(e2,{children:e.jsxs(t2,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Qa,{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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:d.avatarUrl}),e.jsx(kn,{children:o(d.name)})]}),e.jsx(Ld,{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 C1e,upe="HoverCard",[Aot,VUs]=pd(upe,[Pv]),hpe=Pv(),[fJt,u5e]=Aot(upe),Mot=s=>{const{__scopeHoverCard:t,children:r,open:n,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=hpe(t),d=k.useRef(0),h=k.useRef(0),m=k.useRef(!1),x=k.useRef(!1),[y,v]=Sh({prop:n,defaultProp:a??!1,onChange:i,caller:upe}),w=k.useCallback(()=>{clearTimeout(h.current),d.current=window.setTimeout(()=>v(!0),l)},[l,v]),b=k.useCallback(()=>{clearTimeout(d.current),!m.current&&!x.current&&(h.current=window.setTimeout(()=>v(!1),o))},[o,v]),N=k.useCallback(()=>v(!1),[v]);return k.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(h.current)},[]),e.jsx(fJt,{scope:t,open:y,onOpenChange:v,onOpen:w,onClose:b,onDismiss:N,hasSelectionRef:m,isPointerDownOnContentRef:x,children:e.jsx(qF,{...c,children:r})})};Mot.displayName=upe;var Iot="HoverCardTrigger",Lot=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=u5e(Iot,r),i=hpe(r);return e.jsx(PI,{asChild:!0,...i,children:e.jsx(wn.a,{"data-state":a.open?"open":"closed",...n,ref:t,onPointerEnter:Vr(s.onPointerEnter,Fue(a.onOpen)),onPointerLeave:Vr(s.onPointerLeave,Fue(a.onClose)),onFocus:Vr(s.onFocus,a.onOpen),onBlur:Vr(s.onBlur,a.onClose),onTouchStart:Vr(s.onTouchStart,l=>l.preventDefault())})})});Lot.displayName=Iot;var pJt="HoverCardPortal",[HUs,xJt]=Aot(pJt,{forceMount:void 0}),Oue="HoverCardContent",Pot=k.forwardRef((s,t)=>{const r=xJt(Oue,s.__scopeHoverCard),{forceMount:n=r.forceMount,...a}=s,i=u5e(Oue,s.__scopeHoverCard);return e.jsx(ru,{present:n||i.open,children:e.jsx(gJt,{"data-state":i.open?"open":"closed",...a,onPointerEnter:Vr(s.onPointerEnter,Fue(i.onOpen)),onPointerLeave:Vr(s.onPointerLeave,Fue(i.onClose)),ref:t})})});Pot.displayName=Oue;var gJt=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=u5e(Oue,r),d=hpe(r),h=k.useRef(null),m=Ga(t,h),[x,y]=k.useState(!1);return k.useEffect(()=>{if(x){const v=document.body;return C1e=v.style.userSelect||v.style.webkitUserSelect,v.style.userSelect="none",v.style.webkitUserSelect="none",()=>{v.style.userSelect=C1e,v.style.webkitUserSelect=C1e}}},[x]),k.useEffect(()=>{if(h.current){const v=()=>{y(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var b;((b=document.getSelection())==null?void 0:b.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",v),()=>{document.removeEventListener("pointerup",v),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),k.useEffect(()=>{h.current&&bJt(h.current).forEach(w=>w.setAttribute("tabindex","-1"))}),e.jsx(Hj,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:Vr(i,v=>{v.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(VF,{...d,...o,onPointerDown:Vr(o.onPointerDown,v=>{v.currentTarget.contains(v.target)&&y(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:m,style:{...o.style,userSelect:x?"text":void 0,WebkitUserSelect:x?"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)"}})})}),yJt="HoverCardArrow",vJt=k.forwardRef((s,t)=>{const{__scopeHoverCard:r,...n}=s,a=hpe(r);return e.jsx(HF,{...a,...n,ref:t})});vJt.displayName=yJt;function Fue(s){return t=>t.pointerType==="touch"?void 0:s()}function bJt(s){const t=[],r=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;r.nextNode();)t.push(r.currentNode);return t}var _Jt=Mot,wJt=Lot,Dot=Pot;const jJt=_Jt,NJt=wJt,Rot=k.forwardRef(({className:s,align:t="center",sideOffset:r=4,...n},a)=>e.jsx(Dot,{ref:a,align:t,sideOffset:r,className:It("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),...n}));Rot.displayName=Dot.displayName;const kJt=[{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"}],SJt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),Oot=({reactions:s,children:t})=>{if(s.length===0)return e.jsx(e.Fragment,{children:t});const r={};return s.forEach(n=>{r[n.reaction_type]||(r[n.reaction_type]=[]),r[n.reaction_type].push(n)}),e.jsxs(jJt,{openDelay:200,closeDelay:100,children:[e.jsx(NJt,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(Rot,{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(r).map(([n,a])=>{const i=kJt.find(l=>l.type===n);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(Nn,{className:"h-6 w-6",children:[e.jsx(ya,{src:l.user_avatar||void 0}),e.jsx(kn,{className:"text-[10px]",children:SJt(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"]})]})]},n)})})})]})};function CJt({images:s,initialIndex:t=0,open:r,onOpenChange:n}){const[a,i]=k.useState(t),[l,o]=k.useState(!1);k.useEffect(()=>{r&&(i(t),o(!1))},[r,t]);const c=()=>{i(x=>x>0?x-1:s.length-1),o(!1)},d=()=>{i(x=>x{r&&(x.key==="ArrowLeft"&&c(),x.key==="ArrowRight"&&d(),x.key==="Escape"&&n(!1))},[r,s.length]);k.useEffect(()=>(window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)),[h]);const m=s[a];return e.jsx(fs,{open:r,onOpenChange:n,children:e.jsxs(ms,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>n(!1),children:e.jsx(vr,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(G,{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($o,{className:"h-8 w-8"})}),e.jsx(G,{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(va,{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]}),(m==null?void 0:m.type)==="image"&&e.jsx(G,{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(EA,{className:"h-5 w-5"}):e.jsx(dj,{className:"h-5 w-5"})}),e.jsx("div",{className:It("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(m==null?void 0:m.type)==="image"&&o(!l),children:(m==null?void 0:m.type)==="video"?e.jsx("video",{src:m.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:x=>x.stopPropagation()}):e.jsx("img",{src:m==null?void 0:m.url,alt:"",className:It("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((x,y)=>e.jsx("button",{onClick:()=>{i(y),o(!1)},className:It("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===y?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:x.type==="video"?e.jsx("video",{src:x.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:x.url,alt:"",className:"w-full h-full object-cover"})},y))})]})})}const m$=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],TJt=({commentId:s,reactions:t,currentUserId:r})=>{var d,h;const n=Xt(),[a,i]=k.useState(!1),l=t.find(m=>m.user_id===r),o=Ct({mutationFn:async m=>{l?l.reaction_type===m?await V.from("community_comment_reactions").delete().eq("id",l.id):await V.from("community_comment_reactions").update({reaction_type:m}).eq("id",l.id):await V.from("community_comment_reactions").insert({comment_id:s,user_id:r,reaction_type:m})},onSuccess:()=>{n.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(m=>{c[m.reaction_type]=(c[m.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(Oot,{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(m=>{var x;return e.jsx("span",{className:"text-sm",children:(x=m$.find(y=>y.type===m))==null?void 0:x.emoji},m)})}),e.jsx("span",{children:t.length})]})}),r&&e.jsxs(To,{open:a,onOpenChange:i,children:[e.jsx(Eo,{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=m$.find(m=>m.type===l.reaction_type))==null?void 0:d.emoji," ",(h=m$.find(m=>m.type===l.reaction_type))==null?void 0:h.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(_o,{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:m$.map(m=>e.jsx("button",{onClick:()=>o.mutate(m.type),className:"text-xl hover:scale-125 transition-transform p-1",title:m.label,children:m.emoji},m.type))})})]})]})};function h5e({content:s,className:t}){const r=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,n=[];let a=0,i,l=0;for(;(i=r.exec(s))!==null;){if(i.index>a&&n.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],h=o==="#";n.push(e.jsx(Yn,{to:h?`/templates/${d}`:`/profile?user=${d}`,className:It("font-medium hover:underline",h?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:m=>m.stopPropagation(),children:h?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let h;try{const m=new URL(c);h=m.hostname+(m.pathname!=="/"?m.pathname.slice(0,20)+(m.pathname.length>20?"...":""):"")}catch{h=c.length>40?c.slice(0,40)+"...":c}n.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:m=>m.stopPropagation(),children:h},`url-${l++}`)),d&&n.push(d)}a=i.index+i[0].length}return ae.jsx(k.Fragment,{children:o},c))})}function Bue({value:s,onChange:t,placeholder:r="What's on your mind? Use @ to mention someone",className:n,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const h=k.useRef(null),m=k.useRef(null),[x,y]=k.useState(!1),[v,w]=k.useState("user"),[b,N]=k.useState(""),[S,T]=k.useState(null),[A,I]=k.useState(0),[D,R]=k.useState({top:0,left:0,width:0}),$=k.useRef(new Map),F=k.useRef(new Map),z=ve=>{if(c==="plain"){const De=[];return $.current.forEach((He,Le)=>{ve.includes(`@${Le}`)&&De.push(He)}),[...new Set(De)]}const be=/@\[([^\]]+)\]\(([^)]+)\)/g,Ue=[];let Be;for(;(Be=be.exec(ve))!==null;)Ue.push(Be[2]);return[...new Set(Ue)]},Q=ve=>{if(c==="plain"){const De=[];return F.current.forEach((He,Le)=>{ve.includes(`#${Le}`)&&De.push(He)}),[...new Set(De)]}const be=/#\[([^\]]+)\]\(([^)]+)\)/g,Ue=[];let Be;for(;(Be=be.exec(ve))!==null;)Ue.push(Be[2]);return[...new Set(Ue)]};k.useEffect(()=>{if(i){const ve=z(s);i(ve)}if(l){const ve=Q(s);l(ve)}},[s,i,l,c]);const{data:K=[],isLoading:X}=mt({queryKey:["mention-users",b],queryFn:async()=>{const ve=V.from("profiles").select("id, name").limit(8),be=b.length>=1?ve.ilike("name",`%${b}%`):ve.order("name"),{data:Ue,error:Be}=await be;if(Be)throw Be;const De=Ue.map(He=>He.id),Ae=await Pst(De);return Ue.map(He=>({id:He.id,name:He.name||"Unknown",avatar_url:Ae.get(He.id)}))},enabled:x&&v==="user",staleTime:3e4}),{data:Z=[],isLoading:re}=mt({queryKey:["mention-templates",b],queryFn:async()=>{let ve=V.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);b.length>=1&&(ve=ve.ilike("name",`%${b}%`));const{data:be,error:Ue}=await ve;if(Ue)throw Ue;return be||[]},enabled:x&&v==="template"&&d,staleTime:3e4}),le=v==="user"?X:re,oe=v==="user"?K:Z,ne=ve=>ve.split(" ").map(be=>be[0]).join("").toUpperCase().slice(0,2),ie=ve=>{const be=ve.target.value,Ue=ve.target.selectionStart;t(be);const Be=be.substring(0,Ue),De=Be.lastIndexOf("@"),Ae=d?Be.lastIndexOf("#"):-1;let He=-1,Le="user";if(De>Ae?(He=De,Le="user"):Ae>De&&d&&(He=Ae,Le="template"),He!==-1){const Ie=Be.substring(He+1),Te=Ie.includes(" "),xe=Ie.includes(` `);if(!Te&&!xe&&Ie.length<=30){T(He),N(Ie),w(Le),y(!0),I(0);return}}y(!1),T(null)},ye=ve=>{if(S===null)return;const be=s.substring(0,S),Ue=s.substring(S+b.length+1),Be=v==="user"?"@":"#",De=c==="plain"?`${Be}${ve.name} `:`${Be}[${ve.name}](${ve.id}) `;c==="plain"&&(v==="user"?$.current.set(ve.name,ve.id):F.current.set(ve.name,ve.id));const Ae=be+De+Ue;t(Ae),y(!1),T(null),N(""),setTimeout(()=>{if(h.current){const He=be.length+De.length;h.current.focus(),h.current.setSelectionRange(He,He)}},0)},ce=ve=>{if(!(!x||oe.length===0))switch(ve.key){case"ArrowDown":ve.preventDefault(),I(be=>(be+1)%oe.length);break;case"ArrowUp":ve.preventDefault(),I(be=>(be-1+oe.length)%oe.length);break;case"Enter":oe[A]&&(ve.preventDefault(),ye(oe[A]));break;case"Escape":ve.preventDefault(),y(!1);break;case"Tab":oe[A]&&(ve.preventDefault(),ye(oe[A]));break}};return k.useEffect(()=>{const ve=be=>{m.current&&!m.current.contains(be.target)&&h.current&&!h.current.contains(be.target)&&y(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[]),k.useEffect(()=>{if(!x)return;const ve=()=>{const be=h.current;if(!be)return;const Ue=be.getBoundingClientRect();R({top:Ue.bottom+4,left:Ue.left,width:Ue.width})};return ve(),window.addEventListener("resize",ve),window.addEventListener("scroll",ve,!0),()=>{window.removeEventListener("resize",ve),window.removeEventListener("scroll",ve,!0)}},[x,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(or,{ref:h,value:s,onChange:ie,onKeyDown:ve=>{ce(ve),ve.defaultPrevented||o==null||o(ve)},placeholder:r,className:It("resize-none",n),style:{minHeight:a}}),x&&Vf.createPortal(e.jsxs("div",{ref:m,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:D.top,left:D.left,width:D.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:v==="user"?"👤 Mention a person":"📋 Link a template"}),le?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):oe.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:b.length<1?`Type to search ${v==="user"?"people":"templates"}...`:`No ${v==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:oe.map((ve,be)=>e.jsx("li",{className:It("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",be===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>ye(ve),onMouseEnter:()=>I(be),children:v==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Nn,{className:"h-6 w-6",children:[e.jsx(ya,{src:ve.avatar_url}),e.jsx(kn,{className:"text-xs",children:ne(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 EJt(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,r=[];let n;for(;(n=t.exec(s))!==null;)r.push(n[2]);return[...new Set(r)]}const ABe=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function Fot({comment:s,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Xt(),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,y]=k.useState([]),v=Ct({mutationFn:async({content:S,parentCommentId:T})=>{const{data:A,error:I}=await V.from("community_comments").insert({post_id:t,user_id:r,content:S,parent_comment_id:T}).select("id").single();if(I)throw I;const D=x;if(D.length>0&&A){const R=D.filter($=>$!==r).map($=>({comment_id:A.id,mentioned_user_id:$,mentioned_by_user_id:r}));R.length>0&&await V.from("community_comment_mentions").insert(R)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),m(""),y([]),d(!1)}}),w=Ct({mutationFn:async S=>{const{error:T}=await V.from("community_comments").delete().eq("id",S);if(T)throw T},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),b=()=>{h.trim()&&v.mutate({content:h,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(Nn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ya,{src:s.user_avatar||void 0}),e.jsx(kn,{className:"text-xs",children:ABe(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(h5e,{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:rl(new Date(s.created_at),{addSuffix:!0})}),e.jsx(TJt,{commentId:s.id,reactions:s.reactions,currentUserId:r}),r&&l<2&&e.jsxs("button",{onClick:()=>d(!c),className:"hover:text-primary flex items-center gap-1",children:[e.jsx(OR,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===r||i)&&e.jsx("button",{onClick:()=>w.mutate(s.id),className:"hover:text-destructive",children:s.user_id!==r?"Remove":"Delete"})]}),c&&r&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(Nn,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(ya,{src:n||void 0}),e.jsx(kn,{className:"text-xs",children:ABe((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Bue,{placeholder:`Reply to ${s.user_name}...`,value:h,onChange:m,onMentionsChange:y,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:b,disabled:!h.trim()||v.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(en,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(S=>e.jsx(Fot,{comment:S,postId:t,currentUserId:r,currentUserAvatar:n,currentUserEmail:a,canModerate:i,depth:l+1},S.id))})]})}const f$=[{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"}],AJt=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:r,isAdmin:n}=js(),{avatarUrl:a}=Lst(s==null?void 0:s.id),{onlineUsers:i}=sXe(),{toast:l}=Ma(),o=Xt(),c=k.useRef(null),[d,h]=k.useState("all"),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState([]),[T,A]=k.useState([]),[I,D]=k.useState(""),[R,$]=k.useState(!1),[F,z]=k.useState(null),[Q,K]=k.useState(""),[X,Z]=k.useState(new Set),[re,le]=k.useState({}),[oe,ne]=k.useState({}),[ie,ye]=k.useState([]),[ce,ve]=k.useState([]),[be,Ue]=k.useState({open:!1,images:[],index:0});k.useEffect(()=>{if(d.startsWith("group:")){const Je=d.replace("group:","");b(Je),v("")}else d!=="all"?(v(d),b("")):(v(""),b(""))},[d]);const{data:Be=[]}=mt({queryKey:["community-categories"],queryFn:async()=>{const{data:Je,error:jt}=await V.from("community_categories").select("*").order("sort_order");if(jt)throw jt;return Je}}),{data:De=[]}=mt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:Je,error:jt}=await V.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(jt)throw jt;return Je}}),Ae=20,{data:He,isLoading:Le,hasNextPage:Ie,fetchNextPage:Te,isFetchingNextPage:xe}=fSt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:Je})=>{var ze;const jt=Je*Ae,ns=jt+Ae;let Ns=V.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(jt,ns);if(d.startsWith("group:")){const st=d.replace("group:","");Ns=Ns.eq("private_group_id",st)}else d==="all"||(Ns=Ns.eq("category_id",d).is("private_group_id",null));const{data:Ys,error:rs}=await Ns;if(rs)throw rs;const bt=((Ys==null?void 0:Ys.length)||0)>Ae,cs=(Ys||[]).slice(0,Ae);if(cs.length===0)return{posts:[],hasMore:!1,nextPage:Je+1};const yt=cs.map(st=>st.id),is=[...new Set(cs.filter(st=>st.category_id).map(st=>st.category_id))].filter(Boolean),[Bs,ps,lr,kr,Lr]=await Promise.all([is.length?V.from("community_categories").select("*").in("id",is):Promise.resolve({data:[]}),V.from("community_post_media").select("*").in("post_id",yt).order("sort_order"),V.from("community_reactions").select("*").in("post_id",yt),V.from("community_comments").select("*").in("post_id",yt).order("created_at",{ascending:!0}),V.from("community_post_resources").select("*").in("post_id",yt)]),qr=Bs==null?void 0:Bs.data,Ur=ps==null?void 0:ps.data,Mr=lr==null?void 0:lr.data,Cr=kr==null?void 0:kr.data,Xr=Lr==null?void 0:Lr.data,Ln=(Cr||[]).map(st=>st.id),[Zs,Yr]=await Promise.all([Ln.length?V.from("community_comment_reactions").select("*").in("comment_id",Ln):Promise.resolve({data:[]}),(()=>{const st=(Xr||[]).filter(gt=>gt.resource_type==="template").map(gt=>gt.resource_id);return st.length===0?Promise.resolve({data:[]}):V.from("canva_templates").select("id, name, preview_image_url").in("id",st)})()]),ss=(Zs==null?void 0:Zs.data)||[],ta=(Yr==null?void 0:Yr.data)||[],nn=new Map(ta.map(st=>[st.id,{name:st.name,preview_image_url:st.preview_image_url}])),hr=Array.from(new Set([...cs.map(st=>st.user_id),...(Mr||[]).map(st=>st.user_id),...(Cr||[]).map(st=>st.user_id),...ss.map(st=>st.user_id)])),[Pr,Qn]=await Promise.all([hr.length?V.from("profiles").select("id, name").in("id",hr):Promise.resolve({data:[]}),Pst(hr)]),Gt=new Map(((ze=Pr==null?void 0:Pr.data)==null?void 0:ze.map(st=>[st.id,st.name]))||[]),gr=new Map((qr||[]).map(st=>[st.id,st])),zt=st=>{const gt=new Map,At=[];return st.forEach(Ft=>{gt.set(Ft.id,{...Ft,user_name:Gt.get(Ft.user_id)||"Unknown User",user_avatar:Qn.get(Ft.user_id),reactions:ss.filter(Wt=>Wt.comment_id===Ft.id).map(Wt=>({...Wt,user_name:Gt.get(Wt.user_id)||"Unknown User",user_avatar:Qn.get(Wt.user_id)})),replies:[]})}),st.forEach(Ft=>{const Wt=gt.get(Ft.id);if(Ft.parent_comment_id&>.has(Ft.parent_comment_id)){const Vt=gt.get(Ft.parent_comment_id);Vt.replies=Vt.replies||[],Vt.replies.push(Wt)}else At.push(Wt)}),At};return{posts:cs.map(st=>{const gt=(Xr||[]).filter(At=>At.post_id===st.id).map(At=>{let Ft="",Wt=null;if(At.resource_type==="template"){const Vt=nn.get(At.resource_id);Ft=(Vt==null?void 0:Vt.name)||"Unknown Template",Wt=(Vt==null?void 0:Vt.preview_image_url)||null}return{id:At.id,resource_type:At.resource_type,resource_id:At.resource_id,resource_name:Ft,resource_preview_url:Wt}});return{...st,user_name:Gt.get(st.user_id)||"Unknown User",user_avatar:Qn.get(st.user_id),category:st.category_id?gr.get(st.category_id):null,media:(Ur||[]).filter(At=>At.post_id===st.id),reactions:((Mr||[]).filter(At=>At.post_id===st.id)||[]).map(At=>({...At,user_name:Gt.get(At.user_id)||"Unknown User",user_avatar:Qn.get(At.user_id)})),comments:zt((Cr||[]).filter(At=>At.post_id===st.id)),resources:gt}}),hasMore:bt,nextPage:Je+1}},getNextPageParam:Je=>Je.hasMore?Je.nextPage:void 0}),et=k.useMemo(()=>(He==null?void 0:He.pages.flatMap(Je=>Je.posts))??[],[He]),fe=Ct({mutationFn:async()=>{$(!0);const{data:Je,error:jt}=await V.from("community_posts").insert({user_id:s.id,category_id:w?null:y||null,private_group_id:w||null,content:m,link_url:I||null}).select().single();if(jt)throw jt;for(let Ns=0;Ns0){const Ns=ie.filter(Ys=>Ys!==s.id).map(Ys=>({post_id:Je.id,mentioned_user_id:Ys,mentioned_by_user_id:s.id}));Ns.length>0&&await V.from("community_post_mentions").insert(Ns)}const ns=EJt(m);if(ns.length>0){const Ns=ns.map(Ys=>({post_id:Je.id,resource_type:"template",resource_id:Ys}));await V.from("community_post_resources").insert(Ns)}return Je},onSuccess:async Je=>{var jt;o.invalidateQueries({queryKey:["community-posts"]}),x(""),ye([]),ve([]),v(""),b(""),S([]),A([]),D(""),l({title:"Post created!"});try{const ns=((jt=s==null?void 0:s.user_metadata)==null?void 0:jt.name)||"Someone",Ns=m.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),Ys=Ns.length>50?Ns.substring(0,50)+"...":Ns;await V.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${ns}: ${Ys}`,url:"/community"}})}catch(ns){console.error("Failed to send push notification:",ns)}},onError:Je=>{l({title:"Error creating post",description:Je.message,variant:"destructive"})},onSettled:()=>$(!1)}),it=Ct({mutationFn:async({postId:Je,content:jt})=>{const{error:ns}=await V.from("community_posts").update({content:jt}).eq("id",Je);if(ns)throw ns},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),z(null),K(""),l({title:"Post updated!"})}}),Oe=Ct({mutationFn:async Je=>{const{error:jt}=await V.from("community_posts").delete().eq("id",Je);if(jt)throw jt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Ye=Ct({mutationFn:async({postId:Je,isPinned:jt})=>{const{error:ns}=await V.from("community_posts").update({is_pinned:!jt,pinned_at:jt?null:new Date().toISOString(),pinned_by:jt?null:s==null?void 0:s.id}).eq("id",Je);if(ns)throw ns},onSuccess:(Je,{isPinned:jt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:jt?"Post unpinned":"Post pinned to top"})}}),We=Ct({mutationFn:async({postId:Je,reactionType:jt})=>{var Ns;const ns=(Ns=et.find(Ys=>Ys.id===Je))==null?void 0:Ns.reactions.find(Ys=>Ys.user_id===(s==null?void 0:s.id));ns?ns.reaction_type===jt?await V.from("community_reactions").delete().eq("id",ns.id):await V.from("community_reactions").update({reaction_type:jt}).eq("id",ns.id):await V.from("community_reactions").insert({post_id:Je,user_id:s.id,reaction_type:jt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),_e=Ct({mutationFn:async({postId:Je,content:jt})=>{const{data:ns,error:Ns}=await V.from("community_comments").insert({post_id:Je,user_id:s.id,content:jt}).select("id").single();if(Ns)throw Ns;const Ys=oe[Je]||[];if(Ys.length>0&&ns){const rs=Ys.filter(bt=>bt!==s.id).map(bt=>({comment_id:ns.id,mentioned_user_id:bt,mentioned_by_user_id:s.id}));rs.length>0&&await V.from("community_comment_mentions").insert(rs)}},onSuccess:(Je,{postId:jt})=>{o.invalidateQueries({queryKey:["community-posts"]}),le(ns=>({...ns,[jt]:""})),ne(ns=>({...ns,[jt]:[]}))}});Ct({mutationFn:async Je=>{const{error:jt}=await V.from("community_comments").delete().eq("id",Je);if(jt)throw jt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Re=Je=>{const jt=Array.from(Je.target.files||[]);if(jt.length+N.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}S(ns=>[...ns,...jt]),jt.forEach(ns=>{const Ns=new FileReader;Ns.onloadend=()=>{A(Ys=>[...Ys,Ns.result])},Ns.readAsDataURL(ns)})},tt=Je=>{S(jt=>jt.filter((ns,Ns)=>Ns!==Je)),A(jt=>jt.filter((ns,Ns)=>Ns!==Je))},Ke=Je=>Je.split(" ").map(jt=>jt[0]).join("").toUpperCase().slice(0,2),Ze=Je=>{const jt={};return Je.forEach(ns=>{jt[ns.reaction_type]=(jt[ns.reaction_type]||0)+1}),jt},lt=Je=>{var jt;return(jt=Je.find(ns=>ns.user_id===(s==null?void 0:s.id)))==null?void 0:jt.reaction_type},xt=Je=>Je.reduce((jt,ns)=>jt+1+(ns.replies?xt(ns.replies):0),0),Xe=Je=>{if(n)return!0;if(!t||!Je.private_group_id)return!1;const jt=De.find(ns=>ns.id===Je.private_group_id);return jt!=null&&jt.brokerage_id?r.some(ns=>ns.id===jt.brokerage_id):!1};return e.jsx(ws,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(hJt,{categories:Be,privateGroups:De,selectedFilter:d,onFilterChange:h,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(mJt,{categories:Be,privateGroups:De,selectedFilter:d,onFilterChange:h,onlineUsers:i}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:a||void 0}),e.jsx(kn,{children:s!=null&&s.email?Ke(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Bue,{placeholder:n?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:m,onChange:x,onMentionsChange:ye,onTemplatesChange:ve,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:n}),T.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:T.map((Je,jt)=>{var ns;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(ns=N[jt])!=null&&ns.type.startsWith("video/")?e.jsx("video",{src:Je,className:"w-full h-full object-cover"}):e.jsx("img",{src:Je,alt:"",className:"w-full h-full object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>tt(jt),children:e.jsx(vr,{className:"h-3 w-3"})})]},jt)})}),I&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(po,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:I,onChange:Je=>D(Je.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>D(""),children:e.jsx(vr,{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:Re,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>{var Je;return(Je=c.current)==null?void 0:Je.click()},children:[e.jsx(ml,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>{var Je;return(Je=c.current)==null?void 0:Je.click()},children:[e.jsx(Jr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>D("https://"),children:[e.jsx(po,{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:[De.length>0?e.jsxs(Is,{value:w||y||"none",onValueChange:Je=>{Je==="none"?(v(""),b("")):Je.startsWith("group:")?(b(Je.replace("group:","")),v("")):(v(Je),b(""))},children:[e.jsx(As,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(Ls,{placeholder:"Select..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No category"}),Be.map(Je=>e.jsxs(ct,{value:Je.id,children:[Je.icon," ",Je.name]},Je.id)),De.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"}),De.map(Je=>e.jsxs(ct,{value:`group:${Je.id}`,children:[Je.icon||"🔒"," ",Je.name]},Je.id))]})]})]}):e.jsxs(Is,{value:y,onValueChange:v,children:[e.jsx(As,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(Ls,{placeholder:"Category"})}),e.jsx(Ms,{children:Be.map(Je=>e.jsxs(ct,{value:Je.id,children:[Je.icon," ",Je.name]},Je.id))})]}),e.jsxs(G,{size:"sm",onClick:()=>fe.mutate(),disabled:!m.trim()||R,children:[e.jsx(en,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Le?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Je,jt)=>e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Fs,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Fs,{className:"h-4 w-32"}),e.jsx(Fs,{className:"h-4 w-full"}),e.jsx(Fs,{className:"h-4 w-3/4"})]})]})})},jt))}):et.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Jl,{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:[et.map(Je=>{var jt,ns,Ns,Ys;return e.jsx(ke,{children:e.jsxs(Pe,{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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:Je.user_avatar||void 0}),e.jsx(kn,{children:Ke(Je.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:Je.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:rl(new Date(Je.created_at),{addSuffix:!0})}),Je.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[Je.category.icon," ",Je.category.name]})]})]})]})]}),(Je.user_id===(s==null?void 0:s.id)||Xe(Je))&&e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Lp,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[Xe(Je)&&Je.private_group_id&&e.jsx(Pa,{onClick:()=>Ye.mutate({postId:Je.id,isPinned:Je.is_pinned}),children:Je.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(IR,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(ij,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),Je.user_id===(s==null?void 0:s.id)&&e.jsxs(Pa,{onClick:()=>{z(Je),K(Je.content)},children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Pa,{className:"text-destructive",onClick:()=>Oe.mutate(Je.id),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),Je.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),Je.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(ij,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(h5e,{content:Je.content})}),Je.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${Je.media.length===1?"grid-cols-1":Je.media.length===2?"grid-cols-2":Je.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:Je.media.slice(0,4).map((rs,bt)=>{const cs=bt===3&&Je.media.length>4,yt=Je.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${Je.media.length===1?"max-h-[500px]":Je.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>Ue({open:!0,images:Je.media.map(is=>({url:is.media_url,type:is.media_type==="video"?"video":"image"})),index:bt}),children:[rs.media_type==="video"?e.jsx("video",{src:rs.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:rs.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"})})})}),cs&&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:["+",yt]})})]},rs.id)})}),Je.link_url&&e.jsxs("a",{href:Je.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[Je.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:Je.link_image,alt:Je.link_title||"Link preview",className:"w-full h-full object-cover",onError:rs=>{rs.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:Je.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:Je.link_title}),Je.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:Je.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(Je.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(po,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:Je.link_url})]})})]}),Je.reactions.length>0&&e.jsx(Oot,{reactions:Je.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(Ze(Je.reactions)).slice(0,3).map(([rs])=>{var bt;return e.jsx("span",{className:"text-base",children:(bt=f$.find(cs=>cs.type===rs))==null?void 0:bt.emoji},rs)})}),e.jsx("span",{children:Je.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"flex-1",children:[lt(Je.reactions)?e.jsx("span",{className:"mr-1",children:(jt=f$.find(rs=>rs.type===lt(Je.reactions)))==null?void 0:jt.emoji}):e.jsx(jh,{className:"h-4 w-4 mr-1"}),lt(Je.reactions)?(ns=f$.find(rs=>rs.type===lt(Je.reactions)))==null?void 0:ns.label:"Like"]})}),e.jsx(_o,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:f$.map(rs=>e.jsx("button",{onClick:()=>We.mutate({postId:Je.id,reactionType:rs.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:rs.label,children:rs.emoji},rs.type))})})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>Z(rs=>{const bt=new Set(rs);return bt.has(Je.id)?bt.delete(Je.id):bt.add(Je.id),bt}),children:[e.jsx(Jl,{className:"h-4 w-4 mr-1"}),(()=>{const rs=xt(Je.comments);return rs>0?`Comment (${rs})`:"Comment"})()]})]}),X.has(Je.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[Je.comments.map(rs=>e.jsx(Fot,{comment:rs,postId:Je.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:Xe(Je)},rs.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:a||void 0}),e.jsx(kn,{className:"text-xs",children:Ke(((Ns=s.email)==null?void 0:Ns.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Bue,{placeholder:"Write a comment... (use @ to mention)",value:re[Je.id]||"",onChange:rs=>le(bt=>({...bt,[Je.id]:rs})),onMentionsChange:rs=>ne(bt=>({...bt,[Je.id]:rs})),mentionFormat:"plain",onKeyDown:rs=>{var bt;rs.defaultPrevented||rs.key==="Enter"&&!rs.shiftKey&&((bt=re[Je.id])!=null&&bt.trim())&&(rs.preventDefault(),_e.mutate({postId:Je.id,content:re[Je.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{var rs;(rs=re[Je.id])!=null&&rs.trim()&&_e.mutate({postId:Je.id,content:re[Je.id]})},disabled:!((Ys=re[Je.id])!=null&&Ys.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(en,{className:"h-4 w-4"})})]})]})]})]})},Je.id)}),Ie&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(G,{variant:"outline",onClick:()=>Te(),disabled:xe,children:xe?"Loading…":"Load more posts"})})]}),e.jsx(fs,{open:!!F,onOpenChange:()=>z(null),children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Edit Post"})}),e.jsx(or,{value:Q,onChange:Je=>K(Je.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>z(null),children:"Cancel"}),e.jsx(G,{onClick:()=>{F&&it.mutate({postId:F.id,content:Q})},disabled:!Q.trim(),children:"Save Changes"})]})]})}),e.jsx(CJt,{images:be.images,initialIndex:be.index,open:be.open,onOpenChange:Je=>Ue(jt=>({...jt,open:Je}))})]})]})})},MJt=50*1024*1024;function Bot({value:s,onChange:t,disabled:r}){const{user:n}=js(),a=k.useRef(null),[i,l]=k.useState(!1),o=async d=>{if(!d||!n)return;const h=[];l(!0);try{for(const m of Array.from(d)){if(!m.type.startsWith("image/")&&!m.type.startsWith("video/")){ue.error(`${m.name}: only images and videos allowed`);continue}if(m.size>MJt){ue.error(`${m.name}: must be under 50MB`);continue}const x=m.name.split(".").pop()||"bin",y=`${n.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${x}`,{error:v}=await V.storage.from("support-attachments").upload(y,m,{contentType:m.type,upsert:!1});if(v){ue.error(`${m.name}: ${v.message}`);continue}h.push({path:y,type:m.type,name:m.name,size:m.size})}h.length&&t([...s,...h])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const h=s[d];t(s.filter((m,x)=>x!==d)),await V.storage.from("support-attachments").remove([h.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,h)=>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(xR,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(hb,{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(h),className:"text-muted-foreground hover:text-foreground",children:e.jsx(vr,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:r||i,className:"gap-1.5",children:[i?e.jsx(es,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(nj,{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 zot({attachments:s}){const[t,r]=k.useState({}),[n,a]=k.useState(!0);return k.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await V.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,h)=>{d.signedUrl&&(c[l[h]]=d.signedUrl)}),r(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?n?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(es,{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 sE={open:{label:"Open",icon:fn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Jl,color:"bg-blue-500"},resolved:{label:"Resolved",icon:di,color:"bg-green-500"},closed:{label:"Closed",icon:Sc,color:"bg-muted-foreground"}},MBe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function IJt(){const{user:s}=js(),t=Xt(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),{data:c=[],isLoading:d}=mt({queryKey:["support-tickets"],queryFn:async()=>{const{data:y,error:v}=await V.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(v)throw v;return y},enabled:!!s}),{data:h=[]}=mt({queryKey:["ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:y,error:v}=await V.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(v)throw v;return y},enabled:!!r}),m=Ct({mutationFn:async({content:y,attachments:v})=>{if(!r||!s)throw new Error("Missing data");const{error:w}=await V.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:y,is_admin_reply:!1,attachments:v});if(w)throw w},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",r==null?void 0:r.id]}),i(""),o([]),ue.success("Reply sent!")},onError:()=>{ue.error("Failed to send reply")}}),x=()=>{!a.trim()&&l.length===0||m.mutate({content:a,attachments:l})};if(r){const y=sE[r.status].icon;return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"secondary",children:MBe[r.category]}),e.jsxs(Ge,{className:sE[r.status].color,children:[e.jsx(y,{className:"h-3 w-3 mr-1"}),sE[r.status].label]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Nr,{children:["Created on ",_s(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Pe,{children:[e.jsx(Qa,{className:"h-[300px] pr-4",children:h.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:h.map(v=>{var w;return e.jsxs("div",{className:`p-4 rounded-lg ${v.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:v.is_admin_reply?"Support Team":((w=v.profiles)==null?void 0:w.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_s(new Date(v.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.content}),v.attachments&&v.attachments.length>0&&e.jsx(zot,{attachments:v.attachments})]},v.id)})})}),r.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(fo,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(or,{placeholder:"Type your reply...",value:a,onChange:v=>i(v.target.value),className:"min-h-[80px]"}),e.jsx(G,{onClick:x,disabled:!a.trim()&&l.length===0||m.isPending,className:"self-end",children:e.jsx(en,{className:"h-4 w-4"})})]}),e.jsx(Bot,{value:l,onChange:o,disabled:m.isPending})]})]})]})]})]})})}return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Pe,{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(G1,{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(Fje,{trigger:e.jsxs(G,{size:"lg",className:"gap-2",children:[e.jsx($s,{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(Cn,{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(Fje,{trigger:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx($s,{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(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"text-center py-12",children:[e.jsx(Jl,{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(y=>{const v=sE[y.status].icon;return e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(y),children:e.jsx(Pe,{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:y.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"outline",className:"text-xs",children:MBe[y.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_s(new Date(y.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Ge,{className:sE[y.status].color,children:[e.jsx(v,{className:"h-3 w-3 mr-1"}),sE[y.status].label]})]})})},y.id)})})]})})}function LJt({open:s,onOpenChange:t}){return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ys,{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(on,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(gs,{children:"Schedule Agent Onboarding"}),e.jsx(Hr,{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 PJt({open:s,onOpenChange:t}){const{brokerageId:r}=js(),[n,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(!1),{data:d,isLoading:h}=mt({queryKey:["brokerage-agents-for-onboarding",r],queryFn:async()=>{if(!r)return[];const{data:w,error:b}=await V.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name",{ascending:!0});if(b)throw b;return w},enabled:s&&!!r}),m=d==null?void 0:d.filter(w=>w.name.toLowerCase().includes(n.toLowerCase())||w.email.toLowerCase().includes(n.toLowerCase())),x=w=>{l(b=>b.includes(w)?b.filter(N=>N!==w):[...b,w])},y=async()=>{if(i.length===0){ue.error("Please select at least one agent");return}c(!0);try{const{data:w,error:b}=await V.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(b)throw b;ue.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(w){console.error("Error sending onboarding link:",w),ue.error(w.message||"Failed to send onboarding link")}finally{c(!1)}},v=w=>{w||(l([]),a("")),t(w)};return e.jsx(fs,{open:s,onOpenChange:v,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{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(en,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(gs,{children:"Send Onboarding Link"}),e.jsx(Hr,{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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:n,onChange:w=>a(w.target.value),className:"pl-10"})]}),h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(m==null?void 0:m.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Qa,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:m==null?void 0:m.map(w=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>x(w.id),children:[e.jsx(Si,{checked:i.includes(w.id),onCheckedChange:()=>x(w.id)}),e.jsx(Nn,{className:"h-8 w-8",children:e.jsx(kn,{className:"text-xs",children:w.name.split(" ").map(b=>b[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:w.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:w.email})]})]},w.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(G,{onClick:y,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function DJt(){const[s,t]=k.useState(!1),[r,n]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{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(pr,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{children:"Agent Onboarding"}),e.jsx(Nr,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(G,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(G,{variant:"outline",onClick:()=>n(!0),className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(LJt,{open:s,onOpenChange:t}),e.jsx(PJt,{open:r,onOpenChange:n})]})}function RJt({open:s,onOpenChange:t}){return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(ys,{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(lv,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(gs,{children:"Schedule Launch Meeting"}),e.jsx(Hr,{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 OJt(){const[s,t]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{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(lv,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{children:"Launch or ReLaunch Meeting"}),e.jsx(Nr,{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(Pe,{children:e.jsxs(G,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(lv,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(RJt,{open:s,onOpenChange:t})]})}function FJt(){const s=br(),[t,r]=k.useState(""),[n,a]=k.useState(null),{data:i,isLoading:l}=mt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:w,error:b}=await V.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(b)throw b;return w}}),{data:o}=mt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:w,error:b}=await V.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(b)throw b;return w}}),{data:c}=mt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:w,error:b}=await V.from("brokerage_resource_pdfs").select("resource_id");if(b)throw b;return w}}),{data:d}=mt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:w,error:b}=await V.from("brokerage_resource_videos").select("resource_id");if(b)throw b;return w}}),{data:h}=mt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:w,error:b}=await V.from("brokerage_resource_links").select("resource_id");if(b)throw b;return w}}),m=i==null?void 0:i.filter(w=>{var S;const b=w.title.toLowerCase().includes(t.toLowerCase())||((S=w.description)==null?void 0:S.toLowerCase().includes(t.toLowerCase())),N=!n||w.category_id===n;return b&&N}),x=o==null?void 0:o.filter(w=>i==null?void 0:i.some(b=>b.category_id===w.id)),y=w=>{const b=(c==null?void 0:c.filter(T=>T.resource_id===w).length)||0,N=(d==null?void 0:d.filter(T=>T.resource_id===w).length)||0,S=(h==null?void 0:h.filter(T=>T.resource_id===w).length)||0;return{pdfCount:b,videoCount:N,linkCount:S}},v=w=>{s(`/brokerage-resources/${w}`)};return e.jsx(ws,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(DJt,{}),e.jsx(OJt,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search resources...",value:t,onChange:w=>r(w.target.value),className:"pl-10"})]}),x&&x.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ge,{variant:n===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),x.map(w=>e.jsx(Ge,{variant:n===w.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(w.id),children:w.name},w.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(m==null?void 0:m.length)||0," resource",(m==null?void 0:m.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((w,b)=>e.jsxs(ke,{children:[e.jsx(Fs,{className:"h-40 w-full"}),e.jsx(Mt,{children:e.jsx(Fs,{className:"h-5 w-3/4"})}),e.jsxs(Pe,{children:[e.jsx(Fs,{className:"h-4 w-full mb-2"}),e.jsx(Fs,{className:"h-4 w-2/3"})]})]},b))}):(m==null?void 0:m.length)===0?e.jsxs(ke,{className:"p-12 text-center",children:[e.jsx(Gu,{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||n?"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:m==null?void 0:m.map(w=>{const{pdfCount:b,videoCount:N,linkCount:S}=y(w.id),T=o==null?void 0:o.find(A=>A.id===w.category_id);return e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>v(w.id),children:[w.preview_image_url?e.jsx("img",{src:w.preview_image_url,alt:w.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(Gu,{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(Dt,{className:"text-lg line-clamp-1",children:w.title}),T&&e.jsx(Ge,{variant:"secondary",className:"shrink-0 text-xs",children:T.name})]})}),e.jsxs(Pe,{children:[w.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:w.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4"}),b]}),N>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),N]}),S>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(po,{className:"h-4 w-4"}),S]})]})]})]},w.id)})})]})})}const BJt=()=>{const{resourceId:s}=Ki(),{data:t,isLoading:r}=mt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await V.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await V.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await V.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await V.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),n=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return r?e.jsx(ws,{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(ws,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/brokerage-resources",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Resources"]})}),t.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:t.preview_image_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),t.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:t.description}})]}),t.videos&&t.videos.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ln,{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(ln,{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:n(a.file_size)})]})]}),e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Qr,{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(Qr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(ws,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Gu,{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(G,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function zJt(){const{onlineUsers:s,totalOnline:t}=sXe();return e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(pr,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Ge,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Ld,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Pe,{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(Qa,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var n;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(Nn,{className:"h-9 w-9",children:[e.jsx(ya,{src:r.avatarUrl,alt:r.name}),e.jsx(kn,{className:"text-xs",children:(n=r.name)==null?void 0:n.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:r.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",rl(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const IBe={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:pr,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:HR,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:Vp,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:hR,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:wh,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Ec,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:pr,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Pd,path:"/admin/prospector",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Recruiting",description:"Manage agent recruit pipeline and outreach",icon:sl,path:"/admin/recruiting",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Coaching",description:"Promote coaches and manage agent coaching assignments",icon:Gi,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 Academy",description:"Upload videos and training content",icon:Md,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:Ay,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:jr,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:jr,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:iv,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:hd,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Gu,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Gu,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:bu,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:$4,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Bx,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:bu,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:uA,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:dv,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:ii,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:Gi,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:tl,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:pr,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:bu,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:xi,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:yA,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:sj,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Xn,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:ro,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:bh,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:Md,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:ci,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:En,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:Ty,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:bh,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:ml,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:Xw,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:fc,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:mR,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:bo,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:ln,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:ln,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:wl,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function LBe(){const s=br();return console.log("[AdminDashboard] render"),e.jsx(ws,{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(zJt,{})})]}),e.jsxs(On,{defaultValue:"users",className:"w-full",children:[e.jsx(Rn,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(IBe).map(([t,r])=>e.jsx(Kt,{value:t,className:"data-[state=active]:bg-background",children:r.label},t))}),Object.entries(IBe).map(([t,r])=>e.jsx(ts,{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:r.sections.map(n=>e.jsxs(ke,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(n.path),children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${n.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(n.icon,{className:"h-5 w-5"})}),e.jsx(Dt,{className:"text-base",children:n.title})]}),e.jsx(Pe,{className:"pt-0",children:e.jsx(Nr,{className:"text-sm",children:n.description})})]},n.path))})},t))]})]})})}const Bn=k.forwardRef(({className:s,...t},r)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:r,className:It("w-full caption-bottom text-sm",s),...t})}));Bn.displayName="Table";const zn=k.forwardRef(({className:s,...t},r)=>e.jsx("thead",{ref:r,className:It("[&_tr]:border-b",s),...t}));zn.displayName="TableHeader";const $n=k.forwardRef(({className:s,...t},r)=>e.jsx("tbody",{ref:r,className:It("[&_tr:last-child]:border-0",s),...t}));$n.displayName="TableBody";const $Jt=k.forwardRef(({className:s,...t},r)=>e.jsx("tfoot",{ref:r,className:It("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));$Jt.displayName="TableFooter";const Ds=k.forwardRef(({className:s,...t},r)=>e.jsx("tr",{ref:r,className:It("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));Ds.displayName="TableRow";const Nt=k.forwardRef(({className:s,...t},r)=>e.jsx("th",{ref:r,className:It("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Nt.displayName="TableHead";const dt=k.forwardRef(({className:s,...t},r)=>e.jsx("td",{ref:r,className:It("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));dt.displayName="TableCell";const UJt=k.forwardRef(({className:s,...t},r)=>e.jsx("caption",{ref:r,className:It("mt-4 text-sm text-muted-foreground",s),...t}));UJt.displayName="TableCaption";const qJt=()=>{const{isAdmin:s}=js(),t=br(),[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState(null);k.useEffect(()=>{if(!s){t("/dashboard");return}h()},[s]);const h=async()=>{try{const{data:w,error:b}=await V.from("app_tiles").select("*").order("name");if(b)throw b;n(w||[])}catch(w){console.error("Error loading apps:",w),ue.error("Failed to load apps")}finally{i(!1)}},m=async w=>{w.preventDefault();const b=new FormData(w.currentTarget),N={name:b.get("name"),description:b.get("description"),icon:b.get("icon"),app_id:b.get("app_id"),target_url:b.get("target_url"),required_tags:b.get("required_tags").split(",").map(S=>S.trim()).filter(Boolean)};try{if(c){const{error:S}=await V.from("app_tiles").update(N).eq("id",c.id);if(S)throw S;ue.success("App updated successfully")}else{const{error:S}=await V.from("app_tiles").insert([N]);if(S)throw S;ue.success("App created successfully")}o(!1),d(null),h()}catch(S){console.error("Error saving app:",S),ue.error("Failed to save app")}},x=async w=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:b}=await V.from("app_tiles").delete().eq("id",w);if(b)throw b;ue.success("App deleted successfully"),h()}catch(b){console.error("Error deleting app:",b),ue.error("Failed to delete app")}},y=w=>{d(w),o(!0)},v=()=>{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(G,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Manage Apps"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create and configure application tiles"})]})]}),e.jsxs(fs,{open:l,onOpenChange:o,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{onClick:v,children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(ms,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:c?"Edit App":"Create New App"}),e.jsx(Hr,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:m,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(he,{htmlFor:"name",children:"App Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"app_id",children:"App ID"}),e.jsx(Ne,{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(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{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(he,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(Ne,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"target_url",children:"Target URL"}),e.jsx(Ne,{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(he,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(Ne,{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(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Application Tiles"}),e.jsx(Nr,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Pe,{children:r.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(G,{onClick:v,children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Icon"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"App ID"}),e.jsx(Nt,{children:"Target URL"}),e.jsx(Nt,{children:"Tags"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:r.map(w=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"text-2xl",children:w.icon}),e.jsx(dt,{className:"font-medium",children:w.name}),e.jsx(dt,{className:"font-mono text-sm",children:w.app_id}),e.jsx(dt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:w.target_url}),e.jsx(dt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:w.required_tags.map(b=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:b},b))})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>y(w),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(w.id),children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},w.id))})]})})]})})]})};function eh({title:s,description:t,children:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Yn,{to:"/admin",children:e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Admin Dashboard"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:s}),t&&e.jsx("p",{className:"text-muted-foreground",children:t})]}),r]})]})}const PBe=({expiresAt:s,className:t})=>{const r=new Date().getTime(),n=new Date(s).getTime(),a=Math.ceil((n-r)/(1e3*60*60*24));return a<=0?e.jsxs(Ge,{variant:"destructive",className:It("gap-1",t),children:[e.jsx(id,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Ge,{variant:"destructive",className:It("gap-1",t),children:[e.jsx(fn,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Ge,{className:It("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(fn,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Ge,{variant:"secondary",className:It("gap-1",t),children:[e.jsx(fn,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},$ot=({open:s,onOpenChange:t,brokerages:r,fixedBrokerageId:n,onSuccess:a})=>{const{toast:i}=Ma(),l=k.useRef(null),[o,c]=k.useState([]),[d,h]=k.useState(""),[m,x]=k.useState(!1),[y,v]=k.useState("upload"),[w,b]=k.useState(null),N=()=>{c([]),h(""),v("upload"),b(null),l.current&&(l.current.value="")},S=()=>{N(),t(!1)},T=$=>{const F=$.split(` `).map(Z=>Z.trim()).filter(Z=>Z);if(F.length===0)return[];const z=F[0].toLowerCase(),K=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,X=[];for(const Z of K){const le=(Z.includes(" ")?Z.split(" "):Z.split(",")).map(oe=>oe.trim().replace(/^["']|["']$/g,""));if(le.length>=2){let oe="",ne="",ie="",ye="",ce;if(le.length===2){const Ue=le[0].split(" ");oe=Ue[0]||"",ne=Ue.slice(1).join(" ")||"",ie=le[1]}else if(le.length===3)oe=le[0],ne=le[1],ie=le[2];else if(le.length===4)oe=le[0],ne=le[1],ie=le[2],ye=le[3];else if(le.length>=5){oe=le[0],ne=le[1],ie=le[2],ye=le[3];const Ue=le[4].toLowerCase();ce=Ue==="true"||Ue==="yes"||Ue==="1"||Ue==="y"}const be=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ie);X.push({firstName:oe.trim(),lastName:ne.trim(),email:ie.trim().toLowerCase(),phone:ye.trim()||void 0,smsConsent:ce,isValid:be&&oe.trim().length>0,error:be?oe.trim()?void 0:"Missing name":"Invalid email"})}}return X},A=$=>{var Q;const F=(Q=$.target.files)==null?void 0:Q[0];if(!F)return;const z=new FileReader;z.onload=K=>{var re;const X=(re=K.target)==null?void 0:re.result,Z=T(X);if(Z.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(Z),v("preview")},z.readAsText(F)},I=async()=>{const $=o.filter(z=>z.isValid);if($.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const F=n||d||null;x(!0);try{const{data:{session:z}}=await V.auth.getSession(),Q=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:$.map(X=>({firstName:X.firstName,lastName:X.lastName,email:X.email,phone:X.phone,smsConsent:X.smsConsent})),brokerageId:F})}),K=await Q.json();if(!Q.ok)throw new Error(K.error||"Failed to import users");b(K),v("result"),K.created>0&&a(),i({title:"Import Complete",description:`${K.created} user(s) created successfully.${K.failed>0?` ${K.failed} failed.`:""}`})}catch(z){console.error("Import error:",z),i({title:"Import Failed",description:z.message||"Failed to import users",variant:"destructive"})}finally{x(!1)}},D=o.filter($=>$.isValid).length,R=o.filter($=>!$.isValid).length;return e.jsx(fs,{open:s,onOpenChange:S,children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(mb,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Hr,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),y==="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(da,{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(G,{onClick:()=>{var $;return($=l.current)==null?void 0:$.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."})]})]}),y==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!n&&r&&r.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Assign to Brokerage (optional)"}),e.jsxs(Is,{value:d||"none",onValueChange:$=>h($==="none"?"":$),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a brokerage..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No brokerage"}),r.map($=>e.jsx(ct,{value:$.id,children:$.name},$.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(In,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[D," valid"]})]}),R>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Oi,{className:"h-4 w-4"}),e.jsxs("span",{children:[R," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30",children:[e.jsx(Nt,{children:"First Name"}),e.jsx(Nt,{children:"Last Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Phone"}),e.jsx(Nt,{children:"SMS"}),e.jsx(Nt,{children:"Status"})]})}),e.jsx($n,{children:o.slice(0,100).map(($,F)=>e.jsxs(Ds,{children:[e.jsx(dt,{children:$.firstName}),e.jsx(dt,{children:$.lastName}),e.jsx(dt,{children:$.email}),e.jsx(dt,{className:"text-muted-foreground",children:$.phone||"-"}),e.jsx(dt,{className:"text-muted-foreground",children:$.smsConsent===!0?"✓":$.smsConsent===!1?"✗":"-"}),e.jsx(dt,{children:$.isValid?e.jsx(Ge,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Ge,{variant:"destructive",children:$.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"]})]})]}),y==="result"&&w&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(In,{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:[w.created," agent(s) created and invited"]}),w.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[w.failed," failed to create"]})]}),w.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:[w.errors.slice(0,10).map(($,F)=>e.jsxs("li",{children:["• ",$]},F)),w.errors.length>10&&e.jsxs("li",{children:["...and ",w.errors.length-10," more"]})]})]})]}),e.jsxs(an,{children:[y==="upload"&&e.jsx(G,{variant:"outline",onClick:S,children:"Cancel"}),y==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:N,children:"Back"}),e.jsx(G,{onClick:I,disabled:m||D===0,children:m?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${D} Agent${D!==1?"s":""}`})]}),y==="result"&&e.jsx(G,{onClick:S,children:"Done"})]})]})})};function El({sortKey:s,currentSortKey:t,currentDirection:r,onSort:n,children:a,className:i,...l}){const o=t===s;return e.jsx(Nt,{className:It("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:()=>n(s),children:[a,o?r==="asc"?e.jsx(Id,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Hu,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Ad,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function bB(s=null,t=null){const[r,n]=k.useState(s),[a,i]=k.useState(t),l=k.useCallback(c=>{r===c?a==="asc"?i("desc"):a==="desc"?(n(null),i(null)):i("asc"):(n(c),i("asc"))},[r,a]),o=k.useCallback((c,d)=>{if(!r||!a||!d[r])return c;const h=d[r];return[...c].sort((m,x)=>{const y=h(m),v=h(x);if(y==null&&v==null)return 0;if(y==null)return 1;if(v==null)return-1;let w;return typeof y=="string"&&typeof v=="string"?w=y.localeCompare(v,void 0,{sensitivity:"base"}):w=y-v,a==="asc"?w:-w})},[r,a]);return{sortKey:r,sortDirection:a,handleSort:l,sortData:o}}const VJt=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Xn},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:Gi},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:eu}];function Uot({open:s,onOpenChange:t,userId:r,userName:n}){const[a,i]=k.useState("custom"),[l,o]=k.useState(""),[c,d]=k.useState(""),h=GEt(),m=y=>{i(y.type),o(y.title),d(y.message)},x=async y=>{if(y.preventDefault(),!l.trim()){cn({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await h.mutateAsync({user_id:r,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),cn({title:"Celebration sent! 🎉",description:`${n} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{cn({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(eu,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",n]}),e.jsx(Hr,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(he,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:VJt.map((y,v)=>e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>m(y),className:"text-xs",children:[e.jsx(y.icon,{className:"h-3 w-3 mr-1"}),y.title]},v))})]}),e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(Is,{value:a,onValueChange:y=>i(y),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"})," Custom"]})}),e.jsx(ct,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(ct,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(ct,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:l,onChange:y=>o(y.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"message",children:"Message (optional)"}),e.jsx(or,{id:"message",value:c,onChange:y=>d(y.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:h.isPending,children:[e.jsx(eu,{className:"h-4 w-4 mr-2"}),h.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const T1e={points_earned:{label:"Points Earned",icon:Gi,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:En,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:wl,color:"bg-green-500"},custom:{label:"Custom",icon:jr,color:"bg-purple-500"}};function HJt(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),{data:l=[],isLoading:o}=mt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:h,error:m}=await V.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(m)throw m;const x=[...new Set([...h.map(w=>w.user_id),...h.map(w=>w.created_by).filter(Boolean)])],{data:y}=await V.from("profiles").select("id, name, email").in("id",x),v=new Map((y==null?void 0:y.map(w=>[w.id,w]))||[]);return h.map(w=>{var b,N,S;return{...w,user_name:((b=v.get(w.user_id))==null?void 0:b.name)||"Unknown",user_email:((N=v.get(w.user_id))==null?void 0:N.email)||"",creator_name:w.created_by?((S=v.get(w.created_by))==null?void 0:S.name)||"System":"Auto-triggered"}})}}),c=l.filter(h=>{var v,w;const m=((v=h.user_name)==null?void 0:v.toLowerCase().includes(s.toLowerCase()))||((w=h.user_email)==null?void 0:w.toLowerCase().includes(s.toLowerCase()))||h.title.toLowerCase().includes(s.toLowerCase()),x=r==="all"||h.celebration_type===r,y=a==="all"||a==="seen"&&h.seen_at||a==="unseen"&&!h.seen_at;return m&&x&&y}),d={total:l.length,seen:l.filter(h=>h.seen_at).length,unseen:l.filter(h=>!h.seen_at).length,byType:Object.keys(T1e).reduce((h,m)=>(h[m]=l.filter(x=>x.celebration_type===m).length,h),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(es,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(eu,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Nr,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Pe,{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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by agent name, email, or title...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:r,onValueChange:n,children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"Filter by type"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),Object.entries(T1e).map(([h,m])=>e.jsx(ct,{value:h,children:m.label},h))]})]}),e.jsxs(Is,{value:a,onValueChange:i,children:[e.jsx(As,{className:"w-[140px]",children:e.jsx(Ls,{placeholder:"Status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Status"}),e.jsx(ct,{value:"seen",children:"Seen"}),e.jsx(ct,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Points"}),e.jsx(Nt,{children:"Created By"}),e.jsx(Nt,{children:"Created"}),e.jsx(Nt,{children:"Status"})]})}),e.jsx($n,{children:c.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(h=>{const m=T1e[h.celebration_type],x=m.icon;return e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(x,{className:"h-3 w-3"}),m.label]})}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.user_email})]})}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:h.title}),h.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:h.message})]})}),e.jsx(dt,{children:h.points_amount?e.jsxs(Ge,{variant:"secondary",children:["+",h.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:h.creator_name})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:_s(new Date(h.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(dt,{children:h.seen_at?e.jsx(Ge,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Ge,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},h.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const GJt=()=>{const{user:s}=js(),{toast:t}=Ma(),[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState("all"),[h,m]=k.useState("all"),[x,y]=k.useState("new"),[v,w]=k.useState(new Set),b=k.useCallback(async()=>{try{i(!0);const{data:X,error:Z}=await V.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(Z)throw Z;const{data:re,error:le}=await V.from("trial_email_exports").select("user_id");if(le)throw le;const oe=new Set((re||[]).map(ie=>ie.user_id)),ne=(X||[]).map(ie=>({...ie,converted_from_trial_at:ie.converted_from_trial_at??null,already_exported:oe.has(ie.id)}));ne.sort((ie,ye)=>new Date(ye.created_at).getTime()-new Date(ie.created_at).getTime()),n(ne)}catch(X){console.error("Error loading trial users:",X),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);k.useEffect(()=>{b()},[b]);const N=X=>X.trial_started_at?"ghl":"stripe",S=X=>X.trial_expires_at?X.trial_expires_at:X.subscription_end_date?X.subscription_end_date:null,T=X=>X.converted_from_trial_at!==null,A=X=>{if(T(X))return!1;const Z=S(X);return Z?new Date(Z).getTime()<=Date.now():!1},I=r.filter(X=>!(c!=="all"&&N(X)!==c||h==="active"&&(A(X)||T(X))||h==="expired"&&!A(X)||h==="converted"&&!T(X)||x==="new"&&X.already_exported||x==="exported"&&!X.already_exported)),D=()=>{v.size===I.length?w(new Set):w(new Set(I.map(X=>X.id)))},R=X=>{const Z=new Set(v);Z.has(X)?Z.delete(X):Z.add(X),w(Z)},$=async()=>{if(v.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const X=r.filter(ce=>v.has(ce.id)),Z="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",re=X.map(ce=>{const ve=(ce.name||"").split(" "),be=ve[0]||"",Ue=ve.slice(1).join(" ")||"",Be=N(ce)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",De=T(ce)?"Converted":A(ce)?"Expired":"Active",Ae=ce.created_at?new Date(ce.created_at).toLocaleDateString():"",He=S(ce)?new Date(S(ce)).toLocaleDateString():"";return`"${be}","${Ue}","${ce.email}","${ce.phone||""}","${Be}","${De}","${Ae}","${He}"`}),le=[Z,...re].join(` `),oe=new Blob([le],{type:"text/csv"}),ne=URL.createObjectURL(oe),ie=document.createElement("a");ie.href=ne,ie.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ie.click(),URL.revokeObjectURL(ne);const ye=X.filter(ce=>!ce.already_exported).map(ce=>({user_id:ce.id,exported_by:s.id}));if(ye.length>0){const{error:ce}=await V.from("trial_email_exports").upsert(ye,{onConflict:"user_id"});ce&&console.error("Error marking exports:",ce)}t({title:"Export complete",description:`Downloaded ${X.length} trial user(s). ${ye.length} newly marked as exported.`}),w(new Set),b()}catch(X){console.error("Export error:",X),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},F=r.filter(X=>!X.already_exported).length,z=r.filter(X=>X.already_exported).length,Q=r.filter(X=>T(X)).length,K=r.filter(X=>!A(X)&&!T(X)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(es,{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(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Total"}),e.jsx(Dt,{className:"text-2xl",children:r.length})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"New (Not Exported)"}),e.jsx(Dt,{className:"text-2xl text-green-600",children:F})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Active Trials"}),e.jsx(Dt,{className:"text-2xl",children:K})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Converted 🎉"}),e.jsx(Dt,{className:"text-2xl text-primary",children:Q})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Already Exported"}),e.jsx(Dt,{className:"text-2xl text-muted-foreground",children:z})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Is,{value:x,onValueChange:X=>y(X),children:[e.jsx(As,{className:"w-[160px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Users"}),e.jsx(ct,{value:"new",children:"New Only"}),e.jsx(ct,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(Is,{value:c,onValueChange:X=>d(X),children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Trial Types"}),e.jsx(ct,{value:"stripe",children:"Credit Card Trial"}),e.jsx(ct,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(Is,{value:h,onValueChange:X=>m(X),children:[e.jsx(As,{className:"w-[160px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Statuses"}),e.jsx(ct,{value:"active",children:"Active Trial"}),e.jsx(ct,{value:"expired",children:"Expired"}),e.jsx(ct,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(G,{onClick:$,disabled:l||v.size===0,children:[l?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Export Selected (",v.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Nt,{className:"w-[40px]",children:e.jsx(Si,{checked:I.length>0&&v.size===I.length,onCheckedChange:D})}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Trial Type"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Signup Date"}),e.jsx(Nt,{children:"Last Login"}),e.jsx(Nt,{children:"Expires / Renews"}),e.jsx(Nt,{children:"Exported"})]})}),e.jsx($n,{children:I.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):I.map(X=>{const Z=N(X),re=T(X),le=A(X),oe=S(X);return e.jsxs(Ds,{className:`hover:bg-muted/30 ${re?"bg-primary/5":""}`,children:[e.jsx(dt,{children:e.jsx(Si,{checked:v.has(X.id),onCheckedChange:()=>R(X.id)})}),e.jsx(dt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[X.name,re&&e.jsx(bo,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(dt,{className:"text-muted-foreground",children:X.email}),e.jsx(dt,{children:Z==="stripe"?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Vp,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(dt,{children:re?e.jsxs(Ge,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(bo,{className:"h-3 w-3"}),"Converted"]}):le?e.jsx(Ge,{variant:"destructive",children:"Expired"}):e.jsx(Ge,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(dt,{className:"text-sm",children:X.created_at?new Date(X.created_at).toLocaleDateString():"—"}),e.jsx(dt,{className:"text-sm",children:X.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(X.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(X.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(dt,{className:"text-sm",children:re&&oe?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(oe).toLocaleDateString()]}):oe?new Date(oe).toLocaleDateString():"—"}),e.jsx(dt,{children:X.already_exported?e.jsx(In,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ge,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},X.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",I.length," of ",r.length," trial users · ",Q," converted to paid"]})]})},WJt=()=>{const[s,t]=k.useState([]),[r,n]=k.useState(!0);return k.useEffect(()=>{(async()=>{const{data:i,error:l}=await V.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!l&&i&&t(i),n(!1)})()},[]),r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(yr,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"User Deletion History"})}),e.jsx(Pe,{children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Date"}),e.jsx(Nt,{children:"User"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Brokerage"}),e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Deleted By"})]})}),e.jsx($n,{children:s.map(a=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"whitespace-nowrap text-sm",children:_s(new Date(a.created_at),"MMM d, yyyy h:mm a")}),e.jsx(dt,{className:"font-medium",children:a.deleted_user_name||"—"}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:a.deleted_user_email||"—"}),e.jsx(dt,{children:a.brokerage_name||"—"}),e.jsx(dt,{children:e.jsx(Ge,{variant:a.deletion_type==="deleted"?"destructive":"secondary",children:a.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(dt,{className:"text-sm",children:a.deleted_by_name||a.deleted_by_email||"—"})]},a.id))})]})})]})},l5=s=>{const{user:t}=js(),r=Xt(),n=mt({queryKey:["teams",s],queryFn:async()=>{let m=V.from("teams").select("*").order("created_at",{ascending:!1});s&&(m=m.eq("brokerage_id",s));const{data:x,error:y}=await m;if(y)throw y;return x||[]},enabled:!!t}),a=m=>mt({queryKey:["team-members",m],queryFn:async()=>{const{data:x,error:y}=await V.from("team_members").select("*").eq("team_id",m).order("role",{ascending:!0});if(y)throw y;const v=(x||[]).map(N=>N.user_id),{data:w}=await V.from("profiles").select("id, name, email, avatar_url").in("id",v),b=new Map((w||[]).map(N=>[N.id,N]));return(x||[]).map(N=>({...N,profile:b.get(N.user_id)||null}))},enabled:!!m}),i=Ct({mutationFn:async m=>{const x={name:m.name,created_by:t.id,description:m.description,contact_visibility:m.contact_visibility,lead_pond_enabled:m.lead_pond_enabled,shared_assets_enabled:m.shared_assets_enabled};m.brokerage_id&&(x.brokerage_id=m.brokerage_id);const{data:y,error:v}=await V.from("teams").insert(x).select().single();if(v)throw v;return y},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),ue.success("Team created!")},onError:m=>{ue.error("Failed to create team: "+m.message)}}),l=Ct({mutationFn:async({id:m,...x})=>{const{data:y,error:v}=await V.from("teams").update(x).eq("id",m).select().single();if(v)throw v;return y},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),ue.success("Team updated")},onError:m=>{ue.error("Failed to update team: "+m.message)}}),o=Ct({mutationFn:async m=>{const{error:x}=await V.from("teams").delete().eq("id",m);if(x)throw x},onSuccess:()=>{r.invalidateQueries({queryKey:["teams"]}),ue.success("Team deleted")},onError:m=>{ue.error("Failed to delete team: "+m.message)}}),c=Ct({mutationFn:async m=>{const{data:x,error:y}=await V.from("team_members").insert({team_id:m.team_id,user_id:m.user_id,role:m.role||"team_member"}).select().single();if(y)throw y.message.includes("duplicate")||y.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):y;return x},onSuccess:(m,x)=>{r.invalidateQueries({queryKey:["team-members",x.team_id]}),ue.success("Member added to team")},onError:m=>{ue.error(m.message)}}),d=Ct({mutationFn:async m=>{const{error:x}=await V.from("team_members").delete().eq("id",m.member_id);if(x)throw x},onSuccess:(m,x)=>{r.invalidateQueries({queryKey:["team-members",x.team_id]}),ue.success("Member removed from team")},onError:m=>{ue.error("Failed to remove member: "+m.message)}}),h=Ct({mutationFn:async m=>{const{error:x}=await V.from("team_members").update({role:m.role}).eq("id",m.member_id);if(x)throw x},onSuccess:(m,x)=>{r.invalidateQueries({queryKey:["team-members",x.team_id]}),ue.success("Member role updated")},onError:m=>{ue.error("Failed to update role: "+m.message)}});return{teams:n.data||[],isLoading:n.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:h,useTeamMembers:a}},KJt=()=>{const{user:s}=js();return mt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.rpc("get_team_contacts",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},qot=s=>{const{user:t}=js(),r=Xt(),n=mt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await V.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(N=>N.contact_id),h=[...new Set(o.map(N=>N.added_by))],m=o.filter(N=>N.claimed_by).map(N=>N.claimed_by),x=[...new Set([...h,...m])],[y,v]=await Promise.all([V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),V.from("profiles").select("id, name, avatar_url").in("id",x)]),w=new Map((y.data||[]).map(N=>[N.id,N])),b=new Map((v.data||[]).map(N=>[N.id,N]));return o.map(N=>({...N,status:N.claimed_by?"claimed":"available",contact:w.get(N.contact_id)||null,contributor:b.get(N.added_by)||null,claimer:N.claimed_by&&b.get(N.claimed_by)||null}))},enabled:!!s&&!!t}),a=Ct({mutationFn:async o=>{const{data:c,error:d}=await V.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:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ue.success("Contact added to Lead Pond")},onError:o=>{ue.error(o.message)}}),i=Ct({mutationFn:async o=>{const{error:c}=await V.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ue.success("Lead claimed!")},onError:o=>{ue.error(o.message)}}),l=Ct({mutationFn:async o=>{const{error:c}=await V.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ue.success("Lead returned to pond")},onError:o=>{ue.error(o.message)}});return{leadPondItems:n.data||[],isLoading:n.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},YJt=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(n)throw n;const a=r;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"]}),ue.success("Contact transferred successfully")},onError:t=>{ue.error(t.message||"Failed to transfer contact")}})};function Vot({open:s,onOpenChange:t,contactIds:r,contactNames:n=[],onComplete:a}){var I;const{user:i}=js(),{data:l}=yg(),{useTeamMembers:o}=l5(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=YJt(),[h,m]=k.useState(null),[x,y]=k.useState(""),[v,w]=k.useState(!1),b=c.filter(D=>D.user_id!==(i==null?void 0:i.id)),N=async()=>{if(h){w(!0);try{for(const D of r)await d.mutateAsync({contactId:D,toUserId:h,notes:x||void 0});t(!1),m(null),y(""),a==null||a()}catch{}finally{w(!1)}}},S=b.find(D=>D.user_id===h),T=r.length>1,A=n.length>0?T?`${n.length} contacts`:n[0]:T?`${r.length} contacts`:"this contact";return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(ub,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(Hr,{children:["Select a team member to transfer ",T?"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(he,{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:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):b.map(D=>{var R,$,F;return e.jsxs("button",{onClick:()=>m(D.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${h===D.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:((R=D.profile)==null?void 0:R.avatar_url)||""}),e.jsx(kn,{className:"text-xs",children:((($=D.profile)==null?void 0:$.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((F=D.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:D.role.replace("_"," ")})]})]},D.user_id)})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(or,{id:"transfer-notes",value:x,onChange:D=>y(D.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:N,disabled:!h||v,children:[v?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ub,{className:"h-4 w-4 mr-2"}),"Transfer",S?` to ${(I=S.profile)==null?void 0:I.name}`:""]})]})]})})}const m5e=()=>{const s=br(),{data:t,isLoading:r}=KJt(),{data:n}=yg(),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState(null),[h,m]=k.useState(""),x=(n==null?void 0:n.role)==="team_leader",y=k.useMemo(()=>{if(!t)return[];const w=new Map;return t.forEach(b=>{w.has(b.owner_user_id)||w.set(b.owner_user_id,{id:b.owner_user_id,name:b.owner_name||"Unknown",avatar:b.owner_avatar_url})}),Array.from(w.values())},[t]),v=k.useMemo(()=>{if(!t)return[];let w=t;if(l!=="all"&&(w=w.filter(b=>b.owner_user_id===l)),a.trim()){const b=a.toLowerCase();w=w.filter(N=>{var S,T,A;return(N.first_name+" "+(N.last_name||"")).toLowerCase().includes(b)||((S=N.email)==null?void 0:S.toLowerCase().includes(b))||((T=N.phone)==null?void 0:T.includes(b))||((A=N.owner_name)==null?void 0:A.toLowerCase().includes(b))})}return w},[t,a,l]);return r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fs,{className:"h-10 w-full"}),e.jsx(Fs,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pr,{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(ke,{children:e.jsx(Pe,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:w=>i(w.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:l,onValueChange:o,children:[e.jsx(As,{className:"w-[200px]",children:e.jsx(Ls,{placeholder:"Filter by agent"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Team Members"}),y.map(w=>e.jsx(ct,{value:w.id,children:w.name},w.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[v.length," contact",v.length!==1?"s":""," from ",y.length," teammate",y.length!==1?"s":""]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0 overflow-x-auto",children:e.jsxs(Bn,{className:"min-w-[800px]",children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Contact Info"}),e.jsx(Nt,{children:"Address"}),e.jsx(Nt,{children:"Lead Source"}),e.jsx(Nt,{children:"Date Added"}),x&&e.jsx(Nt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx($n,{children:v.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:x?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):v.map(w=>e.jsxs(Ds,{className:`hover:bg-accent/50 ${x?"cursor-pointer":""}`,onClick:x?()=>s(`/mission-control/contacts/${w.id}`):void 0,children:[e.jsx(dt,{className:"font-medium",children:e.jsxs("span",{className:x?"hover:text-primary hover:underline transition-colors":"",children:[w.first_name," ",w.last_name||""]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Nn,{className:"h-6 w-6",children:[e.jsx(ya,{src:w.owner_avatar_url||""}),e.jsx(kn,{className:"text-[10px]",children:(w.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:w.owner_name||"Unknown"})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[w.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:w.email})]}),w.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Cn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:w.phone})]}),!w.email&&!w.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(dt,{children:w.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:w.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(dt,{children:w.lead_source?e.jsx(Ge,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:w.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:_s(new Date(w.created_at),"MMM d, yyyy")})}),x&&e.jsx(dt,{children:e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:b=>{b.stopPropagation(),d(w.id),m(`${w.first_name} ${w.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(ub,{className:"h-4 w-4"})})})]},w.id))})]})})}),e.jsx(Vot,{open:!!c,onOpenChange:w=>{w||d(null)},contactIds:c?[c]:[],contactNames:h?[h]:[],onComplete:()=>d(null)})]})},f5e=({teamId:s})=>{const{user:t}=js(),{leadPondItems:r,isLoading:n,claimLead:a,returnLead:i}=qot(s);if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",r.length,"loading:",n),n)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(c=>e.jsx(Fs,{className:"h-20 w-full"},c))});if(r.length===0)return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ky,{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=r.filter(c=>c.status==="available"),o=r.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,h,m,x,y,v,w;return e.jsx(ke,{children:e.jsxs(Pe,{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," ",((h=c.contact)==null?void 0:h.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 mt-1",children:[((m=c.contact)==null?void 0:m.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]}),((x=c.contact)==null?void 0:x.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(Nn,{className:"h-4 w-4",children:[e.jsx(ya,{src:((y=c.contributor)==null?void 0:y.avatar_url)||""}),e.jsx(kn,{className:"text-[8px]",children:(((v=c.contributor)==null?void 0:v.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((w=c.contributor)==null?void 0:w.name)||"Unknown"]})]})]}),e.jsxs(G,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(vR,{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,h,m;return e.jsx(ke,{className:"opacity-75",children:e.jsxs(Pe,{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," ",((h=c.contact)==null?void 0:h.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:["Claimed by ",((m=c.claimer)==null?void 0:m.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(cv,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},Hot=({teamId:s})=>{const{useTeamMembers:t}=l5(),{data:r=[]}=t(s),n=r.map(y=>y.user_id),a=new Map(r.map(y=>[y.user_id,y.profile])),{data:i=[],isLoading:l}=mt({queryKey:["team-shared-presentations",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:y,error:v}=await V.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",n).neq("status","archived").order("created_at",{ascending:!1});if(v)throw v;return y||[]},enabled:n.length>0}),{data:o=[],isLoading:c}=mt({queryKey:["team-shared-open-houses",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:y,error:v}=await V.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",n).order("event_date",{ascending:!1});if(v)throw v;return y||[]},enabled:n.length>0}),{data:d=[],isLoading:h}=mt({queryKey:["team-shared-videos",s,n],queryFn:async()=>{if(n.length===0)return[];const{data:y,error:v}=await V.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",n).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(v)throw v;return y||[]},enabled:n.length>0});if(l||c||h)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(Fs,{className:"h-20 w-full"},y))});const x=y=>{const v=a.get(y);return{name:(v==null?void 0:v.name)||"Unknown",avatar:(v==null?void 0:v.avatar_url)||"",initials:((v==null?void 0:v.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(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsx(Ty,{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(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsx(En,{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(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:d.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]}),e.jsxs(On,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Rn,{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(ts,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(E1e,{icon:e.jsx(Ty,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(y=>{const v=x(y.owner_user_id);return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Nn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ya,{src:v.avatar}),e.jsx(kn,{className:"text-xs",children:v.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:y.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.name," · ",_s(new Date(y.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Ge,{variant:y.status==="published"?"default":"secondary",className:"text-xs capitalize",children:y.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(bn,{className:"h-3 w-3"}),y.view_count||0]})]})]})},y.id)})}),e.jsx(ts,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(E1e,{icon:e.jsx(En,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(y=>{const v=x(y.agent_id);return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Nn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ya,{src:v.avatar}),e.jsx(kn,{className:"text-xs",children:v.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:y.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.name," · ",_s(new Date(y.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[y.is_active?e.jsx(Ge,{className:"text-xs",children:"Active"}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(pr,{className:"h-3 w-3"}),y.visitor_count||0]})]})]})},y.id)})}),e.jsx(ts,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(E1e,{icon:e.jsx(Jr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(y=>{const v=x(y.owner_user_id);return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Nn,{className:"h-8 w-8 shrink-0",children:[e.jsx(ya,{src:v.avatar}),e.jsx(kn,{className:"text-xs",children:v.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:y.title||y.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.name," · ",_s(new Date(y.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs capitalize",children:y.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(bn,{className:"h-3 w-3"}),y.view_count||0]})]})]})},y.id)})})]})]})},E1e=({icon:s,label:t})=>e.jsx(ke,{children:e.jsxs(Pe,{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})]})}),Got=({team:s,brokerageAgents:t,onBack:r,onUpdate:n,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var R,$;const{useTeamMembers:h}=l5(),{data:m=[],isLoading:x}=h(s.id),[y,v]=k.useState(!1),[w,b]=k.useState(""),[N,S]=k.useState("team_member"),{data:T}=mt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:F}=await V.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),z=new Map;return(F||[]).forEach(Q=>{var K;z.set(Q.user_id,((K=Q.teams)==null?void 0:K.name)||"another team")}),z}}),A=new Set(m.map(F=>F.user_id)),I=t.filter(F=>!A.has(F.id)),D=async()=>{w&&(await a(w,N),b(""),S("team_member"),v(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(G,{variant:"ghost",onClick:r,className:"mb-2",children:"← Back to Teams"}),e.jsxs(On,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Rn,{children:[e.jsx(Kt,{value:"members",children:"Members"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(R4,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Kt,{value:"lead-pond",children:[e.jsx(ky,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Kt,{value:"shared-assets",children:[e.jsx(Qh,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(ts,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:[s.name," — Members"]}),e.jsxs(fs,{open:y,onOpenChange:v,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(sl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add Team Member"}),e.jsxs(Hr,{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(he,{children:"Agent"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[w&&(((R=I.find(F=>F.id===w))==null?void 0:R.name)||(($=I.find(F=>F.id===w))==null?void 0:$.email))||"Select an agent",e.jsx(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search agents..."}),e.jsxs(ax,{children:[e.jsx(ix,{children:"No agents found."}),e.jsx(ox,{children:I.map(F=>{const z=T==null?void 0:T.get(F.id);return e.jsxs(cf,{value:F.name||F.email||F.id,disabled:!!z,onSelect:()=>b(F.id),children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",w===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(he,{children:"Role"}),e.jsxs(Is,{value:N,onValueChange:S,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"team_leader",children:"Team Leader"}),e.jsx(ct,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(G,{onClick:D,disabled:!w||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),x?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(F=>e.jsx(Fs,{className:"h-16 w-full"},F))}):m.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(pr,{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:m.map(F=>{var z,Q,K,X,Z;return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:((z=F.profile)==null?void 0:z.avatar_url)||""}),e.jsx(kn,{children:(((Q=F.profile)==null?void 0:Q.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((K=F.profile)==null?void 0:K.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(X=F.profile)==null?void 0:X.email})]}),F.role==="team_leader"?e.jsxs(Ge,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(Zh,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Ge,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Is,{value:F.role,onValueChange:re=>l(F.id,re),children:[e.jsx(As,{className:"w-[140px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"team_leader",children:"Team Leader"}),e.jsx(ct,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(KR,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Remove Member?"}),e.jsxs(Bo,{children:["Remove ",((Z=F.profile)==null?void 0:Z.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>i(F.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},F.id)})})]}),e.jsx(ts,{value:"contacts",className:"space-y-4",children:e.jsx(m5e,{})}),s.lead_pond_enabled&&e.jsx(ts,{value:"lead-pond",className:"space-y-4",children:e.jsx(f5e,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(ts,{value:"shared-assets",className:"space-y-4",children:e.jsx(Hot,{teamId:s.id})}),e.jsxs(ts,{value:"settings",className:"space-y-4",children:[e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{className:"text-lg",children:"Team Settings"}),e.jsx(Nr,{children:"Configure how this team operates."})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Team Name"}),e.jsx(Ne,{defaultValue:s.name,onBlur:F=>{F.target.value!==s.name&&n({name:F.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(or,{defaultValue:s.description||"",onBlur:F=>{F.target.value!==(s.description||"")&&n({description:F.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Contact Visibility"}),e.jsxs(Is,{defaultValue:s.contact_visibility,onValueChange:F=>n({contact_visibility:F}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(ct,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(ct,{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(he,{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(_r,{checked:s.lead_pond_enabled,onCheckedChange:F=>n({lead_pond_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:s.shared_assets_enabled,onCheckedChange:F=>n({shared_assets_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:s.shared_videos_enabled??!1,onCheckedChange:F=>n({shared_videos_enabled:F})})]})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsxs(G,{variant:"destructive",size:"sm",children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Team?"}),e.jsxs(Bo,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>{o(),r()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},Wot=({open:s,onOpenChange:t,onCreateTeam:r,isCreating:n,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=k.useState(1),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState([]),A=()=>{d(1),m(""),y(""),w(""),N(""),T([])},I=F=>{F||A(),t(F)},D=async()=>{const F=v&&v!=="none"?v:o||null;await r({name:h.trim(),description:x.trim()||void 0,brokerage_id:F,leaderId:b||void 0,memberIds:S.length>0?S:void 0}),A()},R=F=>{F!==b&&T(z=>z.includes(F)?z.filter(Q=>Q!==F):[...z,F])},$=a.filter(F=>F.id!==b);return e.jsx(fs,{open:s,onOpenChange:I,children:e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Hr,{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:It("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:It("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(he,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(Ne,{id:"team-name",value:h,onChange:F=>m(F.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"team-desc",children:"Description"}),e.jsx(or,{id:"team-desc",value:x,onChange:F=>y(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(he,{children:"Brokerage"}),e.jsxs(Is,{value:v,onValueChange:w,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"No brokerage (independent team)"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No brokerage (independent)"}),l.map(F=>e.jsx(ct,{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(he,{className:"flex items-center gap-1.5",children:[e.jsx(Zh,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(Is,{value:b,onValueChange:F=>{N(F),T(z=>z.filter(Q=>Q!==F))},children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a team leader (optional)"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No leader for now"}),a.map(F=>e.jsx(ct,{value:F.id,children:F.name||F.email||"Unknown"},F.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-1.5",children:[e.jsx(sl,{className:"h-3.5 w-3.5"}),"Initial Members",S.length>0&&e.jsxs(Ge,{variant:"secondary",className:"ml-1 text-xs",children:[S.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:$.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(pr,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):$.map(F=>{const z=S.includes(F.id);return e.jsxs("button",{type:"button",className:It("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",z&&"bg-primary/5"),onClick:()=>R(F.id),children:[e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:F.avatar_url||""}),e.jsx(kn,{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:It("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(Kn,{className:"h-3 w-3"})})]},F.id)})})]})]})}),e.jsx(an,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>d(2),disabled:!h.trim(),children:["Next",e.jsx(Ha,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",onClick:()=>d(1),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(G,{onClick:D,disabled:n,children:n?"Creating…":"Create Team"})]})})]})})},ZJt=()=>{const{teams:s,isLoading:t,createTeam:r,updateTeam:n,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=l5(),[c,d]=k.useState(!1),[h,m]=k.useState(null),[x,y]=k.useState(""),{data:v}=mt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:I,error:D}=await V.from("brokerages").select("id, name").order("name");if(D)throw D;return I||[]}}),{data:w}=mt({queryKey:["admin-team-member-info",s.map(I=>I.id).join(",")],queryFn:async()=>{var F;if(s.length===0)return{};const{data:I}=await V.from("team_members").select("team_id, user_id, role").in("team_id",s.map(z=>z.id));if(!I)return{};const D=I.filter(z=>z.role==="team_leader").map(z=>z.user_id);let R={};if(D.length>0){const{data:z}=await V.from("profiles").select("id, name").in("id",D);z&&(R=Object.fromEntries(z.map(Q=>[Q.id,{name:Q.name}])))}const $={};for(const z of s){const Q=I.filter(X=>X.team_id===z.id),K=Q.find(X=>X.role==="team_leader");$[z.id]={count:Q.length,leaderName:K&&((F=R[K.user_id])==null?void 0:F.name)||null}}return $},enabled:s.length>0}),b=(h==null?void 0:h.brokerage_id)||null,{data:N}=mt({queryKey:["brokerage-agents-for-teams",b],queryFn:async()=>{let I=V.from("profiles").select("id, name, email, avatar_url").order("name");b&&(I=I.eq("brokerage_id",b));const{data:D,error:R}=await I;if(R)throw R;return D||[]},enabled:!!h}),S=Object.fromEntries((v||[]).map(I=>[I.id,I.name])),T=async I=>{const D=await r.mutateAsync({name:I.name,brokerage_id:I.brokerage_id||null,description:I.description});if(I.leaderId&&I.leaderId!=="none"&&await i.mutateAsync({team_id:D.id,user_id:I.leaderId,role:"team_leader"}),I.memberIds)for(const R of I.memberIds)await i.mutateAsync({team_id:D.id,user_id:R,role:"team_member"});d(!1)};if(h)return e.jsx(Got,{team:h,brokerageAgents:N||[],onBack:()=>m(null),onUpdate:I=>n.mutateAsync({id:h.id,...I}).then(D=>m(D)),onAddMember:(I,D)=>i.mutateAsync({team_id:h.id,user_id:I,role:D}),onRemoveMember:I=>l.mutateAsync({team_id:h.id,member_id:I}),onUpdateRole:(I,D)=>o.mutateAsync({team_id:h.id,member_id:I,role:D}),onDeleteTeam:()=>{a.mutate(h.id),m(null)},isUpdating:n.isPending,isAddingMember:i.isPending});const A=s.filter(I=>I.name.toLowerCase().includes(x.toLowerCase())||(I.description||"").toLowerCase().includes(x.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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search teams...",value:x,onChange:I=>y(I.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(G,{size:"sm",onClick:()=>d(!0),children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(Wot,{open:c,onOpenChange:d,onCreateTeam:T,isCreating:r.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:v,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Nt,{className:"font-semibold",children:"Team Name"}),e.jsx(Nt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Nt,{className:"font-semibold",children:"Leader"}),e.jsx(Nt,{className:"font-semibold",children:"Members"}),e.jsx(Nt,{className:"font-semibold",children:"Visibility"}),e.jsx(Nt,{className:"w-[100px]"})]})}),e.jsx($n,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(I=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx(Fs,{className:"h-4 w-32"})}),e.jsx(dt,{children:e.jsx(Fs,{className:"h-4 w-24"})}),e.jsx(dt,{children:e.jsx(Fs,{className:"h-4 w-28"})}),e.jsx(dt,{children:e.jsx(Fs,{className:"h-4 w-12"})}),e.jsx(dt,{children:e.jsx(Fs,{className:"h-4 w-20"})}),e.jsx(dt,{children:e.jsx(Fs,{className:"h-4 w-16"})})]},I))}):A.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:x?"No teams match your search":"No teams found. Create one to get started."})}):A.map(I=>{const D=w==null?void 0:w[I.id];return e.jsxs(Ds,{className:"hover:bg-muted/30",children:[e.jsxs(dt,{children:[e.jsx("button",{onClick:()=>m(I),className:"text-primary hover:underline font-medium",children:I.name}),I.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:I.description})]}),e.jsx(dt,{children:I.brokerage_id?e.jsx("span",{className:"text-sm",children:S[I.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(dt,{children:D!=null&&D.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Zh,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),D.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(dt,{children:e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),(D==null?void 0:D.count)??0]})}),e.jsx(dt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Wu,{className:"h-3 w-3"}),I.contact_visibility.replace("_"," ")]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(I),title:"Edit team",children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete team "${I.name}"? This cannot be undone.`)&&a.mutate(I.id)},title:"Delete team",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})})]},I.id)})})]})})]})};function DBe(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 XJt({open:s,onOpenChange:t,recipients:r}){const{toast:n}=Ma(),[a,i]=k.useState([]),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(!1),[b,N]=k.useState(!1),S=k.useMemo(()=>a.find(D=>D.id===c)||null,[a,c]);k.useEffect(()=>{s&&(o(!0),(async()=>{const D=new Date().toISOString(),{data:R,error:$}=await V.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",D).order("event_date",{ascending:!0}).limit(50);$?n({title:"Could not load events",description:$.message,variant:"destructive"}):i(R||[]),o(!1)})())},[s,n]);const T=k.useMemo(()=>r.filter(D=>D.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(D.email)),[r]),A=()=>{if(!S){n({title:"Pick an event first",variant:"destructive"});return}if(T.length===0){n({title:"No valid recipient emails",variant:"destructive"});return}N(!0)},I=async()=>{if(S){N(!1),w(!0);try{const{data:{session:D}}=await V.auth.getSession(),R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({event_id:S.id,recipients:T.map(Q=>({email:Q.email,name:Q.name,user_id:Q.id})),custom_subject:h.trim()||void 0,custom_intro:x.trim()||void 0})}),$=await R.json().catch(()=>({}));if(!R.ok)throw new Error(($==null?void 0:$.error)||"Failed to send event invite");const F=($==null?void 0:$.sent)??0,z=($==null?void 0:$.failed)??0;n({title:"Invites sent",description:`Sent: ${F}${z?` · Failed: ${z}`:""}`}),t(!1),y(""),m(""),d("")}catch(D){const R=D instanceof Error?D.message:"Send failed";n({title:"Send failed",description:R,variant:"destructive"})}finally{w(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Hr,{children:["Send a beautiful event invitation to ",T.length," selected member",T.length===1?"":"s",".",r.length!==T.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[r.length-T.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{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(es,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(Is,{value:c,onValueChange:d,children:[e.jsx(As,{id:"event-select",children:e.jsx(Ls,{placeholder:"Pick an upcoming event..."})}),e.jsx(Ms,{children:a.map(D=>e.jsx(ct,{value:D.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:D.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[DBe(D.event_date),!D.is_published&&" · (Draft)"]})]})},D.id))})]})]}),S&&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(on,{className:"h-4 w-4 text-primary"}),S.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:DBe(S.event_date)}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:S.description})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(Ne,{id:"subject",placeholder:S?`You're invited: ${S.title}`:"You're invited to...",value:h,onChange:D=>m(D.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(he,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(or,{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:x,onChange:D=>y(D.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 (",T.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[T.slice(0,30).map(D=>e.jsx(Ge,{variant:"secondary",className:"text-xs font-normal",children:D.name||D.email},D.id)),T.length>30&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:["+",T.length-30," more"]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsx(G,{onClick:A,disabled:v||!c||T.length===0,children:v?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4 mr-2"})," Send to ",T.length]})})]})]})}),e.jsx(Ko,{open:b,onOpenChange:N,children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Send event invite?"}),e.jsx(Bo,{children:S?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',S.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[T.length," member",T.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsxs(Co,{onClick:I,children:[e.jsx(en,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const QJt=()=>{const s=br(),{user:t,isAdmin:r}=js(),{startImpersonation:n,isLoading:a}=Yme(),{toast:i}=Ma(),[l,o]=k.useState([]),[c,d]=k.useState([]),[h,m]=k.useState([]),[x,y]=k.useState({}),[v,w]=k.useState(!0);k.useState({});const[b,N]=k.useState(!1),[S,T]=k.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[A,I]=k.useState(!1),[D,R]=k.useState(""),[$,F]=k.useState(1),[z,Q]=k.useState(50),[K,X]=k.useState("all"),[Z,re]=k.useState("all"),[le,oe]=k.useState("all"),[ne,ie]=k.useState("all"),[ye,ce]=k.useState("all"),[ve,be]=k.useState(!1),[Ue,Be]=k.useState(!1),[De,Ae]=k.useState(!1),[He,Le]=k.useState(null),[Ie,Te]=k.useState(null),[xe,et]=k.useState(!1),[fe,it]=k.useState({name:"",email:"",brokerage_id:"",phone:""}),[Oe,Ye]=k.useState(null),[We,_e]=k.useState(!1),[Re,tt]=k.useState(""),[Ke,Ze]=k.useState(!1),[lt,xt]=k.useState(!1),[Xe,Je]=k.useState(null),[jt,ns]=k.useState(""),[Ns,Ys]=k.useState(!1),[rs,bt]=k.useState(!1),[cs,yt]=k.useState(null),[is,Bs]=k.useState(!1),[ps,lr]=k.useState(!1),[kr,Lr]=k.useState(null),[qr,Ur]=k.useState(""),[Mr,Cr]=k.useState(!1),[Xr,Ln]=k.useState({email:"",name:"",password:"",phone:""}),[Zs,Yr]=k.useState(!1),[ss,ta]=k.useState(!1),[nn,hr]=k.useState(""),[Pr,Qn]=k.useState(!1),[Gt,gr]=k.useState(!1),[zt,Se]=k.useState(""),[ze,st]=k.useState(new Set),[gt,At]=k.useState(!1),[Ft,Wt]=k.useState(!1),[Vt,Jt]=k.useState(null),[qs,Cs]=k.useState(!1),[xr,Wr]=k.useState(null),[tn,Rr]=k.useState([]),[sn,rn]=k.useState([]),[un,fa]=k.useState(!1),[go,wo]=k.useState({});k.useEffect(()=>{!t||!r||(ia(),Ji())},[t,r]);const co=async()=>{try{const{data:kt,error:Gs}=await V.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Gs)throw Gs;const mr={};for(const An of kt??[])mr[An.brokerage_id]||(mr[An.brokerage_id]=[]),mr[An.brokerage_id].push(An.user_id);y(mr)}catch(kt){console.error("Error loading brokerage manager assignments:",kt)}},ia=async()=>{try{w(!0);const{data:kt,error:Gs}=await V.functions.invoke("get-user-details");if(Gs)throw Gs;const mr=kt.users||[];o(mr),m(kt.brokerages||[]),await co();const An=mr.filter(wr=>wr.roles.includes("assistant"));if(An.length>0){const wr=An.map(Ia=>Ia.id),{data:Oa}=await V.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",wr);if(Oa&&Oa.length>0){const Ia=[...new Set(Oa.map(gd=>gd.agent_id))],{data:si}=await V.from("profiles").select("id, name, email").in("id",Ia),hn={};for(const gd of Oa){const Dm=si==null?void 0:si.find(sh=>sh.id===gd.agent_id);Dm&&(hn[gd.assistant_id]={agent_name:Dm.name||"",agent_email:Dm.email||""})}wo(hn)}}}catch(kt){console.error("Error loading members:",kt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{w(!1)}},Ji=async()=>{try{const{data:kt,error:Gs}=await V.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Gs)throw Gs;d(kt||[])}catch(kt){console.error("Error loading apps:",kt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},il=async kt=>{if(!fe.name.trim()||!fe.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(fe.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:mr}=await V.from("profiles").update({name:fe.name.trim(),email:fe.email.trim(),brokerage_id:fe.brokerage_id||null,phone:fe.phone.trim()||null}).eq("id",kt);if(mr)throw mr;i({title:"Success",description:"Member details updated successfully"}),Le(null),ia()}catch(mr){console.error("Error updating member:",mr),i({title:"Error",description:mr.message||"Failed to update member",variant:"destructive"})}},bi=async kt=>{try{const{data:{session:Gs}}=await V.auth.getSession(),mr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({userId:kt})}),An=await mr.json();if(!mr.ok)throw new Error(An.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Gs){console.error("Error resending welcome email:",Gs),i({title:"Error",description:Gs.message||"Failed to resend welcome email",variant:"destructive"})}},eo=async(kt,Gs)=>{try{const{error:mr}=await V.functions.invoke("send-password-reset",{body:{email:kt,redirectTo:window.location.origin}});if(mr)throw mr;i({title:"Password Reset Sent",description:`Password reset email sent to ${Gs}`})}catch(mr){console.error("Error sending password reset:",mr),i({title:"Error",description:mr.message||"Failed to send password reset email",variant:"destructive"})}},no=async(kt,Gs)=>{if(confirm(`Are you sure you want to delete ${Gs}? This action cannot be undone.`))try{const{data:{session:mr}}=await V.auth.getSession(),An=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${mr==null?void 0:mr.access_token}`},body:JSON.stringify({userId:kt})}),wr=await An.json();if(!An.ok)throw new Error(wr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),ia()}catch(mr){console.error("Error deleting user:",mr),i({title:"Error",description:mr.message||"Failed to delete user",variant:"destructive"})}},ba=async()=>{if(!S.email||!S.name||!S.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(S.role==="brokerage_manager"&&!S.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}N(!0);try{const{data:{session:kt}}=await V.auth.getSession(),Gs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`},body:JSON.stringify(S)}),mr=await Gs.json();if(!Gs.ok)throw new Error(mr.error||"Failed to create user");if(S.role&&S.role!=="user"&&mr.userId){const An=S.role==="brokerage_manager"?S.brokerage_id:void 0;await ir(mr.userId,S.role,"add",An)}i({title:"Success",description:`User ${S.email} created successfully`}),T({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),I(!1),ia()}catch(kt){console.error("Error creating user:",kt),i({title:"Error",description:kt.message||"Failed to create user",variant:"destructive"})}finally{N(!1)}},ir=async(kt,Gs,mr,An)=>{try{const{data:{session:wr}}=await V.auth.getSession(),Oa={userId:kt,role:Gs,action:mr};if(Gs==="brokerage_manager"){if(!An){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Oa.brokerageId=An}const Ia=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${wr==null?void 0:wr.access_token}`},body:JSON.stringify(Oa)}),si=await Ia.json();if(!Ia.ok)throw new Error(si.error||"Failed to manage user role");i({title:"Success",description:`Role ${mr==="add"?"added":"removed"} successfully`}),ia()}catch(wr){console.error("Error managing user role:",wr),i({title:"Error",description:wr.message||"Failed to manage user role",variant:"destructive"})}},ra=(kt,Gs)=>Gs.length===0?!0:Gs.some(mr=>kt.includes(mr)),Ci=async(kt,Gs,mr)=>{const An=`${kt}-${Gs.id}`;Ye(An);try{if(mr){const wr=l.find(Ia=>Ia.id===kt),Oa=Gs.required_tags.filter(Ia=>wr==null?void 0:wr.tags.includes(Ia));for(const Ia of Oa){const{error:si}=await V.from("user_tags").delete().eq("user_id",kt).eq("tag",Ia);if(si)throw si}i({title:"Access Removed",description:`Removed access to ${Gs.name}`})}else if(Gs.required_tags.length>0){const{error:wr}=await V.from("user_tags").insert({user_id:kt,tag:Gs.required_tags[0]});if(wr)throw wr;i({title:"Access Granted",description:`Granted access to ${Gs.name}`})}await ia()}catch(wr){console.error("Error toggling access:",wr),i({title:"Error",description:wr.message||"Failed to update access",variant:"destructive"})}finally{Ye(null)}},qo=async()=>{const kt=Re.trim();if(!kt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(kt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(h.find(mr=>mr.name.toLowerCase()===kt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}Ze(!0);try{const{error:mr}=await V.from("brokerages").insert({name:kt});if(mr)throw mr;i({title:"Success",description:`Brokerage "${kt}" created successfully`}),tt(""),_e(!1),ia()}catch(mr){console.error("Error creating brokerage:",mr),i({title:"Error",description:mr.message||"Failed to create brokerage",variant:"destructive"})}finally{Ze(!1)}},Xo=kt=>{Je(kt),ns(kt.name),xt(!0)},ol=()=>{Je(null),ns(""),xt(!1)},Kc=async()=>{if(!Xe)return;const kt=jt.trim();if(!kt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(kt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Ys(!0);try{const{error:Gs}=await V.from("brokerages").update({name:kt}).eq("id",Xe.id);if(Gs)throw Gs;i({title:"Success",description:"Brokerage updated successfully"}),ol(),ia()}catch(Gs){console.error("Error updating brokerage:",Gs),i({title:"Error",description:Gs.message||"Failed to update brokerage",variant:"destructive"})}finally{Ys(!1)}},nu=async(kt,Gs)=>{var mr;if(!Gs||typeof Gs!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const An={userId:kt,role:"brokerage_manager",action:"add",brokerageId:Gs};console.debug("[assignManagerToBrokerage] payload",An);const{data:{session:wr}}=await V.auth.getSession(),Oa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${wr==null?void 0:wr.access_token}`},body:JSON.stringify(An)}),Ia=await Oa.json();if(!Oa.ok&&!((mr=Ia.error)!=null&&mr.includes("duplicate")))throw new Error(Ia.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await ia()}catch(An){console.error("Error assigning manager:",An),i({title:"Error",description:An.message||"Failed to assign manager",variant:"destructive"})}},Nf=kt=>{yt(kt),bt(!0)},Ah=async()=>{if(cs){Bs(!0);try{const kt=l.filter(An=>An.brokerage_id===cs.id),{data:{session:Gs}}=await V.auth.getSession();for(const An of kt){const wr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({userId:An.id})});if(!wr.ok){const Oa=await wr.json();console.error(`Failed to delete user ${An.email}:`,Oa.error)}}const{error:mr}=await V.from("brokerages").delete().eq("id",cs.id);if(mr)throw mr;i({title:"Success",description:`Brokerage "${cs.name}" and ${kt.length} member(s) deleted`}),bt(!1),yt(null),ia()}catch(kt){console.error("Error deleting brokerage:",kt),i({title:"Error",description:kt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Bs(!1)}}},kf=kt=>{Lr(kt),Ur(""),lr(!0)},am=()=>{Lr(null),Ur(""),lr(!1)},ju=async kt=>{try{const{error:Gs}=await V.from("profiles").update({brokerage_id:null}).eq("id",kt);if(Gs)throw Gs;i({title:"Success",description:"User removed from brokerage"}),ia()}catch(Gs){console.error("Error removing user from brokerage:",Gs),i({title:"Error",description:Gs.message||"Failed to remove user",variant:"destructive"})}},Wv=async(kt,Gs)=>{try{const{error:mr}=await V.from("profiles").update({brokerage_id:Gs}).eq("id",kt);if(mr)throw mr;i({title:"Success",description:"User added to brokerage"}),ia()}catch(mr){console.error("Error adding user to brokerage:",mr),i({title:"Error",description:mr.message||"Failed to add user",variant:"destructive"})}},m2=async()=>{if(!kr||!Xr.email||!Xr.name||!Xr.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}Yr(!0);try{const{data:{session:kt}}=await V.auth.getSession(),Gs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`},body:JSON.stringify({...Xr,brokerage_id:kr.id,role:"user"})}),mr=await Gs.json();if(!Gs.ok)throw new Error(mr.error||"Failed to create agent");i({title:"Success",description:`Agent ${Xr.email} created successfully`}),Ln({email:"",name:"",password:"",phone:""}),Cr(!1),ia()}catch(kt){console.error("Error creating agent:",kt),i({title:"Error",description:kt.message||"Failed to create agent",variant:"destructive"})}finally{Yr(!1)}},Im=kt=>l.filter(Gs=>Gs.brokerage_id===kt),Kv=kt=>{const Gs=Im(kt);if(!qr)return Gs;const mr=qr.toLowerCase();return Gs.filter(An=>An.name.toLowerCase().includes(mr)||An.email.toLowerCase().includes(mr))},Zb=kt=>l.filter(Gs=>Gs.brokerage_id!==kt),Wy=l.filter(kt=>{var mr;if(D){const An=D.toLowerCase();if(!(kt.name.toLowerCase().includes(An)||kt.email.toLowerCase().includes(An)||((mr=kt.brokerage_name)==null?void 0:mr.toLowerCase().includes(An))))return!1}if(K==="claimed"&&!kt.claimed||K==="unclaimed"&&kt.claimed||Z!=="all"&&!kt.roles.includes(Z))return!1;const Gs=kt.is_trial||kt.subscription_status==="trialing";if(le==="trial"&&!Gs||le==="non-trial"&&Gs||ne==="none"&&kt.brokerage_id||ne!=="all"&&ne!=="none"&&kt.brokerage_id!==ne)return!1;if(ye!=="all"){if(!kt.created_at)return!1;const An=parseInt(ye,10),wr=Date.now()-An*24*60*60*1e3;if(new Date(kt.created_at).getTime(){var Gs;return((Gs=kt.name)==null?void 0:Gs.toLowerCase())||""},brokerage:kt=>{var Gs;return((Gs=kt.brokerage_name)==null?void 0:Gs.toLowerCase())||""},status:kt=>kt.claimed?"active":"pending",role:kt=>kt.roles[0]||"",last_login:kt=>kt.last_sign_in_at?new Date(kt.last_sign_in_at).getTime():null,created_at:kt=>kt.created_at?new Date(kt.created_at).getTime():null}),Mh=Lm.length,cp=z===0,au=cp?1:Math.ceil(Mh/z),ku=cp?0:($-1)*z,Yv=cp?Mh:ku+z,zd=Lm.slice(ku,Yv),Zv=kt=>{R(kt),F(1)},p2=kt=>{Q(kt),F(1)},Tg=(kt,Gs)=>{kt(Gs),F(1)},qa=async(kt,Gs)=>{Be(!0);try{const mr=l.find(Ia=>Ia.id===kt);if(!mr)return;const An=mr.trial_expires_at?new Date(mr.trial_expires_at):new Date,wr=new Date(An.getTime()+Gs*24*60*60*1e3),{error:Oa}=await V.from("profiles").update({trial_expires_at:wr.toISOString()}).eq("id",kt);if(Oa)throw Oa;i({title:"Trial Extended",description:`Trial extended by ${Gs} days`}),ia()}catch(mr){console.error("Error extending trial:",mr),i({title:"Error",description:mr.message||"Failed to extend trial",variant:"destructive"})}finally{Be(!1)}},Ky=async kt=>{Ae(!0);try{const{error:Gs}=await V.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",kt);if(Gs)throw Gs;i({title:"Account Converted",description:"User has been converted to a full account"}),ia(),Ag()}catch(Gs){console.error("Error converting trial:",Gs),i({title:"Error",description:Gs.message||"Failed to convert account",variant:"destructive"})}finally{Ae(!1)}},[Yy,g5]=k.useState(!1),Xb=async(kt,Gs)=>{if(confirm(`Revert this user to a ${Gs}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){g5(!0);try{const mr=new Date,An=new Date(mr.getTime()+Gs*24*60*60*1e3),{error:wr}=await V.from("profiles").update({is_trial:!0,trial_started_at:mr.toISOString(),trial_expires_at:An.toISOString(),trial_claimed_at:mr.toISOString(),is_grandfathered:!1,subscription_status:"none",subscription_end_date:null,subscription_product_id:null,subscription_price_id:null,converted_from_trial_at:null}).eq("id",kt);if(wr)throw wr;i({title:"Reverted to Trial",description:`User is now on a ${Gs}-day free trial.`}),ia()}catch(mr){console.error("Error reverting to trial:",mr),i({title:"Error",description:mr.message||"Failed to revert to trial",variant:"destructive"})}finally{g5(!1)}}},gx=async kt=>{fa(!0);try{const{data:Gs}=await V.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",kt);if(Gs&&Gs.length>0){const An=Gs.map(Oa=>Oa.assistant_id),{data:wr}=await V.from("profiles").select("id, name, email").in("id",An);Rr(Gs.map(Oa=>{const Ia=wr==null?void 0:wr.find(si=>si.id===Oa.assistant_id);return{id:Oa.id,assistant_id:Oa.assistant_id,assistant_name:(Ia==null?void 0:Ia.name)||"Unknown",assistant_email:(Ia==null?void 0:Ia.email)||"",permissions:Oa.permissions||{}}}))}else Rr([]);const{data:mr}=await V.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",kt);if(mr&&mr.length>0){const An=mr.map(Oa=>Oa.agent_id),{data:wr}=await V.from("profiles").select("id, name, email").in("id",An);rn(mr.map(Oa=>{const Ia=wr==null?void 0:wr.find(si=>si.id===Oa.agent_id);return{id:Oa.id,agent_id:Oa.agent_id,agent_name:(Ia==null?void 0:Ia.name)||"Unknown",agent_email:(Ia==null?void 0:Ia.email)||"",permissions:Oa.permissions||{}}}))}else rn([])}catch(Gs){console.error("Error loading assistant data:",Gs)}finally{fa(!1)}},Eg=kt=>{Te(kt),it({name:kt.name,email:kt.email,brokerage_id:kt.brokerage_id||"",phone:kt.phone||""}),et(!0),gx(kt.id)},Ag=()=>{Te(null),et(!1),it({name:"",email:"",brokerage_id:"",phone:""})},Qb=async()=>{Ie&&(await il(Ie.id),Ag())},y5=kt=>{st(Gs=>{const mr=new Set(Gs);return mr.has(kt)?mr.delete(kt):mr.add(kt),mr})},Mg=()=>{if(ze.size===zd.length&&zd.every(kt=>ze.has(kt.id))){const kt=new Set(ze);zd.forEach(Gs=>kt.delete(Gs.id)),st(kt)}else{const kt=new Set(ze);zd.forEach(Gs=>kt.add(Gs.id)),st(kt)}},Xv=()=>{st(new Set)},x2=async()=>{if(ze.size===0)return;At(!0);let kt=0,Gs=0;try{const{data:{session:mr}}=await V.auth.getSession();for(const An of ze)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${mr==null?void 0:mr.access_token}`},body:JSON.stringify({userId:An})})).ok?kt++:Gs++}catch{Gs++}i({title:"Bulk Email Complete",description:`Sent ${kt} emails${Gs>0?`, ${Gs} failed`:""}`}),Xv()}catch(mr){i({title:"Error",description:mr.message||"Failed to send emails",variant:"destructive"})}finally{At(!1)}},PL=async()=>{if(ze.size===0)return;At(!0);let kt=0,Gs=0;try{const{data:{session:mr}}=await V.auth.getSession();for(const An of ze)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${mr==null?void 0:mr.access_token}`},body:JSON.stringify({userId:An})})).ok?kt++:Gs++}catch{Gs++}i({title:"Bulk Password Reset Complete",description:`Sent ${kt} reset emails${Gs>0?`, ${Gs} failed`:""}`}),Xv()}catch(mr){i({title:"Error",description:mr.message||"Failed to send password reset emails",variant:"destructive"})}finally{At(!1)}},yx=async()=>{if(ze.size===0)return;const kt=l.filter(wr=>ze.has(wr.id)).map(wr=>wr.name).slice(0,5).join(", "),Gs=ze.size>5?` and ${ze.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${ze.size} users (${kt}${Gs})? This action cannot be undone.`))return;At(!0);let mr=0,An=0;try{const{data:{session:wr}}=await V.auth.getSession();for(const Oa of ze)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${wr==null?void 0:wr.access_token}`},body:JSON.stringify({userId:Oa})})).ok?mr++:An++}catch{An++}i({title:"Bulk Delete Complete",description:`Deleted ${mr} users${An>0?`, ${An} failed`:""}`}),Xv(),ia()}catch(wr){i({title:"Error",description:wr.message||"Failed to delete users",variant:"destructive"})}finally{At(!1)}},Pm=async()=>{Wt(!0);try{const{data:{session:kt}}=await V.auth.getSession(),Gs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${kt==null?void 0:kt.access_token}`}});if(!Gs.ok){const An=await Gs.json();throw new Error(An.error||"Failed to sync phones")}const mr=await Gs.json();i({title:"Phone Sync Complete",description:`Pulled ${mr.summary.pulledFromGHL} from GHL, pushed ${mr.summary.pushedToGHL} to GHL, ${mr.summary.alreadySynced} already synced`}),ia()}catch(kt){i({title:"Error",description:kt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Wt(!1)}},Zy=async(kt,Gs)=>{Jt(kt);try{const{data:{session:mr}}=await V.auth.getSession(),{data:An}=await V.from("profiles").select("phone").eq("id",kt).single(),wr=(An==null?void 0:An.phone)||"",Oa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${mr==null?void 0:mr.access_token}`},body:JSON.stringify({email:Gs,action:"update",phone:wr||void 0})});if(!Oa.ok){const si=await Oa.json();throw new Error(si.error||"Failed to sync with GHL")}const Ia=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Gs)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:wr?`Phone ${wr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),ia()}catch(mr){i({title:"Error",description:mr.message||"Failed to sync phone",variant:"destructive"})}finally{Jt(null)}},Ih=async kt=>{await n(kt)},Jb=()=>{if(ze.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const kt=l.filter(si=>ze.has(si.id)),Gs=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],mr=kt.map(si=>[si.name,si.email,si.phone||"",si.brokerage_name||"",si.roles.join("; "),si.claimed?"Claimed":"Unclaimed",new Date(si.created_at).toLocaleDateString()]),An=[Gs.join(","),...mr.map(si=>si.map(hn=>`"${(hn||"").replace(/"/g,'""')}"`).join(","))].join(` `),wr=new Blob([An],{type:"text/csv"}),Oa=URL.createObjectURL(wr),Ia=document.createElement("a");Ia.href=Oa,Ia.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Ia.click(),URL.revokeObjectURL(Oa),i({title:"Export complete",description:`Exported ${kt.length} member(s)`})},Qv=()=>{if(Wy.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const kt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Gs=Wy.map(si=>[si.name,si.email,si.phone||"",si.brokerage_name||"",si.roles.join("; "),si.claimed?"Claimed":"Unclaimed",si.created_at?new Date(si.created_at).toLocaleDateString():""]),mr=[kt.join(","),...Gs.map(si=>si.map(hn=>`"${(hn||"").replace(/"/g,'""')}"`).join(","))].join(` `),An=new Blob([mr],{type:"text/csv"}),wr=URL.createObjectURL(An),Oa=document.createElement("a"),Ia=ye!=="all"?`-last-${ye}days`:"";Oa.href=wr,Oa.download=`members-export${Ia}-${new Date().toISOString().split("T")[0]}.csv`,Oa.click(),URL.revokeObjectURL(wr),i({title:"Export complete",description:`Exported ${Wy.length} member(s)`})};return v?e.jsx(ws,{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(ws,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Member Management",description:"Manage users, roles, and permissions"}),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(G,{size:"sm",variant:"outline",onClick:Pm,disabled:Ft,children:[Ft?e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Cn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Ft?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:Ft?"Syncing...":"Sync GHL"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>ta(!0),children:[e.jsx(mb,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import CSV"}),e.jsx("span",{className:"sm:hidden",children:"Import"})]}),e.jsxs(fs,{open:A,onOpenChange:I,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(sl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create New User"}),e.jsx(Hr,{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(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",placeholder:"John Doe",value:S.name,onChange:kt=>T({...S,name:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",placeholder:"john@example.com",value:S.email,onChange:kt=>T({...S,email:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"password",children:"Password"}),e.jsx(Ne,{id:"password",type:"password",placeholder:"Min 6 characters",value:S.password,onChange:kt=>T({...S,password:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"phone",type:"tel",placeholder:"555-123-4567",value:S.phone,onChange:kt=>T({...S,phone:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"brokerage",children:["Brokerage",S.role==="brokerage_manager"?" (required)":""]}),e.jsxs(Is,{value:S.brokerage_id||"none",onValueChange:kt=>T({...S,brokerage_id:kt==="none"?"":kt}),children:[e.jsx(As,{id:"brokerage",children:e.jsx(Ls,{placeholder:S.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"None"}),h.map(kt=>e.jsx(ct,{value:kt.id,children:kt.name},kt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"role",children:"Role"}),e.jsxs(Is,{value:S.role,onValueChange:kt=>T({...S,role:kt}),children:[e.jsx(As,{id:"role",children:e.jsx(Ls,{placeholder:"Select role"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"user",children:"User"}),e.jsx(ct,{value:"moderator",children:"Moderator"}),e.jsx(ct,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(ct,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(Is,{value:S.trial_days||"none",onValueChange:kt=>T({...S,trial_days:kt==="none"?"":kt}),children:[e.jsx(As,{id:"trial_days",children:e.jsx(Ls,{placeholder:"No trial (full access)"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No trial (full access)"}),e.jsx(ct,{value:"7",children:"7-day trial"}),e.jsx(ct,{value:"30",children:"30-day trial"}),e.jsx(ct,{value:"60",children:"60-day trial"}),e.jsx(ct,{value:"90",children:"90-day trial"}),e.jsx(ct,{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(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx(G,{onClick:ba,disabled:b,children:b?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(On,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Rn,{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(ts,{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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search members...",value:D,onChange:kt=>Zv(kt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Is,{value:K,onValueChange:kt=>Tg(X,kt),children:[e.jsx(As,{className:"w-[130px] h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Status"}),e.jsx(ct,{value:"claimed",children:"Active"}),e.jsx(ct,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(Is,{value:Z,onValueChange:kt=>Tg(re,kt),children:[e.jsx(As,{className:"w-[130px] h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Roles"}),e.jsx(ct,{value:"admin",children:"Admin"}),e.jsx(ct,{value:"brokerage_manager",children:"Manager"}),e.jsx(ct,{value:"assistant",children:"Assistant"}),e.jsx(ct,{value:"user",children:"User"})]})]}),e.jsxs(Is,{value:le,onValueChange:kt=>Tg(oe,kt),children:[e.jsx(As,{className:"w-[130px] h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Users"}),e.jsx(ct,{value:"trial",children:"Trial Only"}),e.jsx(ct,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(Is,{value:ne,onValueChange:kt=>Tg(ie,kt),children:[e.jsx(As,{className:"w-[150px] h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Brokerages"}),e.jsx(ct,{value:"none",children:"No Brokerage"}),h.map(kt=>e.jsx(ct,{value:kt.id,children:kt.name},kt.id))]})]}),e.jsxs(Is,{value:ye,onValueChange:kt=>Tg(ce,kt),children:[e.jsx(As,{className:"w-[150px] h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"Any Join Date"}),e.jsx(ct,{value:"30",children:"Joined Last 30 Days"}),e.jsx(ct,{value:"60",children:"Joined Last 60 Days"}),e.jsx(ct,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(G,{size:"sm",variant:"outline",className:"h-9",onClick:Qv,title:"Export currently filtered members to CSV",children:[e.jsx(Ya,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(D||K!=="all"||Z!=="all"||le!=="all"||ne!=="all"||ye!=="all")&&e.jsxs(G,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),X("all"),re("all"),oe("all"),ie("all"),ce("all"),F(1)},children:[e.jsx(vr,{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:cp?`Showing all ${Mh} members`:`Showing ${ku+1}-${Math.min(Yv,Mh)} of ${Mh} members`}),e.jsxs(Is,{value:z.toString(),onValueChange:kt=>p2(Number(kt)),children:[e.jsx(As,{className:"h-9 w-[110px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"50",children:"50 / page"}),e.jsx(ct,{value:"100",children:"100 / page"}),e.jsx(ct,{value:"250",children:"250 / page"}),e.jsx(ct,{value:"0",children:"All"})]})]})]})]}),ze.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[zd.length>0&&zd.every(kt=>ze.has(kt.id))&&Lm.length>ze.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 ",ze.size," on this page are selected."]}),e.jsxs(G,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>st(new Set(Lm.map(kt=>kt.id))),children:["Select all ",Lm.length," filtered members"]})]}),Lm.length>0&&ze.size===Lm.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Lm.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(Z1,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[ze.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:x2,disabled:gt,children:[gt?e.jsx(es,{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(G,{size:"sm",variant:"outline",onClick:PL,disabled:gt,children:[gt?e.jsx(es,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(ep,{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(G,{size:"sm",variant:"outline",onClick:()=>be(!0),disabled:gt,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(cR,{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(G,{size:"sm",variant:"outline",onClick:Jb,children:[e.jsx(Ya,{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(G,{size:"sm",variant:"destructive",onClick:yx,disabled:gt,children:[gt?e.jsx(es,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(yr,{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(G,{size:"sm",variant:"ghost",onClick:Xv,disabled:gt,children:e.jsx(vr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Nt,{className:"w-[50px]",children:e.jsx(Si,{checked:zd.length>0&&zd.every(kt=>ze.has(kt.id)),onCheckedChange:Mg,"aria-label":"Select all on page"})}),e.jsx(El,{sortKey:"name",currentSortKey:Nu,currentDirection:Cg,onSort:lp,children:"Name"}),e.jsx(El,{sortKey:"brokerage",currentSortKey:Nu,currentDirection:Cg,onSort:lp,children:"Brokerage"}),e.jsx(El,{sortKey:"status",currentSortKey:Nu,currentDirection:Cg,onSort:lp,children:"Status"}),e.jsx(El,{sortKey:"role",currentSortKey:Nu,currentDirection:Cg,onSort:lp,children:"Role"}),e.jsx(El,{sortKey:"last_login",currentSortKey:Nu,currentDirection:Cg,onSort:lp,children:"Last Login"}),e.jsx(El,{sortKey:"created_at",currentSortKey:Nu,currentDirection:Cg,onSort:lp,children:"Member Since"}),e.jsx(Nt,{className:"w-[100px]"})]})}),e.jsx($n,{children:zd.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):zd.map(kt=>e.jsxs(Ds,{className:`hover:bg-muted/30 ${ze.has(kt.id)?"bg-primary/5":""}`,children:[e.jsx(dt,{children:e.jsx(Si,{checked:ze.has(kt.id),onCheckedChange:()=>y5(kt.id),"aria-label":`Select ${kt.name}`})}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>Eg(kt),className:"text-primary hover:underline font-medium text-left",children:kt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:kt.email})]})}),e.jsx(dt,{className:"text-muted-foreground",children:kt.brokerage_name||"—"}),e.jsx(dt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Gs=kt.trial_expires_at||kt.subscription_end_date;if((kt.is_trial||kt.subscription_status==="trialing")&&Gs){const An=Math.ceil((new Date(Gs).getTime()-Date.now())/864e5),wr=An<=0,Oa=An<=3;return e.jsx(Ge,{variant:"outline",className:It("w-fit",wr?"border-destructive text-destructive":Oa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:wr?"Trial Expired":`Trial · ${An}d left`})}return e.jsx(Ge,{variant:kt.claimed?"default":"secondary",className:kt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:kt.claimed?"Active":"Pending"})})()})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex flex-col",children:[kt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:kt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),kt.roles.includes("assistant")&&go[kt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",go[kt.id].agent_name||go[kt.id].agent_email]})]})}),e.jsx(dt,{className:"text-muted-foreground",children:kt.last_sign_in_at?new Date(kt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(dt,{className:"text-muted-foreground",children:kt.created_at?new Date(kt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{Wr(kt),Cs(!0)},title:"Send celebration",children:e.jsx(eu,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Eg(kt),title:"Edit member",children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Zy(kt.id,kt.email),disabled:Vt===kt.id,title:"Sync phone with GHL",children:Vt===kt.id?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(Cn,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>bi(kt.id),title:"Resend welcome email",children:e.jsx(Vs,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>eo(kt.email,kt.name),title:"Send password reset",children:e.jsx(z4,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Ih(kt.id),disabled:a||kt.id===(t==null?void 0:t.id),title:kt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${kt.name}`,children:a?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(V4,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>no(kt.id,kt.name),title:"Delete user",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},kt.id))})]})}),au>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 ",$," of ",au]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>F(1),disabled:$===1,children:"First"}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(kt=>Math.max(1,kt-1)),disabled:$===1,children:e.jsx($o,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,au)},(kt,Gs)=>{let mr;return au<=5||$<=3?mr=Gs+1:$>=au-2?mr=au-4+Gs:mr=$-2+Gs,e.jsx(G,{variant:$===mr?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>F(mr),children:mr},mr)})}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(kt=>Math.min(au,kt+1)),disabled:$===au,children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>F(au),disabled:$===au,children:"Last"})]})]})]}),e.jsx(fs,{open:xe,onOpenChange:et,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Edit Member"}),e.jsx(Hr,{children:"Update member details, roles, and app access"})]}),Ie&&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(he,{htmlFor:"edit-name",children:"Name"}),e.jsx(Ne,{id:"edit-name",value:fe.name,onChange:kt=>it({...fe,name:kt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-email",children:"Email"}),e.jsx(Ne,{id:"edit-email",type:"email",value:fe.email,onChange:kt=>it({...fe,email:kt.target.value}),maxLength:255})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(Ne,{id:"edit-phone",type:"tel",value:fe.phone,onChange:kt=>it({...fe,phone:kt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(Is,{value:fe.brokerage_id||"none",onValueChange:kt=>it({...fe,brokerage_id:kt==="none"?"":kt}),children:[e.jsx(As,{id:"edit-brokerage",children:e.jsx(Ls,{placeholder:"Select brokerage"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"None"}),h.map(kt=>e.jsx(ct,{value:kt.id,children:kt.name},kt.id))]})]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Roles"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Ie.roles.map(kt=>e.jsxs(Ge,{variant:"default",className:"gap-1",children:[e.jsx(Wu,{className:"h-3 w-3"}),kt,kt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>ir(Ie.id,kt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(vr,{className:"h-3 w-3"})})]},kt)),Ie.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(Is,{onValueChange:kt=>ir(Ie.id,kt,"add"),children:[e.jsx(As,{className:"w-[200px]",children:e.jsx(Ls,{placeholder:"Add role..."})}),e.jsxs(Ms,{children:[!Ie.roles.includes("admin")&&e.jsx(ct,{value:"admin",children:"Admin"}),!Ie.roles.includes("user")&&e.jsx(ct,{value:"user",children:"User"})]})]}),!Ie.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"})]}),(tn.length>0||sn.length>0||Ie.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(pr,{className:"h-4 w-4"}),"Assistant Relationships"]}),un?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[tn.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:"}),tn.map(kt=>e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:kt.assistant_name}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:kt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(kt.permissions).filter(([,Gs])=>Gs).map(([Gs])=>e.jsx(Ge,{variant:"secondary",className:"text-[10px] capitalize",children:Gs},Gs))})]},kt.id))]}),sn.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:"}),sn.map(kt=>e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:kt.agent_name}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:kt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(kt.permissions).filter(([,Gs])=>Gs).map(([Gs])=>e.jsx(Ge,{variant:"secondary",className:"text-[10px] capitalize",children:Gs},Gs))})]},kt.id))]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"App Access"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Toggle which apps this member can access"}),e.jsx("div",{className:"grid gap-3",children:c.map(kt=>{const Gs=ra(Ie.tags,kt.required_tags),mr=`${Ie.id}-${kt.id}`,An=Oe===mr,wr=kt.required_tags.length===0;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xl",children:kt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:kt.name}),wr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:An?e.jsx(es,{className:"h-4 w-4 animate-spin text-muted-foreground"}):wr?e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(_r,{checked:Gs,onCheckedChange:()=>Ci(Ie.id,kt,Gs)})})]},kt.id)})})]}),(Ie.is_trial||Ie.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(fn,{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:[Ie.trial_expires_at&&e.jsx(PBe,{expiresAt:Ie.trial_expires_at}),!Ie.trial_expires_at&&Ie.subscription_status==="trialing"&&Ie.subscription_end_date&&e.jsx(PBe,{expiresAt:Ie.subscription_end_date})]}),(Ie.trial_expires_at||Ie.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Ie.trial_expires_at||Ie.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>qa(Ie.id,7),disabled:Ue,children:[e.jsx(rb,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>qa(Ie.id,14),disabled:Ue,children:[e.jsx(rb,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>qa(Ie.id,30),disabled:Ue,children:[e.jsx(rb,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(G,{size:"sm",variant:"default",onClick:()=>Ky(Ie.id),disabled:De,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(uv,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Ie.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Ie.trial_started_at).toLocaleDateString(),Ie.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Ie.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Ie.is_trial||Ie.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(fn,{className:"h-4 w-4"}),"Revert to Free Trial"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Move this user back to a free trial. Clears paid/grandfathered status. If they have an active Stripe subscription, cancel it separately in Stripe."}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[7,14,30,60,90].map(kt=>e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>Xb(Ie.id,kt),disabled:Yy,children:[e.jsx(rb,{className:"h-4 w-4 mr-1"}),kt,"-day trial"]},kt))})]})]}),e.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Account Information"}),e.jsxs("div",{className:"text-sm space-y-1 text-muted-foreground",children:[Ie.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Ie.email_confirmed_at).toLocaleString()]}),Ie.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Ie.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Ie.created_at).toLocaleString()]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:Ag,children:"Cancel"}),e.jsx(G,{onClick:Qb,children:"Save Changes"})]})]})}),e.jsxs(ts,{value:"access",children:[c.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(G,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(ke,{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(Dt,{children:"Member Access Matrix"}),e.jsx(Nr,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents by name or email...",value:D,onChange:kt=>{R(kt.target.value),F(1)},className:"pl-9"})]})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(kt=>e.jsx("th",{className:"text-center p-4 font-semibold min-w-[120px]",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-2xl",children:kt.icon}),e.jsx("span",{className:"text-sm",children:kt.name})]})},kt.id))]})}),e.jsxs("tbody",{children:[zd.map(kt=>e.jsxs("tr",{className:"border-b hover:bg-muted/50",children:[e.jsx("td",{className:"p-4 sticky left-0 bg-card z-10",children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:kt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:kt.email})]})}),c.map(Gs=>{const mr=ra(kt.tags,Gs.required_tags),An=`${kt.id}-${Gs.id}`,wr=Oe===An;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:wr?e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(_r,{checked:mr,onCheckedChange:()=>Ci(kt.id,Gs,mr),disabled:Gs.required_tags.length===0})})},Gs.id)})]},kt.id)),zd.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"})})]})]})}),au>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 ",ku+1,"-",Math.min(Yv,Mh)," of ",Mh," • Page ",$," of ",au]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(kt=>Math.max(1,kt-1)),disabled:$===1,children:e.jsx($o,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(kt=>Math.min(au,kt+1)),disabled:$===au,children:e.jsx(va,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(G,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(ts,{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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search brokerages...",value:nn,onChange:kt=>hr(kt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[h.filter(kt=>kt.name.toLowerCase().includes(nn.toLowerCase())).length," of ",h.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{const kt=[];for(const Ia of h){const si=x[Ia.id]??[];for(const hn of si){const gd=l.find(Dm=>Dm.id===hn);if(gd){const Dm=(gd.name||"").trim().split(/\s+/),sh=Dm[0]||"",Ig=Dm.slice(1).join(" ")||"";kt.push({firstName:sh,lastName:Ig,email:gd.email,brokerageName:Ia.name})}}}if(kt.length===0){i({title:"No managers found to export"});return}const mr=[["First Name","Last Name","Email","Brokerage Name"].join(","),...kt.map(Ia=>[Ia.firstName,Ia.lastName,Ia.email,Ia.brokerageName].map(si=>`"${(si||"").replace(/"/g,'""')}"`).join(","))].join(` `),An=new Blob([mr],{type:"text/csv"}),wr=URL.createObjectURL(An),Oa=document.createElement("a");Oa.href=wr,Oa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Oa.click(),URL.revokeObjectURL(wr),i({title:`Exported ${kt.length} managers`})},children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(fs,{open:We,onOpenChange:_e,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create New Brokerage"}),e.jsx(Hr,{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(he,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(Ne,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Re,onChange:kt=>tt(kt.target.value),maxLength:100})]})}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>_e(!1),children:"Cancel"}),e.jsx(G,{onClick:qo,disabled:Ke,children:Ke?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Nt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Nt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Nt,{className:"font-semibold",children:"Agents"}),e.jsx(Nt,{className:"w-[150px]"})]})}),e.jsx($n,{children:(()=>{const kt=h.filter(Gs=>Gs.name.toLowerCase().includes(nn.toLowerCase()));return kt.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:nn?"No brokerages match your search":"No brokerages found"})}):kt.map(Gs=>{const mr=l.filter(Ia=>Ia.brokerage_id===Gs.id),wr=(x[Gs.id]??[]).map(Ia=>l.find(si=>si.id===Ia)).filter(Boolean),Oa=mr.length;return e.jsxs(Ds,{className:"hover:bg-muted/30",children:[e.jsx(dt,{children:e.jsx("button",{onClick:()=>Xo(Gs),className:"text-primary hover:underline font-medium",children:Gs.name})}),e.jsx(dt,{children:wr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:wr.map(Ia=>e.jsx(Ge,{variant:"secondary",className:"text-xs",children:Ia.name},Ia.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(dt,{children:[Oa," member",Oa!==1?"s":""]}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"h-8",onClick:()=>kf(Gs),children:[e.jsx(pr,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Xo(Gs),title:"Edit brokerage",children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Nf(Gs),title:"Delete brokerage",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Gs.id)})})()})]})}),e.jsx(fs,{open:lt,onOpenChange:xt,children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Edit Brokerage"}),e.jsx(Hr,{children:"Update brokerage details and manage managers"})]}),Xe&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(Ne,{id:"edit-brokerage-name",value:jt,onChange:kt=>ns(kt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{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 Gs=(x[Xe.id]??[]).map(mr=>l.find(An=>An.id===mr)).filter(Boolean);return Gs.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Gs.map(mr=>e.jsxs(Ge,{variant:"default",className:"gap-1",children:[e.jsx(Wu,{className:"h-3 w-3"}),mr.name,e.jsx("button",{onClick:()=>ir(mr.id,"brokerage_manager","remove",Xe.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(vr,{className:"h-3 w-3"})})]},mr.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(To,{open:Pr,onOpenChange:Qn,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":Pr,className:"w-full justify-between",children:["Search for a member...",e.jsx(yn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-full p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search by name or email..."}),e.jsxs(ax,{className:"max-h-[200px]",children:[e.jsx(ix,{children:"No members found."}),e.jsx(ox,{children:(()=>{const kt=new Set(x[Xe.id]??[]);return l.filter(Gs=>!kt.has(Gs.id)&&(r||Gs.brokerage_id===Xe.id)).map(Gs=>e.jsxs(cf,{value:`${Gs.name} ${Gs.email}`,onSelect:()=>{nu(Gs.id,Xe.id),Qn(!1)},children:[Gs.name," (",Gs.email,")"]},Gs.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(kt=>kt.brokerage_id===Xe.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(kt=>kt.brokerage_id===Xe.id).map(kt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:kt.name}),kt.roles.includes("brokerage_manager")&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Manager"})]},kt.id))})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:ol,children:"Cancel"}),e.jsx(G,{onClick:Kc,disabled:Ns,children:Ns?"Saving...":"Save Changes"})]})]})}),e.jsx(fs,{open:rs,onOpenChange:bt,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Hr,{children:['Are you sure you want to delete "',cs==null?void 0:cs.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 "',cs==null?void 0:cs.name,'"']}),e.jsxs("li",{children:["All ",l.filter(kt=>kt.brokerage_id===(cs==null?void 0:cs.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>bt(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:Ah,disabled:is,children:is?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(fs,{open:ps,onOpenChange:lr,children:e.jsxs(ms,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-5 w-5"}),"Manage ",kr==null?void 0:kr.name]}),e.jsx(Hr,{children:"Add, remove, or manage users in this brokerage"})]}),kr&&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(yn,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search members...",value:qr,onChange:kt=>Ur(kt.target.value),className:"pl-10 h-9"})]}),e.jsxs(fs,{open:Mr,onOpenChange:Cr,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx(sl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add New Agent"}),e.jsxs(Hr,{children:["Create a new agent for ",kr.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-name",children:"Name"}),e.jsx(Ne,{id:"agent-name",placeholder:"John Doe",value:Xr.name,onChange:kt=>Ln({...Xr,name:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-email",children:"Email"}),e.jsx(Ne,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Xr.email,onChange:kt=>Ln({...Xr,email:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-password",children:"Password"}),e.jsx(Ne,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Xr.password,onChange:kt=>Ln({...Xr,password:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Xr.phone,onChange:kt=>Ln({...Xr,phone:kt.target.value})})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>Cr(!1),children:"Cancel"}),e.jsx(G,{onClick:m2,disabled:Zs,children:Zs?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(To,{open:Gt,onOpenChange:gr,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":Gt,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(yn,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[300px] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search users...",value:zt,onValueChange:Se}),e.jsxs(ax,{children:[e.jsx(ix,{children:"No users found."}),e.jsx(ox,{children:Zb(kr.id).filter(kt=>zt===""||kt.name.toLowerCase().includes(zt.toLowerCase())||kt.email.toLowerCase().includes(zt.toLowerCase())).map(kt=>e.jsxs(cf,{value:`${kt.name} ${kt.email}`,onSelect:()=>{Wv(kt.id,kr.id),gr(!1),Se("")},children:[kt.name," (",kt.email,")"]},kt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Nt,{className:"font-semibold",children:"Name"}),e.jsx(Nt,{className:"font-semibold",children:"Email"}),e.jsx(Nt,{className:"font-semibold",children:"Status"}),e.jsx(Nt,{className:"font-semibold",children:"Role"}),e.jsx(Nt,{className:"w-[120px]"})]})}),e.jsx($n,{children:Kv(kr.id).length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:qr?"No matching members found":"No members in this brokerage"})}):Kv(kr.id).map(kt=>e.jsxs(Ds,{className:"hover:bg-muted/30",children:[e.jsx(dt,{className:"font-medium",children:kt.name}),e.jsx(dt,{className:"text-muted-foreground",children:kt.email}),e.jsx(dt,{children:kt.claimed?e.jsx(Ge,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Ge,{variant:"secondary",children:"Pending"})}),e.jsx(dt,{children:kt.roles.includes("brokerage_manager")?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Wu,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!kt.claimed&&e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>bi(kt.id),title:"Resend welcome email",children:e.jsx(Vs,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ju(kt.id),title:"Remove from brokerage",children:e.jsx(vr,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Ih(kt.id),disabled:a||kt.id===(t==null?void 0:t.id),title:kt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${kt.name}`,children:a?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(V4,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>no(kt.id,kt.name),title:"Delete user",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},kt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Im(kr.id).length," total member",Im(kr.id).length!==1?"s":""," •",Im(kr.id).filter(kt=>kt.roles.includes("brokerage_manager")).length," manager",Im(kr.id).filter(kt=>kt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(an,{children:e.jsx(G,{variant:"outline",onClick:am,children:"Close"})})]})})]}),e.jsx(ts,{value:"teams",children:e.jsx(ZJt,{})}),e.jsx(ts,{value:"trials",children:e.jsx(GJt,{})}),e.jsx(ts,{value:"celebrations",children:e.jsx(HJt,{})}),e.jsx(ts,{value:"deletions",children:e.jsx(WJt,{})})]})]}),e.jsx($ot,{open:ss,onOpenChange:ta,brokerages:h,onSuccess:ia}),xr&&e.jsx(Uot,{open:qs,onOpenChange:kt=>{Cs(kt),kt||Wr(null)},userId:xr.id,userName:xr.name}),e.jsx(XJt,{open:ve,onOpenChange:be,recipients:l.filter(kt=>ze.has(kt.id)).map(kt=>({id:kt.id,name:kt.name,email:kt.email}))})]})},JJt=()=>{const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState("");k.useEffect(()=>{v()},[]);const v=async()=>{const{data:I,error:D}=await V.from("invite_codes").select("*").order("created_at",{ascending:!1});D?(ue.error("Failed to load invite codes"),console.error(D)):t(I||[]),n(!1)},w=async I=>{if(I.preventDefault(),!l.trim()){ue.error("Please enter a code");return}i(!0);const{error:D}=await V.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:h?parseInt(h):null,trial_days:x?parseInt(x):null});D?D.code==="23505"?ue.error("This code already exists"):(ue.error("Failed to create invite code"),console.error(D)):(ue.success("Invite code created"),o(""),d(""),m(""),y(""),v()),i(!1)},b=async(I,D)=>{const{error:R}=await V.from("invite_codes").update({is_active:!D}).eq("id",I);R?ue.error("Failed to update code"):t(s.map($=>$.id===I?{...$,is_active:!D}:$))},N=async I=>{const{error:D}=await V.from("invite_codes").delete().eq("id",I);D?ue.error("Failed to delete code"):(ue.success("Code deleted"),t(s.filter(R=>R.id!==I)))},S="https://dashboard.relevelup.com",T=I=>{const D=`${S}/join?code=${I}`;navigator.clipboard.writeText(D),ue.success("Link copied to clipboard")},A=`${S}/join`;return e.jsx(ws,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Create New Code"}),e.jsxs(Nr,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(Pe,{children:e.jsxs("form",{onSubmit:w,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"code",children:"Code"}),e.jsx(Ne,{id:"code",placeholder:"WELCOME2024",value:l,onChange:I=>o(I.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(he,{htmlFor:"description",children:"Description (optional)"}),e.jsx(Ne,{id:"description",placeholder:"For marketing campaign",value:c,onChange:I=>d(I.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(Ne,{id:"maxUses",type:"number",placeholder:"Unlimited",value:h,onChange:I=>m(I.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(Ne,{id:"trialDays",type:"number",placeholder:"None",value:x,onChange:I=>y(I.target.value),className:"w-28"})]}),e.jsxs(G,{type:"submit",disabled:a,children:[a?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Active Codes"})}),e.jsx(Pe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Code"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{children:"Uses"}),e.jsx(Nt,{children:"Trial"}),e.jsx(Nt,{children:"Created"}),e.jsx(Nt,{children:"Active"}),e.jsx(Nt,{className:"w-24",children:"Actions"})]})}),e.jsx($n,{children:s.map(I=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-mono font-medium",children:I.code}),e.jsx(dt,{className:"text-muted-foreground",children:I.description||"—"}),e.jsxs(dt,{children:[I.uses_count,I.max_uses&&` / ${I.max_uses}`]}),e.jsx(dt,{children:I.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[I.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(dt,{className:"text-muted-foreground",children:_s(new Date(I.created_at),"MMM d, yyyy")}),e.jsx(dt,{children:e.jsx(_r,{checked:I.is_active,onCheckedChange:()=>b(I.id,I.is_active)})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>T(I.code),title:"Copy invite link",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>N(I.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},I.id))})]})})]})]})})},_B=async s=>{try{const{data:t,error:r}=await V.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return r?(console.error("Error checking notification setting:",r),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},XI=async s=>{try{const{data:t,error:r}=await V.functions.invoke("send-push-notification",{body:s});return r?(console.error("Error sending notification:",r),{success:!1,error:r}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},ees=async(s,t)=>await _B("new_templates")?XI({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}),tes=async(s,t)=>XI({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),ses=async(s,t)=>await _B("new_events")?XI({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),res=async(s,t)=>await _B("new_toolbox")?XI({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),A2e=async(s,t)=>await _B("new_social_swag")?XI({title:"New Social Swag",body:`New social swag available: ${s}`,url:`/social-swag/${t}`}):(console.log("New social swag notifications are disabled"),{success:!1,skipped:!0}),nes=async(s,t)=>await _B("new_newsletters")?XI({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),p$={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 aes(){const s=br(),t=Xt(),[r,n]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState(p$),[c,d]=k.useState(null),[h,m]=k.useState(null),[x,y]=k.useState(!1),v=k.useRef(null),[w,b]=k.useState(!1),[N,S]=k.useState(null),[T,A]=k.useState(!1),[I,D]=k.useState(null),[R,$]=k.useState(null),[F,z]=k.useState(!0),[Q,K]=k.useState(""),{data:X,isLoading:Z}=mt({queryKey:["admin-events"],queryFn:async()=>{const{data:_e,error:Re}=await V.from("events").select("*").order("event_date",{ascending:!0});if(Re)throw Re;return _e}}),{data:re}=mt({queryKey:["event-registrations-count"],queryFn:async()=>{let _e=[],Re=0;const tt=1e3;for(;;){const{data:Ze,error:lt}=await V.from("event_registrations").select("event_id").range(Re,Re+tt-1);if(lt)throw lt;if(!Ze||Ze.length===0||(_e=_e.concat(Ze),Ze.length{Ke[Ze.event_id]=(Ke[Ze.event_id]||0)+1}),Ke}}),{data:le,isLoading:oe}=mt({queryKey:["event-registrations-details",N==null?void 0:N.id],queryFn:async()=>{if(!N)return[];const{data:_e,error:Re}=await V.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",N.id).order("registered_at",{ascending:!1});if(Re)throw Re;if(!_e||_e.length===0)return[];const tt=_e.map(lt=>lt.user_id).filter(Boolean);let Ke=[];if(tt.length>0){const{data:lt,error:xt}=await V.from("profiles").select("id, name, email").in("id",tt);if(xt)throw xt;Ke=lt||[]}const Ze=new Map((Ke==null?void 0:Ke.map(lt=>[lt.id,lt]))||[]);return _e.map(lt=>({...lt,profiles:lt.user_id&&Ze.get(lt.user_id)||null}))},enabled:!!N}),{data:ne,isLoading:ie}=mt({queryKey:["event-attendees-details",N==null?void 0:N.id],queryFn:async()=>{if(!N)return[];const{data:_e,error:Re}=await V.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",N.id).order("created_at",{ascending:!1});if(Re)throw Re;if(!_e||_e.length===0)return[];const tt=_e.map(Xe=>Xe.user_id).filter(Boolean);let Ke=[];if(tt.length>0){const{data:Xe,error:Je}=await V.from("profiles").select("id, name, email").in("id",tt);if(Je)throw Je;Ke=Xe||[]}const{data:Ze}=await V.from("agent_points").select("user_id").eq("event_id",N.id),lt=new Set((Ze==null?void 0:Ze.map(Xe=>Xe.user_id))||[]),xt=new Map((Ke==null?void 0:Ke.map(Xe=>[Xe.id,Xe]))||[]);return _e.map(Xe=>({...Xe,profiles:Xe.user_id&&xt.get(Xe.user_id)||null,points_awarded:Xe.user_id?lt.has(Xe.user_id):!1}))},enabled:!!N}),ye=_e=>{S(_e),b(!0)},ce=Ct({mutationFn:async _e=>{const{data:{session:Re}}=await V.auth.getSession();if(!Re)throw new Error("Not authenticated");const tt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Re.access_token}`},body:JSON.stringify({event_id:_e})}),Ke=await tt.json();if(!tt.ok)throw new Error(Ke.error||"Failed to sync");return Ke},onSuccess:_e=>{t.invalidateQueries({queryKey:["event-registrations-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ue.success(_e.message)},onError:_e=>{ue.error("Failed to sync: "+_e.message)}}),ve=Ct({mutationFn:async _e=>{const{data:{session:Re}}=await V.auth.getSession();if(!Re)throw new Error("Not authenticated");const tt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Re.access_token}`},body:JSON.stringify({event_id:_e})}),Ke=await tt.json();if(!tt.ok)throw new Error(Ke.error||"Failed to sync attendees");return Ke},onSuccess:_e=>{t.invalidateQueries({queryKey:["event-attendees-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),_e!=null&&_e.message?ue.success(_e.message):ue.success(`Synced ${_e.synced||0} attendees. ${_e.points_awarded||0} points awarded!`)},onError:_e=>{ue.error("Failed to sync attendees: "+_e.message)}}),be=Ct({mutationFn:async()=>{const{data:_e,error:Re}=await V.functions.invoke("zoom-retry-registrations",{body:{}});if(Re)throw Re;return _e},onSuccess:_e=>{t.invalidateQueries({queryKey:["event-registrations-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ue.success(`Retry complete: ${(_e==null?void 0:_e.successCount)??0} fixed, ${(_e==null?void 0:_e.failCount)??0} still failing, ${(_e==null?void 0:_e.rateLimitedCount)??0} rate-limited`)},onError:_e=>{ue.error("Retry failed: "+_e.message)}}),Ue=Ct({mutationFn:async({eventId:_e,testMode:Re})=>{const{data:{session:tt}}=await V.auth.getSession();if(!tt)throw new Error("Not authenticated");const Ke=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${tt.access_token}`},body:JSON.stringify({event_id:_e,test_mode:Re})}),Ze=await Ke.json();if(!Ke.ok)throw new Error(Ze.error||"Failed to send reminders");return Ze},onSuccess:_e=>{_e.test?ue.success(_e.message||"Test email sent!"):ue.success(_e.message||`Reminder emails sent to ${_e.sent} registrants!`)},onError:_e=>{ue.error("Failed to send reminders: "+_e.message)}}),{data:Be}=mt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let _e=[],Re=0;const tt=1e3;for(;;){const{data:Ke,error:Ze}=await V.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(Re,Re+tt-1);if(Ze)throw Ze;if(!Ke||Ke.length===0||(_e=[..._e,...Ke],Ke.length{const{error:Ze}=await V.from("event_attendees").update({user_id:Re}).eq("id",_e);if(Ze)throw Ze;if(Ke&&tt){const{error:xt}=await V.from("zoom_email_aliases").upsert({user_id:Re,zoom_email:tt.toLowerCase()},{onConflict:"zoom_email"});xt&&console.error("Failed to save alias:",xt)}const lt=N==null?void 0:N.id;if(lt){const{data:xt}=await V.from("user_roles").select("id").eq("user_id",Re).eq("role","admin").single();if(!xt){const{data:Xe}=await V.from("agent_points").select("id").eq("user_id",Re).eq("event_id",lt).single();Xe||(await V.rpc("award_attendance_points",{p_user_id:Re,p_event_id:lt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await V.rpc("check_and_award_badges",{p_user_id:Re}))}}return{userId:Re,zoomEmail:tt,shouldSaveAlias:Ke}},onSuccess:_e=>{t.invalidateQueries({queryKey:["event-attendees-details",N==null?void 0:N.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let Re="Attendee linked and points awarded!";_e.shouldSaveAlias&&_e.zoomEmail&&(Re+=` Email "${_e.zoomEmail}" will be auto-matched in the future.`),ue.success(Re),A(!1),D(null),$(null),K("")},onError:_e=>{ue.error("Failed to link attendee: "+_e.message)}}),Ae=_e=>{D(_e),$(null),z(!0),K(""),A(!0)},He=()=>{!I||!R||De.mutate({attendeeId:I.id,userId:R,zoomEmail:I.zoom_email,shouldSaveAlias:F})},Le=(Be==null?void 0:Be.filter(_e=>{var tt,Ke;if(!Q)return!0;const Re=Q.toLowerCase();return((tt=_e.name)==null?void 0:tt.toLowerCase().includes(Re))||((Ke=_e.email)==null?void 0:Ke.toLowerCase().includes(Re))}))||[],Ie=async _e=>{const Re=_e.name.split(".").pop(),Ke=`${`${crypto.randomUUID()}.${Re}`}`,{error:Ze}=await V.storage.from("event-images").upload(Ke,_e);if(Ze)throw Ze;const{data:{publicUrl:lt}}=V.storage.from("event-images").getPublicUrl(Ke);return lt},Te=_e=>{var tt;const Re=(tt=_e.target.files)==null?void 0:tt[0];if(Re){if(Re.size>5*1024*1024){ue.error("Image must be less than 5MB");return}d(Re),m(URL.createObjectURL(Re))}},xe=()=>{d(null),m(null),o({...l,image_url:""}),v.current&&(v.current.value="")},et=Ct({mutationFn:async _e=>{y(!0);let Re=_e.image_url;c&&(Re=await Ie(c)||"");const tt=new Date(_e.event_date),[Ke,Ze]=_e.event_time.split(":");tt.setHours(parseInt(Ke),parseInt(Ze));const lt=[new Date(tt)];if(_e.is_recurring&&_e.recurrence_end_date){let jt=new Date(tt);for(;_e.recurrence_pattern==="weekly"?jt=e4(jt,1):_e.recurrence_pattern==="biweekly"?jt=e4(jt,2):jt=gf(jt,1),!(jt>_e.recurrence_end_date);)lt.push(new Date(jt))}const xt=lt.map(jt=>({title:_e.title,description:_e.description||null,image_url:Re||null,video_url:_e.video_url||null,event_date:jt.toISOString(),zoom_link:_e.zoom_link,zoom_meeting_id:_e.zoom_meeting_id||null,capacity:_e.capacity?parseInt(_e.capacity):null,is_published:_e.is_published})),{data:Xe,error:Je}=await V.from("events").insert(xt).select();if(Je)throw Je;return Xe&&Xe.length>0&&ses(_e.title,Xe[0].id),lt.length},onSuccess:_e=>{t.invalidateQueries({queryKey:["admin-events"]}),ue.success(_e>1?`${_e} recurring events created successfully`:"Event created successfully"),n(!1),o(p$),d(null),m(null),y(!1)},onError:_e=>{ue.error("Failed to create event: "+_e.message),y(!1)}}),fe=Ct({mutationFn:async({id:_e,data:Re})=>{y(!0);let tt=Re.image_url;c&&(tt=await Ie(c)||"");const Ke=new Date(Re.event_date),[Ze,lt]=Re.event_time.split(":");Ke.setHours(parseInt(Ze),parseInt(lt));const{error:xt}=await V.from("events").update({title:Re.title,description:Re.description||null,image_url:tt||null,video_url:Re.video_url||null,event_date:Ke.toISOString(),zoom_link:Re.zoom_link,zoom_meeting_id:Re.zoom_meeting_id||null,capacity:Re.capacity?parseInt(Re.capacity):null,is_published:Re.is_published}).eq("id",_e);if(xt)throw xt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ue.success("Event updated successfully"),n(!1),i(null),o(p$),d(null),m(null),y(!1)},onError:_e=>{ue.error("Failed to update event: "+_e.message),y(!1)}}),it=Ct({mutationFn:async _e=>{const{error:Re}=await V.from("events").delete().eq("id",_e);if(Re)throw Re},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ue.success("Event deleted successfully")},onError:_e=>{ue.error("Failed to delete event: "+_e.message)}}),Oe=_e=>{var tt;const Re=new Date(_e.event_date);i(_e),o({title:_e.title,description:_e.description||"",image_url:_e.image_url||"",video_url:_e.video_url||"",event_date:Re,event_time:_s(Re,"HH:mm"),zoom_link:_e.zoom_link,zoom_meeting_id:_e.zoom_meeting_id||"",capacity:((tt=_e.capacity)==null?void 0:tt.toString())||"",is_published:_e.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),m(_e.image_url||null),d(null),n(!0)},Ye=_e=>{if(_e.preventDefault(),!l.event_date){ue.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ue.error("Please select an end date for recurring events");return}a?fe.mutate({id:a.id,data:l}):et.mutate(l)},We=()=>{n(!1),i(null),o(p$),d(null),m(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>s("/dashboard"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Event Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage upcoming events"})]})]}),e.jsxs(ke,{className:"mb-6",children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"All Events"}),e.jsxs(fs,{open:r,onOpenChange:_e=>!_e&&We(),children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{onClick:()=>n(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(ms,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:Ye,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:l.title,onChange:_e=>o({...l,title:_e.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:l.description,onChange:_e=>o({...l,description:_e}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Event Image"}),e.jsx("input",{type:"file",ref:v,accept:"image/*",onChange:Te,className:"hidden"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:xe,children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs(G,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var _e;return(_e=v.current)==null?void 0:_e.click()},children:[e.jsx(da,{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(he,{children:"Date *"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),l.event_date?_s(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:l.event_date,onSelect:_e=>o({...l,event_date:_e}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"time",children:"Time *"}),e.jsx(Ne,{id:"time",type:"time",value:l.event_time,onChange:_e=>o({...l,event_time:_e.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(Ne,{id:"zoom_link",value:l.zoom_link,onChange:_e=>o({...l,zoom_link:_e.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(Ne,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:_e=>o({...l,zoom_meeting_id:_e.target.value}),placeholder:"e.g., 1234567890 (find in Zoom dashboard)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional: Enter the numeric meeting ID for automatic Zoom registration"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(Ne,{id:"video_url",value:l.video_url,onChange:_e=>o({...l,video_url:_e.target.value}),placeholder:"YouTube, Vimeo, or Bunny.net embed URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a preview/promo video for this event"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(Ne,{id:"capacity",type:"number",value:l.capacity,onChange:_e=>o({...l,capacity:_e.target.value}),placeholder:"Leave empty for unlimited",min:"1"})]}),!a&&e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(RR,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(_r,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:_e=>o({...l,is_recurring:_e})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Frequency"}),e.jsxs(Is,{value:l.recurrence_pattern,onValueChange:_e=>o({...l,recurrence_pattern:_e}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"weekly",children:"Weekly"}),e.jsx(ct,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(ct,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Repeat Until"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?_s(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:l.recurrence_end_date,onSelect:_e=>o({...l,recurrence_end_date:_e}),disabled:_e=>_e<(l.event_date||new Date),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),l.event_date&&l.recurrence_end_date&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This will create ",(()=>{let _e=1,Re=new Date(l.event_date);for(;Re=l.recurrence_pattern==="weekly"?e4(Re,1):l.recurrence_pattern==="biweekly"?e4(Re,2):gf(Re,1),!(Re>l.recurrence_end_date);)_e++;return _e})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{htmlFor:"is_published",children:"Published"}),e.jsx(_r,{id:"is_published",checked:l.is_published,onCheckedChange:_e=>o({...l,is_published:_e})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:We,className:"flex-1",children:"Cancel"}),e.jsx(G,{type:"submit",className:"flex-1",disabled:et.isPending||fe.isPending||x,children:x?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Pe,{children:Z?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(X==null?void 0:X.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Date & Time"}),e.jsx(Nt,{children:"Registrations"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:X==null?void 0:X.map(_e=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:_e.title}),e.jsx(dt,{children:_s(new Date(_e.event_date),"PPP p")}),e.jsx(dt,{children:e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>ye(_e),children:[e.jsx(pr,{className:"h-4 w-4"}),(re==null?void 0:re[_e.id])||0,_e.capacity&&` / ${_e.capacity}`]})}),e.jsx(dt,{children:e.jsx("span",{className:It("px-2 py-1 rounded-full text-xs font-medium",_e.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:_e.is_published?"Published":"Draft"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>window.open(_e.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Qr,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Oe(_e),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&it.mutate(_e.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},_e.id))})]})})]}),e.jsx(fs,{open:w,onOpenChange:b,children:e.jsxs(ms,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),N==null?void 0:N.title]}),e.jsx(Hr,{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(G,{variant:"ghost",size:"sm",onClick:()=>Ue.mutate({eventId:N.id,testMode:!0}),disabled:Ue.isPending,children:[e.jsx(Vs,{className:It("h-4 w-4 mr-2",Ue.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>Ue.mutate({eventId:N.id}),disabled:Ue.isPending||!(le!=null&&le.length),children:[e.jsx(Vs,{className:It("h-4 w-4 mr-2",Ue.isPending&&"animate-spin")}),Ue.isPending?"Sending...":"Send Reminder to All"]}),(N==null?void 0:N.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>ce.mutate(N.id),disabled:ce.isPending,children:[e.jsx(Mi,{className:It("h-4 w-4 mr-2",ce.isPending&&"animate-spin")}),ce.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>be.mutate(),disabled:be.isPending,children:[e.jsx(Mi,{className:It("h-4 w-4 mr-2",be.isPending&&"animate-spin")}),be.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(G,{variant:"default",size:"sm",onClick:()=>ve.mutate(N.id),disabled:ve.isPending,children:[e.jsx(Gi,{className:It("h-4 w-4 mr-2",ve.isPending&&"animate-spin")}),ve.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(On,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Rn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"registrations",className:"gap-2",children:[e.jsx(pr,{className:"h-4 w-4"}),"Registrations (",(le==null?void 0:le.length)||0,")"]}),e.jsxs(Kt,{value:"attendees",className:"gap-2",children:[e.jsx(In,{className:"h-4 w-4"}),"Attendees (",(ne==null?void 0:ne.length)||0,")"]})]}),e.jsx(ts,{value:"registrations",className:"mt-4",children:oe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(le==null?void 0:le.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(N==null?void 0:N.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Registered"}),e.jsx(Nt,{children:"Status"})]})}),e.jsx($n,{children:le==null?void 0:le.map(_e=>{var Ze,lt;const Re=((Ze=_e.profiles)==null?void 0:Ze.name)||_e.zoom_name||"Unknown",tt=((lt=_e.profiles)==null?void 0:lt.email)||_e.zoom_email||null,Ke=!_e.user_id;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Re,Ke&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(dt,{children:tt?e.jsxs("a",{href:`mailto:${tt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"}),tt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(dt,{className:"text-muted-foreground text-sm",children:_s(new Date(_e.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(dt,{children:_e.zoom_join_url?e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Registered"}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},_e.id)})})]})}),e.jsx(ts,{value:"attendees",className:"mt-4",children:ie?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ne==null?void 0:ne.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(N==null?void 0:N.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:[(ne==null?void 0:ne.filter(_e=>!_e.user_id).length)>0&&e.jsxs("div",{className:"mb-6 p-4 border border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Oi,{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 (",ne==null?void 0:ne.filter(_e=>!_e.user_id).length,")"]})]}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300 mb-3",children:"These attendees couldn't be matched to a profile. Link them to award points."}),e.jsx("div",{className:"space-y-2",children:ne==null?void 0:ne.filter(_e=>!_e.user_id).map(_e=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background rounded border",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-sm",children:_e.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_e.zoom_email||"No email"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>Ae(_e),className:"gap-1",children:[e.jsx(tl,{className:"h-3 w-3"}),"Link to Profile"]})]},_e.id))})]}),e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Duration"}),e.jsx(Nt,{children:"Points"})]})}),e.jsx($n,{children:ne==null?void 0:ne.filter(_e=>_e.user_id).map(_e=>{var Ke,Ze;const Re=((Ke=_e.profiles)==null?void 0:Ke.name)||_e.zoom_name||"Unknown",tt=((Ze=_e.profiles)==null?void 0:Ze.email)||_e.zoom_email||null;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Re,_e.manually_added&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:"Manual"})]})}),e.jsx(dt,{children:tt?e.jsxs("a",{href:`mailto:${tt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"}),tt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(dt,{children:_e.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(fn,{className:"h-3 w-3"}),_e.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(dt,{children:_e.points_awarded?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:[e.jsx(Gi,{className:"h-3 w-3"}),"+10 pts"]}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},_e.id)})})]})]})})]})]})}),e.jsx(fs,{open:T,onOpenChange:A,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Hr,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),I&&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:I.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:Q,onChange:_e=>K(_e.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Le.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:Le.slice(0,20).map(_e=>e.jsxs("button",{type:"button",onClick:()=>$(_e.id),className:It("w-full p-3 text-left hover:bg-muted/50 transition-colors",R===_e.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:_e.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_e.email})]},_e.id))})}),I.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Si,{id:"save-alias",checked:F,onCheckedChange:_e=>z(_e)}),e.jsx("label",{htmlFor:"save-alias",className:"text-sm text-muted-foreground cursor-pointer",children:"Remember this email for future auto-matching"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(G,{onClick:He,disabled:!R||De.isPending,children:De.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}function ies({selectedKitIds:s,onChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=mt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:m,error:x}=await V.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(x)throw x;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},h=m=>{t(s.filter(x=>x!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Il,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(vr,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(To,{open:a,onOpenChange:i,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Il,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(_o,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(yn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search toolkits...",value:r,onChange:m=>n(m.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:r?"No toolkits found":"All toolkits selected"}):c.map(m=>e.jsxs("button",{type:"button",onClick:()=>{d(m.id),n("")},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:[m.featured_image_url?e.jsx("img",{src:m.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(Il,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link toolkits that agents can download alongside this template."})]})}const oes=()=>{const{user:s}=js(),{toast:t}=Ma(),r=Xt(),[n,a]=Ac(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.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:""}),[m,x]=k.useState(null),[y,v]=k.useState(0),[w,b]=k.useState(!1),[N,S]=k.useState(null),[T,A]=k.useState(""),[I,D]=k.useState([]),[R,$]=k.useState(""),[F,z]=k.useState(""),[Q,K]=k.useState(!1),[X,Z]=k.useState(!1),{data:re=[]}=mt({queryKey:["template-categories"],queryFn:async()=>{const{data:Oe,error:Ye}=await V.from("template_categories").select("*").order("name");if(Ye)throw Ye;return Oe}}),{data:le=[]}=mt({queryKey:["template-types"],queryFn:async()=>{const{data:Oe,error:Ye}=await V.from("template_types").select("*").order("name");if(Ye)throw Ye;return Oe}}),{data:oe=[],isLoading:ne}=mt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Oe,error:Ye}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Ye)throw Ye;const{data:We,error:_e}=await V.from("template_links").select("*").order("sort_order");if(_e)throw _e;const{data:Re,error:tt}=await V.from("template_guides").select("*").order("sort_order");if(tt)throw tt;return Oe.map(Ze=>({...Ze,links:(We==null?void 0:We.filter(lt=>lt.template_id===Ze.id))||[],guides:(Re==null?void 0:Re.filter(lt=>lt.template_id===Ze.id))||[]}))}});k.useEffect(()=>{const Oe=n.get("edit");if(Oe&&oe.length>0){const Ye=oe.find(We=>We.id===Oe);Ye&&(Be(Ye),a({},{replace:!0}))}},[oe,n]);const ie=Ct({mutationFn:async Oe=>{const{data:Ye,error:We}=await V.from("template_categories").insert({name:Oe}).select().single();if(We)throw We;return Ye},onSuccess:Oe=>{r.invalidateQueries({queryKey:["template-categories"]}),h({...d,category_id:Oe.id}),$(""),K(!1),t({title:"Category added"})},onError:Oe=>{t({title:"Error adding category",description:Oe.message,variant:"destructive"})}}),ye=Ct({mutationFn:async Oe=>{const{data:Ye,error:We}=await V.from("template_types").insert({name:Oe}).select().single();if(We)throw We;return Ye},onSuccess:Oe=>{r.invalidateQueries({queryKey:["template-types"]}),h({...d,type_id:Oe.id}),z(""),Z(!1),t({title:"Type added"})},onError:Oe=>{t({title:"Error adding type",description:Oe.message,variant:"destructive"})}}),ce=Ct({mutationFn:async Oe=>{var tt;let Ye=Oe.existingImageUrl;if(Oe.image){const Ke=Oe.image.name.split(".").pop(),Ze=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ke}`,{error:lt}=await V.storage.from("template-previews").upload(Ze,Oe.image);if(lt)throw lt;const{data:xt}=V.storage.from("template-previews").getPublicUrl(Ze);Ye=xt.publicUrl}const We={name:Oe.template.name,description:Oe.template.description||null,category_id:Oe.template.category_id||null,type_id:Oe.template.type_id||null,preview_image_url:Ye,video_url:Oe.videoUrl||null,publish_date:Oe.template.publish_date?new Date(Oe.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let _e=Oe.templateId;if(_e){const{error:Ke}=await V.from("canva_templates").update(We).eq("id",_e);if(Ke)throw Ke;const{error:Ze}=await V.from("template_links").delete().eq("template_id",_e);if(Ze)throw Ze;const lt=((tt=Oe.existingGuides)==null?void 0:tt.map(Je=>Je.id).filter(Boolean))||[],xt=Oe.template.guides.map(Je=>Je.id).filter(Boolean),Xe=lt.filter(Je=>!xt.includes(Je));Xe.length>0&&await V.from("template_guides").delete().in("id",Xe)}else{const{data:Ke,error:Ze}=await V.from("canva_templates").insert(We).select().single();if(Ze)throw Ze;_e=Ke.id,ees(Oe.template.name,Ke.id)}const Re=Oe.template.links.filter(Ke=>Ke.title.trim()&&Ke.canva_share_link.trim());if(Re.length>0){const Ke=Re.map((lt,xt)=>({template_id:_e,title:lt.title.trim(),canva_share_link:lt.canva_share_link.trim(),sort_order:xt})),{error:Ze}=await V.from("template_links").insert(Ke);if(Ze)throw Ze}for(let Ke=0;Ke0)){const{error:Ke}=await V.from("resource_kit_templates").insert(Oe.linkedKitIds.map(Ze=>({template_id:_e,kit_id:Ze})));if(Ke)throw Ke}},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),Ue(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Oe=>{t({title:"Error saving template",description:Oe.message,variant:"destructive"})}}),ve=Ct({mutationFn:async Oe=>{const{error:Ye}=await V.from("canva_templates").delete().eq("id",Oe);if(Ye)throw Ye},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Oe=>{t({title:"Error deleting template",description:Oe.message,variant:"destructive"})}}),be=Ct({mutationFn:async({id:Oe,is_featured:Ye})=>{const{error:We}=await V.from("canva_templates").update({is_featured:Ye}).eq("id",Oe);if(We)throw We},onSuccess:()=>{r.invalidateQueries({queryKey:["canva-templates-admin"]}),r.invalidateQueries({queryKey:["canva-templates"]})},onError:Oe=>{t({title:"Error updating featured",description:Oe.message,variant:"destructive"})}}),Ue=()=>{h({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:""}),S(null),A(""),c(null),K(!1),Z(!1),$(""),z(""),x(null),v(0),b(!1),D([])},Be=async Oe=>{var We;c(Oe),h({name:Oe.name,description:Oe.description||"",category_id:Oe.category_id||"",type_id:Oe.type_id||"",publish_date:Oe.publish_date?new Date(Oe.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Oe.links&&Oe.links.length>0?Oe.links.map(_e=>({id:_e.id,title:_e.title,canva_share_link:_e.canva_share_link,sort_order:_e.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((We=Oe.guides)==null?void 0:We.map(_e=>({id:_e.id,name:_e.name,file_url:_e.file_url,file_type:_e.file_type,file_size:_e.file_size,sort_order:_e.sort_order})))||[],video_url:Oe.video_url||""}),A(Oe.preview_image_url||""),x(null);const{data:Ye}=await V.from("resource_kit_templates").select("kit_id").eq("template_id",Oe.id);D((Ye||[]).map(_e=>_e.kit_id)),l(!0)},De=Oe=>{var We;const Ye=(We=Oe.target.files)==null?void 0:We[0];Ye&&(S(Ye),A(URL.createObjectURL(Ye)))},Ae=()=>{h({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},He=Oe=>{if(d.links.length<=1)return;const Ye=d.links.filter((We,_e)=>_e!==Oe);h({...d,links:Ye})},Le=(Oe,Ye,We)=>{const _e=[...d.links];_e[Oe]={..._e[Oe],[Ye]:We},h({...d,links:_e})},Ie=Oe=>{const Ye=Oe.target.files;if(!Ye)return;const We=Array.from(Ye).map((_e,Re)=>({name:_e.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:_e.type,file_size:_e.size,sort_order:d.guides.length+Re,file:_e}));h({...d,guides:[...d.guides,...We]}),Oe.target.value=""},Te=Oe=>{const Ye=d.guides.filter((We,_e)=>_e!==Oe);h({...d,guides:Ye})},xe=(Oe,Ye)=>{const We=[...d.guides];We[Oe]={...We[Oe],name:Ye},h({...d,guides:We})},et=async()=>{if(!m)return null;b(!0),v(0);try{const{data:Oe,error:Ye}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||m.name}});if(Ye)throw new Error(Ye.message);const{videoId:We,libraryId:_e}=Oe,{data:Re,error:tt}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:We}});if(tt)throw new Error(tt.message);const Ke=new XMLHttpRequest;return await new Promise((lt,xt)=>{Ke.upload.addEventListener("progress",Xe=>{if(Xe.lengthComputable){const Je=Math.round(Xe.loaded/Xe.total*100);v(Je)}}),Ke.addEventListener("load",()=>{Ke.status>=200&&Ke.status<300?lt():xt(new Error(`Upload failed with status ${Ke.status}`))}),Ke.addEventListener("error",()=>xt(new Error("Upload failed"))),Ke.open("PUT",Re.uploadUrl),Ke.setRequestHeader("AccessKey",Re.apiKey),Ke.send(m)}),`https://player.mediadelivery.net/embed/${_e}/${We}`}catch(Oe){return console.error("Bunny upload error:",Oe),t({title:"Video upload failed",description:Oe instanceof Error?Oe.message:"Unknown error",variant:"destructive"}),null}finally{b(!1)}},fe=Oe=>{var We;const Ye=(We=Oe.target.files)==null?void 0:We[0];Ye&&x(Ye),Oe.target.value=""},it=async Oe=>{if(Oe.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(_e=>_e.title.trim()&&_e.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let We=d.video_url;if(m){const _e=await et();if(!_e)return;We=_e}ce.mutate({template:d,image:N,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:We,linkedKitIds:I})};return e.jsx(ws,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.length})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:re.length})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:le.length})})]})]}),e.jsxs(fs,{open:i,onOpenChange:Oe=>{l(Oe),Oe||Ue()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{htmlFor:"name",children:"Name *"}),e.jsx(Ne,{id:"name",value:d.name,onChange:Oe=>h({...d,name:Oe.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:d.description,onChange:Oe=>h({...d,description:Oe}),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(he,{children:"Canva Links *"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:Ae,className:"gap-1",children:[e.jsx($s,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Oe,Ye)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ne,{value:Oe.title,onChange:We=>Le(Ye,"title",We.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(Ne,{value:Oe.canva_share_link,onChange:We=>Le(Ye,"canva_share_link",We.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>He(Ye),children:e.jsx(vr,{className:"h-4 w-4"})})]},Ye))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Category"}),Q?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:R,onChange:Oe=>$(Oe.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:()=>R.trim()&&ie.mutate(R.trim()),disabled:ie.isPending,children:"Add"}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>{K(!1),$("")},children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{value:d.category_id,onValueChange:Oe=>h({...d,category_id:Oe}),children:[e.jsx(As,{className:"flex-1",children:e.jsx(Ls,{placeholder:"Select category"})}),e.jsx(Ms,{children:re.map(Oe=>e.jsx(ct,{value:Oe.id,children:Oe.name},Oe.id))})]}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>K(!0),children:e.jsx($s,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Template Type"}),X?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:F,onChange:Oe=>z(Oe.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:()=>F.trim()&&ye.mutate(F.trim()),disabled:ye.isPending,children:"Add"}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Z(!1),z("")},children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{value:d.type_id,onValueChange:Oe=>h({...d,type_id:Oe}),children:[e.jsx(As,{className:"flex-1",children:e.jsx(Ls,{placeholder:"Select type"})}),e.jsx(Ms,{children:le.map(Oe=>e.jsx(ct,{value:Oe.id,children:Oe.name},Oe.id))})]}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>Z(!0),children:e.jsx($s,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:d.publish_date,onChange:Oe=>h({...d,publish_date:Oe.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(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[T?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:T,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(G,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{S(null),A("")},children:e.jsx(vr,{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(ml,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:De,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(he,{children:"Video (Optional)"}),d.video_url&&!m?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(Jr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>h({...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})})]}):w?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(es,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",y,"%"]})]}),e.jsx(ei,{value:y,className:"h-2"})]}):m?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(Jr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:m.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(m.size/1024/1024).toFixed(1)," MB"]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>x(null),children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(Ne,{type:"file",accept:"video/*",onChange:fe,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(Jr,{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(he,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(Ne,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Ie,className:"hidden"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Oe,Ye)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(ln,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(Ne,{value:Oe.name,onChange:We=>xe(Ye,We.target.value),placeholder:"Guide name",className:"flex-1"}),Oe.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Oe.file_size/1024).toFixed(0)," KB"]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Te(Ye),children:e.jsx(vr,{className:"h-4 w-4"})})]},Oe.id||Ye))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No guide files added. Upload PDFs to help agents understand how to use this template."})]}),e.jsx(ies,{selectedKitIds:I,onChange:D}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>{l(!1),Ue()},children:"Cancel"}),e.jsx(G,{type:"submit",disabled:ce.isPending,children:ce.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:ne?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):oe.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Preview"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Links"}),e.jsx(Nt,{children:"Category"}),e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:oe.map(Oe=>{var Ye,We,_e,Re,tt;return e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Oe.preview_image_url?e.jsx("img",{src:Oe.preview_image_url,alt:Oe.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ml,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(dt,{className:"font-medium",children:Oe.name}),e.jsx(dt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Ge,{variant:"secondary",children:[((Ye=Oe.links)==null?void 0:Ye.length)||0," link",(((We=Oe.links)==null?void 0:We.length)||0)!==1?"s":""]}),(((_e=Oe.guides)==null?void 0:_e.length)||0)>0&&e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),(Re=Oe.guides)==null?void 0:Re.length," guide",(((tt=Oe.guides)==null?void 0:tt.length)||0)!==1?"s":""]})]})}),e.jsx(dt,{children:Oe.category?e.jsx(Ge,{variant:"secondary",children:Oe.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(dt,{children:Oe.type?e.jsx(Ge,{variant:"outline",children:Oe.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(dt,{className:"text-muted-foreground",children:new Date(Oe.publish_date).toLocaleDateString()}),e.jsx(dt,{className:"text-center",children:e.jsx(G,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Oe.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>be.mutate({id:Oe.id,is_featured:!Oe.is_featured}),children:e.jsx(Xn,{className:`h-4 w-4 ${Oe.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{size:"icon",variant:"ghost",onClick:()=>Be(Oe),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&ve.mutate(Oe.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Oe.id)})})]})})})]})})};function Kot({selectedTemplateIds:s,onChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=mt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:m,error:x}=await V.from("canva_templates").select("id, name, preview_image_url").order("name");if(x)throw x;return m}}),o=l.filter(m=>s.includes(m.id)),c=l.filter(m=>!s.includes(m.id)&&m.name.toLowerCase().includes(r.toLowerCase())),d=m=>{t([...s,m])},h=m=>{t(s.filter(x=>x!==m))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(U4,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(m=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pr-1",children:[m.name,e.jsx("button",{type:"button",onClick:()=>h(m.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(vr,{className:"h-3 w-3"})})]},m.id))}),e.jsxs(To,{open:a,onOpenChange:i,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(U4,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(_o,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(yn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search templates...",value:r,onChange:m=>n(m.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:r?"No templates found":"All templates selected"}):c.map(m=>e.jsxs("button",{type:"button",onClick:()=>{d(m.id),n("")},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:[m.preview_image_url?e.jsx("img",{src:m.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(U4,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link templates that agents can use alongside this content."})]})}const les=[{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"}],ces=()=>{const{user:s}=js(),[t,r]=Ac(),{toast:n}=Ma(),a=Xt(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[m,x]=k.useState(null),[y,v]=k.useState(""),[w,b]=k.useState([]),[N,S]=k.useState([]),[T,A]=k.useState([]),[I,D]=k.useState([]),[R,$]=k.useState(""),[F,z]=k.useState(!1),[Q,K]=k.useState(null),[X,Z]=k.useState(0),[re,le]=k.useState(!1),[oe,ne]=k.useState(null),{data:ie=[]}=mt({queryKey:["academy-categories"],queryFn:async()=>{const{data:fe,error:it}=await V.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(it)throw it;return fe}}),{data:ye=[],isLoading:ce}=mt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:fe,error:it}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(it)throw it;const{data:Oe,error:Ye}=await V.from("academy_resources").select("*").order("sort_order");if(Ye)throw Ye;return fe.map(_e=>({..._e,resources:(Oe==null?void 0:Oe.filter(Re=>Re.video_id===_e.id))||[]}))}});k.useEffect(()=>{const fe=t.get("edit");if(fe&&ye.length>0){const it=ye.find(Oe=>Oe.id===fe);it&&(Ae(it),r({},{replace:!0}))}},[ye,t]);const ve=Ct({mutationFn:async fe=>{const{data:it,error:Oe}=await V.from("academy_categories").insert({name:fe,sort_order:ie.length}).select().single();if(Oe)throw Oe;return it},onSuccess:fe=>{a.invalidateQueries({queryKey:["academy-categories"]}),h({...d,category_id:fe.id}),$(""),z(!1),n({title:"Category added"})},onError:fe=>{n({title:"Error adding category",description:fe.message,variant:"destructive"})}}),be=Ct({mutationFn:async fe=>{let it=fe.existingThumbnailUrl;if(fe.thumbnail){const We=fe.thumbnail.name.split(".").pop(),_e=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${We}`,{error:Re}=await V.storage.from("academy-resources").upload(_e,fe.thumbnail);if(Re)throw Re;const{data:tt}=V.storage.from("academy-resources").getPublicUrl(_e);it=tt.publicUrl}const Oe={title:fe.video.title,description:fe.video.description||null,video_url:fe.video.video_url,video_type:fe.video.video_type,duration:fe.video.duration||null,thumbnail_url:it,category_id:fe.video.category_id||null,publish_date:fe.video.publish_date?new Date(fe.video.publish_date).toISOString():new Date().toISOString(),is_published:fe.video.is_published,created_by:s==null?void 0:s.id};let Ye=fe.videoId;if(Ye){const{error:We}=await V.from("academy_videos").update(Oe).eq("id",Ye);if(We)throw We}else{const{data:We,error:_e}=await V.from("academy_videos").insert(Oe).select().single();if(_e)throw _e;Ye=We.id,tes(fe.video.title,We.id)}if(fe.resourcesToDelete.length>0){const{error:We}=await V.from("academy_resources").delete().in("id",fe.resourcesToDelete);if(We)throw We}for(let We=0;We0){const{error:We}=await V.from("academy_video_templates").insert(I.map(_e=>({video_id:Ye,template_id:_e})));if(We)throw We}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),De(),l(!1),n({title:o?"Video updated":"Video created"})},onError:fe=>{n({title:"Error saving video",description:fe.message,variant:"destructive"})}}),Ue=Ct({mutationFn:async fe=>{const{error:it}=await V.from("academy_videos").delete().eq("id",fe);if(it)throw it},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),n({title:"Video deleted"})},onError:fe=>{n({title:"Error deleting video",description:fe.message,variant:"destructive"})}}),Be=Ct({mutationFn:async({id:fe,is_published:it})=>{const{error:Oe}=await V.from("academy_videos").update({is_published:it}).eq("id",fe);if(Oe)throw Oe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:fe=>{n({title:"Error updating video",description:fe.message,variant:"destructive"})}}),De=()=>{h({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),x(null),v(""),b([]),S([]),A([]),c(null),D([]),$(""),K(null),Z(0),le(!1),ne(null)},Ae=async fe=>{c(fe),h({title:fe.title,description:fe.description||"",video_url:fe.video_url,video_type:fe.video_type,duration:fe.duration||"",category_id:fe.category_id||"",publish_date:fe.publish_date?new Date(fe.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:fe.is_published}),v(fe.thumbnail_url||""),S(fe.resources||[]),b([]),A([]);const{data:it}=await V.from("academy_video_templates").select("template_id").eq("video_id",fe.id);D((it||[]).map(Oe=>Oe.template_id)),l(!0)},He=fe=>{var Oe;const it=(Oe=fe.target.files)==null?void 0:Oe[0];it&&(x(it),v(URL.createObjectURL(it)))},Le=fe=>{const it=fe.target.files;if(it){const Oe=Array.from(it).map(Ye=>({file:Ye,title:Ye.name.replace(/\.[^/.]+$/,"")}));b([...w,...Oe])}fe.target.value=""},Ie=fe=>{b(w.filter((it,Oe)=>Oe!==fe))},Te=fe=>{A([...T,fe]),S(N.filter(it=>it.id!==fe))},xe=async()=>{if(!Q)return null;le(!0),Z(0);try{const{data:fe,error:it}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||Q.name}});if(it)throw new Error(it.message);const{videoId:Oe,libraryId:Ye}=fe;ne(Oe);const{data:We,error:_e}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Oe}});if(_e)throw new Error(_e.message);const Re=new XMLHttpRequest;return await new Promise((Ke,Ze)=>{Re.upload.addEventListener("progress",lt=>{if(lt.lengthComputable){const xt=Math.round(lt.loaded/lt.total*100);Z(xt)}}),Re.addEventListener("load",()=>{Re.status>=200&&Re.status<300?Ke():Ze(new Error(`Upload failed with status ${Re.status}`))}),Re.addEventListener("error",()=>Ze(new Error("Upload failed"))),Re.open("PUT",We.uploadUrl),Re.setRequestHeader("AccessKey",We.apiKey),Re.send(Q)}),`https://player.mediadelivery.net/embed/${Ye}/${Oe}`}catch(fe){return console.error("Bunny upload error:",fe),n({title:"Video upload failed",description:fe instanceof Error?fe.message:"Unknown error",variant:"destructive"}),null}finally{le(!1)}},et=async fe=>{if(fe.preventDefault(),!d.title.trim()){n({title:"Please enter a video title",variant:"destructive"});return}let it=d.video_url;if(d.video_type==="bunny_stream"&&Q&&!o){const Oe=await xe();if(!Oe)return;it=Oe}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){n({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!Q&&!d.video_url&&!o){n({title:"Please select a video file to upload",variant:"destructive"});return}be.mutate({video:{...d,video_url:it},thumbnail:m,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:w,resourcesToDelete:T})};return e.jsx(ws,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{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 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ye.length})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ye.filter(fe=>fe.is_published).length})})]})]}),e.jsxs(fs,{open:i,onOpenChange:fe=>{l(fe),fe||De()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:et,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:d.title,onChange:fe=>h({...d,title:fe.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:d.description,onChange:fe=>h({...d,description:fe}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Video Type"}),e.jsxs(Is,{value:d.video_type,onValueChange:fe=>{h({...d,video_type:fe,video_url:""}),K(null)},disabled:re,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:les.map(fe=>e.jsx(ct,{value:fe.value,children:fe.label},fe.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(he,{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(Ne,{type:"file",accept:"video/*",onChange:fe=>{var Oe;const it=(Oe=fe.target.files)==null?void 0:Oe[0];it&&K(it)},disabled:re}),Q&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jr,{className:"h-4 w-4"}),Q.name," (",(Q.size/(1024*1024)).toFixed(1)," MB)"]}),re&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(ei,{value:X,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[X,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(Ne,{id:"video_url",value:d.video_url,onChange:fe=>h({...d,video_url:fe.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(he,{htmlFor:"duration",children:"Duration"}),e.jsx(Ne,{id:"duration",value:d.duration,onChange:fe=>h({...d,duration:fe.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:d.publish_date,onChange:fe=>h({...d,publish_date:fe.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Category"}),F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:R,onChange:fe=>$(fe.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:()=>R.trim()&&ve.mutate(R.trim()),disabled:ve.isPending,children:"Add"}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",onClick:()=>{z(!1),$("")},children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{value:d.category_id,onValueChange:fe=>h({...d,category_id:fe}),children:[e.jsx(As,{className:"flex-1",children:e.jsx(Ls,{placeholder:"Select category"})}),e.jsx(Ms,{children:ie.map(fe=>e.jsx(ct,{value:fe.id,children:fe.name},fe.id))})]}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!0),children:e.jsx($s,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[y&&e.jsx("img",{src:y,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:He,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(he,{children:"Resource Files"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Le,className:"hidden"})]})})]}),(N.length>0||w.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[N.map(fe=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:fe.title}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:fe.file_type}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>Te(fe.id),className:"text-destructive hover:text-destructive",children:e.jsx(vr,{className:"h-4 w-4"})})]},fe.id)),w.map((fe,it)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:fe.title,onChange:Oe=>{const Ye=[...w];Ye[it].title=Oe.target.value,b(Ye)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ie(it),className:"text-destructive hover:text-destructive",children:e.jsx(vr,{className:"h-4 w-4"})})]},it))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(Kot,{selectedTemplateIds:I,onChange:D}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"is_published",checked:d.is_published,onCheckedChange:fe=>h({...d,is_published:fe})}),e.jsx(he,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(an,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:re,children:"Cancel"}),e.jsx(G,{type:"submit",disabled:be.isPending||re,children:re?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):be.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:ce?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"})}):ye.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Jr,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Category"}),e.jsx(Nt,{children:"Duration"}),e.jsx(Nt,{children:"Resources"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx($n,{children:ye.map(fe=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[fe.thumbnail_url?e.jsx("img",{src:fe.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(Jr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:fe.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:fe.video_type.replace("_"," ")})]})]})}),e.jsx(dt,{children:fe.category?e.jsx(Ge,{variant:"outline",children:fe.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(dt,{children:fe.duration||"-"}),e.jsx(dt,{children:fe.resources&&fe.resources.length>0?e.jsxs(Ge,{variant:"secondary",children:[fe.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(dt,{children:new Date(fe.publish_date).toLocaleDateString()}),e.jsx(dt,{children:e.jsx(_r,{checked:fe.is_published,onCheckedChange:it=>Be.mutate({id:fe.id,is_published:it})})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Ae(fe),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Ue.mutate(fe.id),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},fe.id))})]})})})]})})};function des(){var be,Ue,Be;const s=Xt(),[t,r]=Ac(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,h]=k.useState(null),[m,x]=k.useState(""),[y,v]=k.useState([]),[w,b]=k.useState([]),[N,S]=k.useState([]),[T,A]=k.useState(null),{data:I,isLoading:D}=mt({queryKey:["resource-kits"],queryFn:async()=>{const{data:De,error:Ae}=await V.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ae)throw Ae;return De}}),{data:R}=mt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:De,error:Ae}=await V.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ae)throw Ae;return De}}),{data:$}=mt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:De,error:Ae}=await V.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ae)throw Ae;return De}});k.useEffect(()=>{const De=t.get("edit");if(De&&I&&I.length>0&&R&&$){const Ae=I.find(He=>He.id===De);Ae&&(z(Ae),r({},{replace:!0}))}},[I,R,$,t]);const F=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),h(null),x(""),v([]),b([]),S([]),l(null)},z=async De=>{l(De),c({name:De.name,description:De.description||"",publish_date:De.publish_date.split("T")[0],is_published:De.is_published}),x(De.featured_image_url||"");const Ae=(R==null?void 0:R.filter(Ie=>Ie.kit_id===De.id))||[];v(Ae.map(Ie=>({id:Ie.id,name:Ie.name,file_url:Ie.file_url,file_type:Ie.file_type,file_size:Ie.file_size,sort_order:Ie.sort_order})));const He=($==null?void 0:$.filter(Ie=>Ie.kit_id===De.id))||[];b(He.map(Ie=>({id:Ie.id,title:Ie.title,canva_share_link:Ie.canva_share_link,sort_order:Ie.sort_order})));const{data:Le}=await V.from("resource_kit_templates").select("template_id").eq("kit_id",De.id);S((Le||[]).map(Ie=>Ie.template_id)),a(!0)},Q=De=>{var He;const Ae=(He=De.target.files)==null?void 0:He[0];Ae&&(h(Ae),x(URL.createObjectURL(Ae)))},K=()=>{v([...y,{name:"",file_url:"",sort_order:y.length}])},X=De=>{v(y.filter((Ae,He)=>He!==De))},Z=(De,Ae,He)=>{const Le=[...y];Le[De]={...Le[De],[Ae]:He},v(Le)},re=()=>{b([...w,{title:"",canva_share_link:"",sort_order:w.length}])},le=De=>{b(w.filter((Ae,He)=>He!==De))},oe=(De,Ae,He)=>{const Le=[...w];Le[De]={...Le[De],[Ae]:He},b(Le)},ne=(De,Ae)=>{var Le;const He=(Le=Ae.target.files)==null?void 0:Le[0];if(He){const Ie=[...y],Te=He.name.replace(/\.[^/.]+$/,"");Ie[De]={...Ie[De],file:He,file_type:He.type,file_size:He.size,name:Ie[De].name||Te},v(Ie)}},ie=Ct({mutationFn:async()=>{let De=(i==null?void 0:i.featured_image_url)||null;if(d){const Te=d.name.split(".").pop(),xe=`${Date.now()}.${Te}`,{error:et}=await V.storage.from("resource-kits").upload(`featured/${xe}`,d);if(et)throw et;const{data:fe}=V.storage.from("resource-kits").getPublicUrl(`featured/${xe}`);De=fe.publicUrl}const Ae={name:o.name,description:o.description||null,featured_image_url:De,publish_date:o.publish_date,is_published:o.is_published};let He;const Le=!i,Ie=(i==null?void 0:i.is_published)||!1;if(i){const{error:Te}=await V.from("resource_kits").update(Ae).eq("id",i.id);if(Te)throw Te;He=i.id;const xe=(R==null?void 0:R.filter(We=>We.kit_id===i.id).map(We=>We.id))||[],et=y.filter(We=>We.id).map(We=>We.id),fe=xe.filter(We=>!et.includes(We));fe.length>0&&await V.from("resource_kit_files").delete().in("id",fe);const it=($==null?void 0:$.filter(We=>We.kit_id===i.id).map(We=>We.id))||[],Oe=w.filter(We=>We.id).map(We=>We.id),Ye=it.filter(We=>!Oe.includes(We));Ye.length>0&&await V.from("resource_kit_links").delete().in("id",Ye)}else{const{data:Te,error:xe}=await V.from("resource_kits").insert(Ae).select().single();if(xe)throw xe;He=Te.id}for(let Te=0;Te0){const{error:Te}=await V.from("resource_kit_templates").insert(N.map(xe=>({kit_id:He,template_id:xe})));if(Te)throw Te}return{kitId:He,kitName:o.name,isNewKit:Le,wasPublished:Ie,isPublished:o.is_published}},onSuccess:De=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ue.success(i?"Resource kit updated":"Resource kit created"),De.isPublished&&(De.isNewKit||!De.wasPublished)&&res(De.kitName,De.kitId),a(!1),F()},onError:De=>{ue.error("Failed to save resource kit: "+De.message)}}),ye=Ct({mutationFn:async De=>{const{error:Ae}=await V.from("resource_kits").delete().eq("id",De);if(Ae)throw Ae},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ue.success("Resource kit deleted")},onError:De=>{ue.error("Failed to delete: "+De.message)}}),ce=De=>{if(De.preventDefault(),!o.name){ue.error("Please enter a name");return}ie.mutate()},ve=De=>(R==null?void 0:R.filter(Ae=>Ae.kit_id===De).length)||0;return e.jsx(ws,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.filter(De=>De.is_published).length)||0})})]})]}),e.jsxs(G,{onClick:()=>{F(),a(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Files"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:D?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(I==null?void 0:I.length)===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):I==null?void 0:I.map(De=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[De.featured_image_url?e.jsx("img",{src:De.featured_image_url,alt:De.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(Il,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:De.name}),De.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:De.description})]})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),ve(De.id)]})}),e.jsx(dt,{children:_s(new Date(De.publish_date),"MMM d, yyyy")}),e.jsx(dt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${De.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:De.is_published?"Published":"Draft"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{const Ae=(R==null?void 0:R.filter(Le=>Le.kit_id===De.id))||[],He=($==null?void 0:$.filter(Le=>Le.kit_id===De.id))||[];A({...De,files:Ae,links:He})},children:e.jsx(bn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>z(De),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&ye.mutate(De.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},De.id))})]})})}),e.jsx(fs,{open:n,onOpenChange:a,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:ce,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[m?e.jsx("img",{src:m,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(Il,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:Q})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name *"}),e.jsx(Ne,{id:"name",value:o.name,onChange:De=>c({...o,name:De.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:o.description,onChange:De=>c({...o,description:De}),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(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:o.publish_date,onChange:De=>c({...o,publish_date:De.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(_r,{checked:o.is_published,onCheckedChange:De=>c({...o,is_published:De})}),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(he,{children:"Resource Files"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:K,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),y.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:y.map((De,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(G,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>X(Ae),children:e.jsx(vr,{className:"h-4 w-4"})})]}),e.jsx(Ne,{placeholder:"File name (e.g., Getting Started Guide)",value:De.name,onChange:He=>Z(Ae,"name",He.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"file",onChange:He=>ne(Ae,He),className:"flex-1"}),De.file_url&&!De.file&&e.jsx("a",{href:De.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),De.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(he,{children:"Canva Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:re,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),w.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:w.map((De,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(G,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>le(Ae),children:e.jsx(vr,{className:"h-4 w-4"})})]}),e.jsx(Ne,{placeholder:"Link title (e.g., Social Media Post Template)",value:De.title,onChange:He=>oe(Ae,"title",He.target.value)}),e.jsx(Ne,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:De.canva_share_link,onChange:He=>oe(Ae,"canva_share_link",He.target.value)})]},Ae))})]}),e.jsx(Kot,{selectedTemplateIds:N,onChange:S}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:ie.isPending,children:ie.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(fs,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsx(ys,{children:e.jsx(gs,{children:T==null?void 0:T.name})}),e.jsxs("div",{className:"space-y-4",children:[(T==null?void 0:T.featured_image_url)&&e.jsx("img",{src:T.featured_image_url,alt:T.name,className:"w-full h-48 object-cover rounded-lg"}),(T==null?void 0:T.description)&&e.jsx("p",{className:"text-muted-foreground",children:T.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((be=T==null?void 0:T.files)==null?void 0:be.length)||0,")"]}),((Ue=T==null?void 0:T.files)==null?void 0:Ue.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:(Be=T==null?void 0:T.files)==null?void 0:Be.map(De=>e.jsxs("a",{href:De.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(ln,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:De.name})]},De.id))})]}),(T==null?void 0:T.links)&&T.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",T.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:T.links.map(De=>e.jsxs("a",{href:De.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(po,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:De.title})]},De.id))})]})]})]})})]})})}const ues=()=>{const{user:s}=js(),{toast:t}=Ma(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,h]=k.useState(null),[m,x]=k.useState(""),{data:y=[],isLoading:v}=mt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:$,error:F}=await V.from("social_swag").select("*").order("publish_date",{ascending:!1});if(F)throw F;const{data:z,error:Q}=await V.from("social_swag_links").select("*").order("sort_order");if(Q)throw Q;return $.map(X=>({...X,links:(z==null?void 0:z.filter(Z=>Z.swag_id===X.id))||[]}))}}),w=Ct({mutationFn:async $=>{let F=$.existingImageUrl;if($.image){const re=$.image.name.split(".").pop(),le=`${Date.now()}-${Math.random().toString(36).substring(7)}.${re}`,{error:oe}=await V.storage.from("template-previews").upload(le,$.image);if(oe)throw oe;const{data:ne}=V.storage.from("template-previews").getPublicUrl(le);F=ne.publicUrl}const z={title:$.item.title,description:$.item.description||null,preview_image_url:F,publish_date:$.item.publish_date?new Date($.item.publish_date).toISOString():new Date().toISOString(),is_published:$.item.is_published,created_by:s==null?void 0:s.id};let Q=$.itemId;const K=!Q,X=(i==null?void 0:i.is_published)||!1;if(Q){const{error:re}=await V.from("social_swag").update(z).eq("id",Q);if(re)throw re;await V.from("social_swag_links").delete().eq("swag_id",Q)}else{const{data:re,error:le}=await V.from("social_swag").insert(z).select().single();if(le)throw le;Q=re.id}const Z=$.item.links.filter(re=>re.title.trim()&&re.canva_share_link.trim());if(Z.length>0){const re=Z.map((oe,ne)=>({swag_id:Q,title:oe.title.trim(),canva_share_link:oe.canva_share_link.trim(),sort_order:ne})),{error:le}=await V.from("social_swag_links").insert(re);if(le)throw le}return{itemId:Q,itemTitle:$.item.title,isNewItem:K,wasPublished:X,isPublished:$.item.is_published}},onSuccess:$=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),$.isPublished&&($.isNewItem||!$.wasPublished)&&A2e($.itemTitle,$.itemId),a(!1),N()},onError:$=>{t({title:"Error saving item",description:$.message,variant:"destructive"})}}),b=Ct({mutationFn:async $=>{const{error:F}=await V.from("social_swag").delete().eq("id",$);if(F)throw F},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-admin"]}),r.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:$=>{t({title:"Error deleting item",description:$.message,variant:"destructive"})}}),N=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),h(null),x(""),l(null)},S=$=>{l($),c({title:$.title,description:$.description||"",publish_date:$.publish_date?new Date($.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:$.is_published,links:$.links&&$.links.length>0?$.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}]}),x($.preview_image_url||""),a(!0)},T=$=>{var z;const F=(z=$.target.files)==null?void 0:z[0];F&&(h(F),x(URL.createObjectURL(F)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},I=$=>{if(o.links.length<=1)return;const F=o.links.filter((z,Q)=>Q!==$);c({...o,links:F})},D=($,F,z)=>{const Q=[...o.links];Q[$]={...Q[$],[F]:z},c({...o,links:Q})},R=$=>{if($.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}w.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(ws,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:y.length})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:y.filter($=>$.is_published).length})})]})]}),e.jsxs(fs,{open:n,onOpenChange:$=>{a($),$||N()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:R,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:o.title,onChange:$=>c({...o,title:$.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:o.description,onChange:$=>c({...o,description:$}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:o.publish_date,onChange:$=>c({...o,publish_date:$.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_r,{id:"is_published",checked:o.is_published,onCheckedChange:$=>c({...o,is_published:$})}),e.jsx(he,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{h(null),x("")},children:e.jsx(vr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(ml,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:T,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Canva Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map(($,F)=>e.jsx(ke,{children:e.jsxs(Pe,{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(G,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>I(F),children:e.jsx(vr,{className:"h-3 w-3"})})]}),e.jsx(Ne,{placeholder:"Link title (e.g., Instagram Post)",value:$.title,onChange:z=>D(F,"title",z.target.value)}),e.jsx(Ne,{placeholder:"Canva share link",value:$.canva_share_link,onChange:z=>D(F,"canva_share_link",z.target.value)})]})},F))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:w.isPending,children:w.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:v?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"})}):y.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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-16",children:"Preview"}),e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Links"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:y.map($=>{var F;return e.jsxs(Ds,{children:[e.jsx(dt,{children:$.preview_image_url?e.jsx("img",{src:$.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(ml,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(dt,{className:"font-medium",children:$.title}),e.jsxs(dt,{children:[((F=$.links)==null?void 0:F.length)||0," links"]}),e.jsx(dt,{children:new Date($.publish_date).toLocaleDateString()}),e.jsx(dt,{children:e.jsx(Ge,{variant:$.is_published?"default":"secondary",children:$.is_published?"Published":"Draft"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${$.id}`,"_blank"),children:e.jsx(bn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>S($),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&b.mutate($.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},$.id)})})]})})})]})})};function hes(){for(var s=arguments.length,t=new Array(s),r=0;rn=>{t.forEach(a=>a(n))},t)}const mpe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function QI(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function p5e(s){return"nodeType"in s}function ap(s){var t,r;return s?QI(s)?s:p5e(s)&&(t=(r=s.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function x5e(s){const{Document:t}=ap(s);return s instanceof t}function wB(s){return QI(s)?!1:s instanceof ap(s).HTMLElement}function Yot(s){return s instanceof ap(s).SVGElement}function JI(s){return s?QI(s)?s.document:p5e(s)?x5e(s)?s:wB(s)||Yot(s)?s.ownerDocument:document:document:document}const Sv=mpe?k.useLayoutEffect:k.useEffect;function g5e(s){const t=k.useRef(s);return Sv(()=>{t.current=s}),k.useCallback(function(){for(var r=arguments.length,n=new Array(r),a=0;a{s.current=setInterval(n,a)},[]),r=k.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,r]}function D8(s,t){t===void 0&&(t=[s]);const r=k.useRef(s);return Sv(()=>{r.current!==s&&(r.current=s)},t),r}function jB(s,t){const r=k.useRef();return k.useMemo(()=>{const n=s(r.current);return r.current=n,n},[...t])}function zue(s){const t=g5e(s),r=k.useRef(null),n=k.useCallback(a=>{a!==r.current&&(t==null||t(a,r.current)),r.current=a},[]);return[r,n]}function M2e(s){const t=k.useRef();return k.useEffect(()=>{t.current=s},[s]),t.current}let A1e={};function NB(s,t){return k.useMemo(()=>{if(t)return t;const r=A1e[s]==null?0:A1e[s]+1;return A1e[s]=r,s+"-"+r},[s,t])}function Zot(s){return function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const h=i[c];h!=null&&(i[c]=h+s*d)}return i},{...t})}}const UA=Zot(1),R8=Zot(-1);function fes(s){return"clientX"in s&&"clientY"in s}function y5e(s){if(!s)return!1;const{KeyboardEvent:t}=ap(s.target);return t&&s instanceof t}function pes(s){if(!s)return!1;const{TouchEvent:t}=ap(s.target);return t&&s instanceof t}function I2e(s){if(pes(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:r}=s.touches[0];return{x:t,y:r}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:r}=s.changedTouches[0];return{x:t,y:r}}}return fes(s)?{x:s.clientX,y:s.clientY}:null}const Oj=Object.freeze({Translate:{toString(s){if(!s)return;const{x:t,y:r}=s;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:t,scaleY:r}=s;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(s){if(s)return[Oj.Translate.toString(s),Oj.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:r,easing:n}=s;return t+" "+r+"ms "+n}}}),RBe="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function xes(s){return s.matches(RBe)?s:s.querySelector(RBe)}const ges={display:"none"};function yes(s){let{id:t,value:r}=s;return wt.createElement("div",{id:t,style:ges},r)}function ves(s){let{id:t,announcement:r,ariaLiveType:n="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 wt.createElement("div",{id:t,style:a,role:"status","aria-live":n,"aria-atomic":!0},r)}function bes(){const[s,t]=k.useState("");return{announce:k.useCallback(n=>{n!=null&&t(n)},[]),announcement:s}}const Xot=k.createContext(null);function _es(s){const t=k.useContext(Xot);k.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function wes(){const[s]=k.useState(()=>new Set),t=k.useCallback(n=>(s.add(n),()=>s.delete(n)),[s]);return[k.useCallback(n=>{let{type:a,event:i}=n;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const jes={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. `},Nes={onDragStart(s){let{active:t}=s;return"Picked up draggable item "+t.id+"."},onDragOver(s){let{active:t,over:r}=s;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(s){let{active:t,over:r}=s;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(s){let{active:t}=s;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function kes(s){let{announcements:t=Nes,container:r,hiddenTextDescribedById:n,screenReaderInstructions:a=jes}=s;const{announce:i,announcement:l}=bes(),o=NB("DndLiveRegion"),[c,d]=k.useState(!1);if(k.useEffect(()=>{d(!0)},[]),_es(k.useMemo(()=>({onDragStart(m){let{active:x}=m;i(t.onDragStart({active:x}))},onDragMove(m){let{active:x,over:y}=m;t.onDragMove&&i(t.onDragMove({active:x,over:y}))},onDragOver(m){let{active:x,over:y}=m;i(t.onDragOver({active:x,over:y}))},onDragEnd(m){let{active:x,over:y}=m;i(t.onDragEnd({active:x,over:y}))},onDragCancel(m){let{active:x,over:y}=m;i(t.onDragCancel({active:x,over:y}))}}),[i,t])),!c)return null;const h=wt.createElement(wt.Fragment,null,wt.createElement(yes,{id:n,value:a.draggable}),wt.createElement(ves,{id:o,announcement:l}));return r?Vf.createPortal(h,r):h}var Ru;(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"})(Ru||(Ru={}));function $ue(){}function $M(s,t){return k.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function fpe(){for(var s=arguments.length,t=new Array(s),r=0;r[...t].filter(n=>n!=null),[...t])}const By=Object.freeze({x:0,y:0});function Qot(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function Jot(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return r-n}function Ses(s,t){let{data:{value:r}}=s,{data:{value:n}}=t;return n-r}function OBe(s){let{left:t,top:r,height:n,width:a}=s;return[{x:t,y:r},{x:t+a,y:r},{x:t,y:r+n},{x:t+a,y:r+n}]}function elt(s,t){if(!s||s.length===0)return null;const[r]=s;return r[t]}function FBe(s,t,r){return t===void 0&&(t=s.left),r===void 0&&(r=s.top),{x:t+s.width*.5,y:r+s.height*.5}}const ppe=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=FBe(t,t.left,t.top),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=Qot(FBe(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(Jot)},Ces=s=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=OBe(t),i=[];for(const l of n){const{id:o}=l,c=r.get(o);if(c){const d=OBe(c),h=a.reduce((x,y,v)=>x+Qot(d[v],y),0),m=Number((h/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:m}})}}return i.sort(Jot)};function Tes(s,t){const r=Math.max(t.top,s.top),n=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-n,o=i-r;if(n{let{collisionRect:t,droppableRects:r,droppableContainers:n}=s;const a=[];for(const i of n){const{id:l}=i,o=r.get(l);if(o){const c=Tes(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(Ses)};function Aes(s,t,r){return{...s,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function tlt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:By}function Mes(s){return function(r){for(var n=arguments.length,a=new Array(n>1?n-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}),{...r})}}const Ies=Mes(1);function Les(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 Pes(s,t,r){const n=Les(t);if(!n)return s;const{scaleX:a,scaleY:i,x:l,y:o}=n,c=s.left-l-(1-a)*parseFloat(r),d=s.top-o-(1-i)*parseFloat(r.slice(r.indexOf(" ")+1)),h=a?s.width/a:s.width,m=i?s.height/i:s.height;return{width:h,height:m,top:d,right:c+h,bottom:d+m,left:c}}const Des={ignoreTransform:!1};function eL(s,t){t===void 0&&(t=Des);let r=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:h}=ap(s).getComputedStyle(s);d&&(r=Pes(r,d,h))}const{top:n,left:a,width:i,height:l,bottom:o,right:c}=r;return{top:n,left:a,width:i,height:l,bottom:o,right:c}}function BBe(s){return eL(s,{ignoreTransform:!0})}function Res(s){const t=s.innerWidth,r=s.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function Oes(s,t){return t===void 0&&(t=ap(s).getComputedStyle(s)),t.position==="fixed"}function Fes(s,t){t===void 0&&(t=ap(s).getComputedStyle(s));const r=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const i=t[a];return typeof i=="string"?r.test(i):!1})}function xpe(s,t){const r=[];function n(a){if(t!=null&&r.length>=t||!a)return r;if(x5e(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!wB(a)||Yot(a)||r.includes(a))return r;const i=ap(s).getComputedStyle(a);return a!==s&&Fes(a,i)&&r.push(a),Oes(a,i)?r:n(a.parentNode)}return s?n(s):r}function slt(s){const[t]=xpe(s,1);return t??null}function M1e(s){return!mpe||!s?null:QI(s)?s:p5e(s)?x5e(s)||s===JI(s).scrollingElement?window:wB(s)?s:null:null}function rlt(s){return QI(s)?s.scrollX:s.scrollLeft}function nlt(s){return QI(s)?s.scrollY:s.scrollTop}function L2e(s){return{x:rlt(s),y:nlt(s)}}var fh;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(fh||(fh={}));function alt(s){return!mpe||!s?!1:s===document.scrollingElement}function ilt(s){const t={x:0,y:0},r=alt(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},n={x:s.scrollWidth-r.width,y:s.scrollHeight-r.height},a=s.scrollTop<=t.y,i=s.scrollLeft<=t.x,l=s.scrollTop>=n.y,o=s.scrollLeft>=n.x;return{isTop:a,isLeft:i,isBottom:l,isRight:o,maxScroll:n,minScroll:t}}const Bes={x:.2,y:.2};function zes(s,t,r,n,a){let{top:i,left:l,right:o,bottom:c}=r;n===void 0&&(n=10),a===void 0&&(a=Bes);const{isTop:d,isBottom:h,isLeft:m,isRight:x}=ilt(s),y={x:0,y:0},v={x:0,y:0},w={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+w.height?(y.y=fh.Backward,v.y=n*Math.abs((t.top+w.height-i)/w.height)):!h&&c>=t.bottom-w.height&&(y.y=fh.Forward,v.y=n*Math.abs((t.bottom-w.height-c)/w.height)),!x&&o>=t.right-w.width?(y.x=fh.Forward,v.x=n*Math.abs((t.right-w.width-o)/w.width)):!m&&l<=t.left+w.width&&(y.x=fh.Backward,v.x=n*Math.abs((t.left+w.width-l)/w.width)),{direction:y,speed:v}}function $es(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:r,right:n,bottom:a}=s.getBoundingClientRect();return{top:t,left:r,right:n,bottom:a,width:s.clientWidth,height:s.clientHeight}}function olt(s){return s.reduce((t,r)=>UA(t,L2e(r)),By)}function Ues(s){return s.reduce((t,r)=>t+rlt(r),0)}function qes(s){return s.reduce((t,r)=>t+nlt(r),0)}function Ves(s,t){if(t===void 0&&(t=eL),!s)return;const{top:r,left:n,bottom:a,right:i}=t(s);slt(s)&&(a<=0||i<=0||r>=window.innerHeight||n>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const Hes=[["x",["left","right"],Ues],["y",["top","bottom"],qes]];class v5e{constructor(t,r){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 n=xpe(r),a=olt(n);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of Hes)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(n),h=a[i]-d;return this.rect[c]+h},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class jO{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(r=>{var n;return(n=this.target)==null?void 0:n.removeEventListener(...r)})},this.target=t}add(t,r,n){var a;(a=this.target)==null||a.addEventListener(t,r,n),this.listeners.push([t,r,n])}}function Ges(s){const{EventTarget:t}=ap(s);return s instanceof t?s:JI(s)}function I1e(s,t){const r=Math.abs(s.x),n=Math.abs(s.y);return typeof t=="number"?Math.sqrt(r**2+n**2)>t:"x"in t&&"y"in t?r>t.x&&n>t.y:"x"in t?r>t.x:"y"in t?n>t.y:!1}var Gx;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(Gx||(Gx={}));function zBe(s){s.preventDefault()}function Wes(s){s.stopPropagation()}var So;(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"})(So||(So={}));const llt={start:[So.Space,So.Enter],cancel:[So.Esc],end:[So.Space,So.Enter,So.Tab]},Kes=(s,t)=>{let{currentCoordinates:r}=t;switch(s.code){case So.Right:return{...r,x:r.x+25};case So.Left:return{...r,x:r.x-25};case So.Down:return{...r,y:r.y+25};case So.Up:return{...r,y:r.y-25}}};class gpe{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:r}}=t;this.props=t,this.listeners=new jO(JI(r)),this.windowListeners=new jO(ap(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Gx.Resize,this.handleCancel),this.windowListeners.add(Gx.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Gx.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,n=t.node.current;n&&Ves(n),r(By)}handleKeyDown(t){if(y5e(t)){const{active:r,context:n,options:a}=this.props,{keyboardCodes:i=llt,coordinateGetter:l=Kes,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}=n.current,h=d?{x:d.left,y:d.top}:By;this.referenceCoordinates||(this.referenceCoordinates=h);const m=l(t,{active:r,context:n.current,currentCoordinates:h});if(m){const x=R8(m,h),y={x:0,y:0},{scrollableAncestors:v}=n.current;for(const w of v){const b=t.code,{isTop:N,isRight:S,isLeft:T,isBottom:A,maxScroll:I,minScroll:D}=ilt(w),R=$es(w),$={x:Math.min(b===So.Right?R.right-R.width/2:R.right,Math.max(b===So.Right?R.left:R.left+R.width/2,m.x)),y:Math.min(b===So.Down?R.bottom-R.height/2:R.bottom,Math.max(b===So.Down?R.top:R.top+R.height/2,m.y))},F=b===So.Right&&!S||b===So.Left&&!T,z=b===So.Down&&!A||b===So.Up&&!N;if(F&&$.x!==m.x){const Q=w.scrollLeft+x.x,K=b===So.Right&&Q<=I.x||b===So.Left&&Q>=D.x;if(K&&!x.y){w.scrollTo({left:Q,behavior:o});return}K?y.x=w.scrollLeft-Q:y.x=b===So.Right?w.scrollLeft-I.x:w.scrollLeft-D.x,y.x&&w.scrollBy({left:-y.x,behavior:o});break}else if(z&&$.y!==m.y){const Q=w.scrollTop+x.y,K=b===So.Down&&Q<=I.y||b===So.Up&&Q>=D.y;if(K&&!x.x){w.scrollTo({top:Q,behavior:o});return}K?y.y=w.scrollTop-Q:y.y=b===So.Down?w.scrollTop-I.y:w.scrollTop-D.y,y.y&&w.scrollBy({top:-y.y,behavior:o});break}}this.handleMove(t,UA(R8(m,this.referenceCoordinates),y))}}}handleMove(t,r){const{onMove:n}=this.props;t.preventDefault(),n(r)}handleEnd(t){const{onEnd:r}=this.props;t.preventDefault(),this.detach(),r()}handleCancel(t){const{onCancel:r}=this.props;t.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}gpe.activators=[{eventName:"onKeyDown",handler:(s,t,r)=>{let{keyboardCodes:n=llt,onActivation:a}=t,{active:i}=r;const{code:l}=s.nativeEvent;if(n.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 $Be(s){return!!(s&&"distance"in s)}function UBe(s){return!!(s&&"delay"in s)}class b5e{constructor(t,r,n){var a;n===void 0&&(n=Ges(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=r;const{event:i}=t,{target:l}=i;this.props=t,this.events=r,this.document=JI(l),this.documentListeners=new jO(this.document),this.listeners=new jO(n),this.windowListeners=new jO(ap(l)),this.initialCoordinates=(a=I2e(i))!=null?a:By,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:r,bypassActivationConstraint:n}}}=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(Gx.Resize,this.handleCancel),this.windowListeners.add(Gx.DragStart,zBe),this.windowListeners.add(Gx.VisibilityChange,this.handleCancel),this.windowListeners.add(Gx.ContextMenu,zBe),this.documentListeners.add(Gx.Keydown,this.handleKeydown),r){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(UBe(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if($Be(r)){this.handlePending(r);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,r){const{active:n,onPending:a}=this.props;a(n,t,this.initialCoordinates,r)}handleStart(){const{initialCoordinates:t}=this,{onStart:r}=this.props;t&&(this.activated=!0,this.documentListeners.add(Gx.Click,Wes,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Gx.SelectionChange,this.removeTextSelection),r(t))}handleMove(t){var r;const{activated:n,initialCoordinates:a,props:i}=this,{onMove:l,options:{activationConstraint:o}}=i;if(!a)return;const c=(r=I2e(t))!=null?r:By,d=R8(a,c);if(!n&&o){if($Be(o)){if(o.tolerance!=null&&I1e(d,o.tolerance))return this.handleCancel();if(I1e(d,o.distance))return this.handleStart()}if(UBe(o)&&I1e(d,o.tolerance))return this.handleCancel();this.handlePending(o,d);return}t.cancelable&&t.preventDefault(),l(c)}handleEnd(){const{onAbort:t,onEnd:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleCancel(){const{onAbort:t,onCancel:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleKeydown(t){t.code===So.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Yes={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class tL extends b5e{constructor(t){const{event:r}=t,n=JI(r.target);super(t,Yes,n)}}tL.activators=[{eventName:"onPointerDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return!r.isPrimary||r.button!==0?!1:(n==null||n({event:r}),!0)}}];const Zes={move:{name:"mousemove"},end:{name:"mouseup"}};var P2e;(function(s){s[s.RightClick=2]="RightClick"})(P2e||(P2e={}));class Xes extends b5e{constructor(t){super(t,Zes,JI(t.event.target))}}Xes.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;return r.button===P2e.RightClick?!1:(n==null||n({event:r}),!0)}}];const L1e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Qes extends b5e{constructor(t){super(t,L1e)}static setup(){return window.addEventListener(L1e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(L1e.move.name,t)};function t(){}}}Qes.activators=[{eventName:"onTouchStart",handler:(s,t)=>{let{nativeEvent:r}=s,{onActivation:n}=t;const{touches:a}=r;return a.length>1?!1:(n==null||n({event:r}),!0)}}];var NO;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(NO||(NO={}));var Uue;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Uue||(Uue={}));function Jes(s){let{acceleration:t,activator:r=NO.Pointer,canScroll:n,draggingRect:a,enabled:i,interval:l=5,order:o=Uue.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:h,delta:m,threshold:x}=s;const y=tts({delta:m,disabled:!i}),[v,w]=mes(),b=k.useRef({x:0,y:0}),N=k.useRef({x:0,y:0}),S=k.useMemo(()=>{switch(r){case NO.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case NO.DraggableRect:return a}},[r,a,c]),T=k.useRef(null),A=k.useCallback(()=>{const D=T.current;if(!D)return;const R=b.current.x*N.current.x,$=b.current.y*N.current.y;D.scrollBy(R,$)},[]),I=k.useMemo(()=>o===Uue.TreeOrder?[...d].reverse():d,[o,d]);k.useEffect(()=>{if(!i||!d.length||!S){w();return}for(const D of I){if((n==null?void 0:n(D))===!1)continue;const R=d.indexOf(D),$=h[R];if(!$)continue;const{direction:F,speed:z}=zes(D,$,S,t,x);for(const Q of["x","y"])y[Q][F[Q]]||(z[Q]=0,F[Q]=0);if(z.x>0||z.y>0){w(),T.current=D,v(A,l),b.current=z,N.current=F;return}}b.current={x:0,y:0},N.current={x:0,y:0},w()},[t,A,n,w,i,l,JSON.stringify(S),JSON.stringify(y),v,d,I,h,JSON.stringify(x)])}const ets={x:{[fh.Backward]:!1,[fh.Forward]:!1},y:{[fh.Backward]:!1,[fh.Forward]:!1}};function tts(s){let{delta:t,disabled:r}=s;const n=M2e(t);return jB(a=>{if(r||!n||!a)return ets;const i={x:Math.sign(t.x-n.x),y:Math.sign(t.y-n.y)};return{x:{[fh.Backward]:a.x[fh.Backward]||i.x===-1,[fh.Forward]:a.x[fh.Forward]||i.x===1},y:{[fh.Backward]:a.y[fh.Backward]||i.y===-1,[fh.Forward]:a.y[fh.Forward]||i.y===1}}},[r,t,n])}function sts(s,t){const r=t!=null?s.get(t):void 0,n=r?r.node.current:null;return jB(a=>{var i;return t==null?null:(i=n??a)!=null?i:null},[n,t])}function rts(s,t){return k.useMemo(()=>s.reduce((r,n)=>{const{sensor:a}=n,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,n)}));return[...r,...i]},[]),[s,t])}var O8;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(O8||(O8={}));var D2e;(function(s){s.Optimized="optimized"})(D2e||(D2e={}));const qBe=new Map;function nts(s,t){let{dragging:r,dependencies:n,config:a}=t;const[i,l]=k.useState(null),{frequency:o,measure:c,strategy:d}=a,h=k.useRef(s),m=b(),x=D8(m),y=k.useCallback(function(N){N===void 0&&(N=[]),!x.current&&l(S=>S===null?N:S.concat(N.filter(T=>!S.includes(T))))},[x]),v=k.useRef(null),w=jB(N=>{if(m&&!r)return qBe;if(!N||N===qBe||h.current!==s||i!=null){const S=new Map;for(let T of s){if(!T)continue;if(i&&i.length>0&&!i.includes(T.id)&&T.rect.current){S.set(T.id,T.rect.current);continue}const A=T.node.current,I=A?new v5e(c(A),A):null;T.rect.current=I,I&&S.set(T.id,I)}return S}return N},[s,i,r,m,c]);return k.useEffect(()=>{h.current=s},[s]),k.useEffect(()=>{m||y()},[r,m]),k.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),k.useEffect(()=>{m||typeof o!="number"||v.current!==null||(v.current=setTimeout(()=>{y(),v.current=null},o))},[o,m,y,...n]),{droppableRects:w,measureDroppableContainers:y,measuringScheduled:i!=null};function b(){switch(d){case O8.Always:return!1;case O8.BeforeDragging:return r;default:return!r}}}function clt(s,t){return jB(r=>s?r||(typeof t=="function"?t(s):s):null,[t,s])}function ats(s,t){return clt(s,t)}function its(s){let{callback:t,disabled:r}=s;const n=g5e(t),a=k.useMemo(()=>{if(r||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(n)},[n,r]);return k.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function ype(s){let{callback:t,disabled:r}=s;const n=g5e(t),a=k.useMemo(()=>{if(r||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(n)},[r]);return k.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function ots(s){return new v5e(eL(s),s)}function VBe(s,t,r){t===void 0&&(t=ots);const[n,a]=k.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??r)!=null?d:null}const h=t(s);return JSON.stringify(c)===JSON.stringify(h)?c:h})}const l=its({callback(c){if(s)for(const d of c){const{type:h,target:m}=d;if(h==="childList"&&m instanceof HTMLElement&&m.contains(s)){i();break}}}}),o=ype({callback:i});return Sv(()=>{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]),n}function lts(s){const t=clt(s);return tlt(s,t)}const HBe=[];function cts(s){const t=k.useRef(s),r=jB(n=>s?n&&n!==HBe&&s&&t.current&&s.parentNode===t.current.parentNode?n:xpe(s):HBe,[s]);return k.useEffect(()=>{t.current=s},[s]),r}function dts(s){const[t,r]=k.useState(null),n=k.useRef(s),a=k.useCallback(i=>{const l=M1e(i.target);l&&r(o=>o?(o.set(l,L2e(l)),new Map(o)):null)},[]);return k.useEffect(()=>{const i=n.current;if(s!==i){l(i);const o=s.map(c=>{const d=M1e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,L2e(d)]):null}).filter(c=>c!=null);r(o.length?new Map(o):null),n.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=M1e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),k.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>UA(i,l),By):olt(s):By,[s,t])}function GBe(s,t){t===void 0&&(t=[]);const r=k.useRef(null);return k.useEffect(()=>{r.current=null},t),k.useEffect(()=>{const n=s!==By;n&&!r.current&&(r.current=s),!n&&r.current&&(r.current=null)},[s]),r.current?R8(s,r.current):By}function uts(s){k.useEffect(()=>{if(!mpe)return;const t=s.map(r=>{let{sensor:n}=r;return n.setup==null?void 0:n.setup()});return()=>{for(const r of t)r==null||r()}},s.map(t=>{let{sensor:r}=t;return r}))}function hts(s,t){return k.useMemo(()=>s.reduce((r,n)=>{let{eventName:a,handler:i}=n;return r[a]=l=>{i(l,t)},r},{}),[s,t])}function dlt(s){return k.useMemo(()=>s?Res(s):null,[s])}const WBe=[];function mts(s,t){t===void 0&&(t=eL);const[r]=s,n=dlt(r?ap(r):null),[a,i]=k.useState(WBe);function l(){i(()=>s.length?s.map(c=>alt(c)?n:new v5e(t(c),c)):WBe)}const o=ype({callback:l});return Sv(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function fts(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return wB(t)?t:s}function pts(s){let{measure:t}=s;const[r,n]=k.useState(null),a=k.useCallback(d=>{for(const{target:h}of d)if(wB(h)){n(m=>{const x=t(h);return m?{...m,width:x.width,height:x.height}:x});break}},[t]),i=ype({callback:a}),l=k.useCallback(d=>{const h=fts(d);i==null||i.disconnect(),h&&(i==null||i.observe(h)),n(h?t(h):null)},[t,i]),[o,c]=zue(l);return k.useMemo(()=>({nodeRef:o,rect:r,setRef:c}),[r,o,c])}const xts=[{sensor:tL,options:{}},{sensor:gpe,options:{}}],gts={current:{}},Nce={draggable:{measure:BBe},droppable:{measure:BBe,strategy:O8.WhileDragging,frequency:D2e.Optimized},dragOverlay:{measure:eL}};class kO extends Map{get(t){var r;return t!=null&&(r=super.get(t))!=null?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:r}=t;return!r})}getNodeFor(t){var r,n;return(r=(n=this.get(t))==null?void 0:n.node.current)!=null?r:void 0}}const yts={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new kO,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:$ue},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Nce,measureDroppableContainers:$ue,windowRect:null,measuringScheduled:!1},vts={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:$ue,draggableNodes:new Map,over:null,measureDroppableContainers:$ue},vpe=k.createContext(vts),ult=k.createContext(yts);function bts(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new kO}}}function _ts(s,t){switch(t.type){case Ru.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Ru.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 Ru.DragEnd:case Ru.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Ru.RegisterDroppable:{const{element:r}=t,{id:n}=r,a=new kO(s.droppable.containers);return a.set(n,r),{...s,droppable:{...s.droppable,containers:a}}}case Ru.SetDroppableDisabled:{const{id:r,key:n,disabled:a}=t,i=s.droppable.containers.get(r);if(!i||n!==i.key)return s;const l=new kO(s.droppable.containers);return l.set(r,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case Ru.UnregisterDroppable:{const{id:r,key:n}=t,a=s.droppable.containers.get(r);if(!a||n!==a.key)return s;const i=new kO(s.droppable.containers);return i.delete(r),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function wts(s){let{disabled:t}=s;const{active:r,activatorEvent:n,draggableNodes:a}=k.useContext(vpe),i=M2e(n),l=M2e(r==null?void 0:r.id);return k.useEffect(()=>{if(!t&&!n&&i&&l!=null){if(!y5e(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 h of[c.current,d.current]){if(!h)continue;const m=xes(h);if(m){m.focus();break}}})}},[n,t,a,l,i]),null}function jts(s,t){let{transform:r,...n}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...n}),r):r}function Nts(s){return k.useMemo(()=>({draggable:{...Nce.draggable,...s==null?void 0:s.draggable},droppable:{...Nce.droppable,...s==null?void 0:s.droppable},dragOverlay:{...Nce.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 kts(s){let{activeNode:t,measure:r,initialRect:n,config:a=!0}=s;const i=k.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;Sv(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!n)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const h=r(d),m=tlt(h,n);if(l||(m.x=0),o||(m.y=0),i.current=!0,Math.abs(m.x)>0||Math.abs(m.y)>0){const x=slt(d);x&&x.scrollBy({top:m.y,left:m.x})}},[t,l,o,n,r])}const hlt=k.createContext({...By,scaleX:1,scaleY:1});var lw;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(lw||(lw={}));const bpe=k.memo(function(t){var r,n,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:h=xts,collisionDetection:m=Ees,measuring:x,modifiers:y,...v}=t;const w=k.useReducer(_ts,void 0,bts),[b,N]=w,[S,T]=wes(),[A,I]=k.useState(lw.Uninitialized),D=A===lw.Initialized,{draggable:{active:R,nodes:$,translate:F},droppable:{containers:z}}=b,Q=R!=null?$.get(R):null,K=k.useRef({initial:null,translated:null}),X=k.useMemo(()=>{var qr;return R!=null?{id:R,data:(qr=Q==null?void 0:Q.data)!=null?qr:gts,rect:K}:null},[R,Q]),Z=k.useRef(null),[re,le]=k.useState(null),[oe,ne]=k.useState(null),ie=D8(v,Object.values(v)),ye=NB("DndDescribedBy",l),ce=k.useMemo(()=>z.getEnabled(),[z]),ve=Nts(x),{droppableRects:be,measureDroppableContainers:Ue,measuringScheduled:Be}=nts(ce,{dragging:D,dependencies:[F.x,F.y],config:ve.droppable}),De=sts($,R),Ae=k.useMemo(()=>oe?I2e(oe):null,[oe]),He=Lr(),Le=ats(De,ve.draggable.measure);kts({activeNode:R!=null?$.get(R):null,config:He.layoutShiftCompensation,initialRect:Le,measure:ve.draggable.measure});const Ie=VBe(De,ve.draggable.measure,Le),Te=VBe(De?De.parentElement:null),xe=k.useRef({activatorEvent:null,active:null,activeNode:De,collisionRect:null,collisions:null,droppableRects:be,draggableNodes:$,draggingNode:null,draggingNodeRect:null,droppableContainers:z,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),et=z.getNodeFor((r=xe.current.over)==null?void 0:r.id),fe=pts({measure:ve.dragOverlay.measure}),it=(n=fe.nodeRef.current)!=null?n:De,Oe=D?(a=fe.rect)!=null?a:Ie:null,Ye=!!(fe.nodeRef.current&&fe.rect),We=lts(Ye?null:Ie),_e=dlt(it?ap(it):null),Re=cts(D?et??De:null),tt=mts(Re),Ke=jts(y,{transform:{x:F.x-We.x,y:F.y-We.y,scaleX:1,scaleY:1},activatorEvent:oe,active:X,activeNodeRect:Ie,containerNodeRect:Te,draggingNodeRect:Oe,over:xe.current.over,overlayNodeRect:fe.rect,scrollableAncestors:Re,scrollableAncestorRects:tt,windowRect:_e}),Ze=Ae?UA(Ae,F):null,lt=dts(Re),xt=GBe(lt),Xe=GBe(lt,[Ie]),Je=UA(Ke,xt),jt=Oe?Ies(Oe,Ke):null,ns=X&&jt?m({active:X,collisionRect:jt,droppableRects:be,droppableContainers:ce,pointerCoordinates:Ze}):null,Ns=elt(ns,"id"),[Ys,rs]=k.useState(null),bt=Ye?Ke:UA(Ke,Xe),cs=Aes(bt,(i=Ys==null?void 0:Ys.rect)!=null?i:null,Ie),yt=k.useRef(null),is=k.useCallback((qr,Ur)=>{let{sensor:Mr,options:Cr}=Ur;if(Z.current==null)return;const Xr=$.get(Z.current);if(!Xr)return;const Ln=qr.nativeEvent,Zs=new Mr({active:Z.current,activeNode:Xr,event:Ln,options:Cr,context:xe,onAbort(ss){if(!$.get(ss))return;const{onDragAbort:nn}=ie.current,hr={id:ss};nn==null||nn(hr),S({type:"onDragAbort",event:hr})},onPending(ss,ta,nn,hr){if(!$.get(ss))return;const{onDragPending:Qn}=ie.current,Gt={id:ss,constraint:ta,initialCoordinates:nn,offset:hr};Qn==null||Qn(Gt),S({type:"onDragPending",event:Gt})},onStart(ss){const ta=Z.current;if(ta==null)return;const nn=$.get(ta);if(!nn)return;const{onDragStart:hr}=ie.current,Pr={activatorEvent:Ln,active:{id:ta,data:nn.data,rect:K}};Vf.unstable_batchedUpdates(()=>{hr==null||hr(Pr),I(lw.Initializing),N({type:Ru.DragStart,initialCoordinates:ss,active:ta}),S({type:"onDragStart",event:Pr}),le(yt.current),ne(Ln)})},onMove(ss){N({type:Ru.DragMove,coordinates:ss})},onEnd:Yr(Ru.DragEnd),onCancel:Yr(Ru.DragCancel)});yt.current=Zs;function Yr(ss){return async function(){const{active:nn,collisions:hr,over:Pr,scrollAdjustedTranslate:Qn}=xe.current;let Gt=null;if(nn&&Qn){const{cancelDrop:gr}=ie.current;Gt={activatorEvent:Ln,active:nn,collisions:hr,delta:Qn,over:Pr},ss===Ru.DragEnd&&typeof gr=="function"&&await Promise.resolve(gr(Gt))&&(ss=Ru.DragCancel)}Z.current=null,Vf.unstable_batchedUpdates(()=>{N({type:ss}),I(lw.Uninitialized),rs(null),le(null),ne(null),yt.current=null;const gr=ss===Ru.DragEnd?"onDragEnd":"onDragCancel";if(Gt){const zt=ie.current[gr];zt==null||zt(Gt),S({type:gr,event:Gt})}})}}},[$]),Bs=k.useCallback((qr,Ur)=>(Mr,Cr)=>{const Xr=Mr.nativeEvent,Ln=$.get(Cr);if(Z.current!==null||!Ln||Xr.dndKit||Xr.defaultPrevented)return;const Zs={active:Ln};qr(Mr,Ur.options,Zs)===!0&&(Xr.dndKit={capturedBy:Ur.sensor},Z.current=Cr,is(Mr,Ur))},[$,is]),ps=rts(h,Bs);uts(h),Sv(()=>{Ie&&A===lw.Initializing&&I(lw.Initialized)},[Ie,A]),k.useEffect(()=>{const{onDragMove:qr}=ie.current,{active:Ur,activatorEvent:Mr,collisions:Cr,over:Xr}=xe.current;if(!Ur||!Mr)return;const Ln={active:Ur,activatorEvent:Mr,collisions:Cr,delta:{x:Je.x,y:Je.y},over:Xr};Vf.unstable_batchedUpdates(()=>{qr==null||qr(Ln),S({type:"onDragMove",event:Ln})})},[Je.x,Je.y]),k.useEffect(()=>{const{active:qr,activatorEvent:Ur,collisions:Mr,droppableContainers:Cr,scrollAdjustedTranslate:Xr}=xe.current;if(!qr||Z.current==null||!Ur||!Xr)return;const{onDragOver:Ln}=ie.current,Zs=Cr.get(Ns),Yr=Zs&&Zs.rect.current?{id:Zs.id,rect:Zs.rect.current,data:Zs.data,disabled:Zs.disabled}:null,ss={active:qr,activatorEvent:Ur,collisions:Mr,delta:{x:Xr.x,y:Xr.y},over:Yr};Vf.unstable_batchedUpdates(()=>{rs(Yr),Ln==null||Ln(ss),S({type:"onDragOver",event:ss})})},[Ns]),Sv(()=>{xe.current={activatorEvent:oe,active:X,activeNode:De,collisionRect:jt,collisions:ns,droppableRects:be,draggableNodes:$,draggingNode:it,draggingNodeRect:Oe,droppableContainers:z,over:Ys,scrollableAncestors:Re,scrollAdjustedTranslate:Je},K.current={initial:Oe,translated:jt}},[X,De,ns,jt,$,it,Oe,be,z,Ys,Re,Je]),Jes({...He,delta:F,draggingRect:jt,pointerCoordinates:Ze,scrollableAncestors:Re,scrollableAncestorRects:tt});const lr=k.useMemo(()=>({active:X,activeNode:De,activeNodeRect:Ie,activatorEvent:oe,collisions:ns,containerNodeRect:Te,dragOverlay:fe,draggableNodes:$,droppableContainers:z,droppableRects:be,over:Ys,measureDroppableContainers:Ue,scrollableAncestors:Re,scrollableAncestorRects:tt,measuringConfiguration:ve,measuringScheduled:Be,windowRect:_e}),[X,De,Ie,oe,ns,Te,fe,$,z,be,Ys,Ue,Re,tt,ve,Be,_e]),kr=k.useMemo(()=>({activatorEvent:oe,activators:ps,active:X,activeNodeRect:Ie,ariaDescribedById:{draggable:ye},dispatch:N,draggableNodes:$,over:Ys,measureDroppableContainers:Ue}),[oe,ps,X,Ie,N,ye,$,Ys,Ue]);return wt.createElement(Xot.Provider,{value:T},wt.createElement(vpe.Provider,{value:kr},wt.createElement(ult.Provider,{value:lr},wt.createElement(hlt.Provider,{value:cs},d)),wt.createElement(wts,{disabled:(o==null?void 0:o.restoreFocus)===!1})),wt.createElement(kes,{...o,hiddenTextDescribedById:ye}));function Lr(){const qr=(re==null?void 0:re.autoScrollEnabled)===!1,Ur=typeof c=="object"?c.enabled===!1:c===!1,Mr=D&&!qr&&!Ur;return typeof c=="object"?{...c,enabled:Mr}:{enabled:Mr}}}),Sts=k.createContext(null),KBe="button",Cts="Draggable";function Tts(s){let{id:t,data:r,disabled:n=!1,attributes:a}=s;const i=NB(Cts),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:h,draggableNodes:m,over:x}=k.useContext(vpe),{role:y=KBe,roleDescription:v="draggable",tabIndex:w=0}=a??{},b=(c==null?void 0:c.id)===t,N=k.useContext(b?hlt:Sts),[S,T]=zue(),[A,I]=zue(),D=hts(l,t),R=D8(r);Sv(()=>(m.set(t,{id:t,key:i,node:S,activatorNode:A,data:R}),()=>{const F=m.get(t);F&&F.key===i&&m.delete(t)}),[m,t]);const $=k.useMemo(()=>({role:y,tabIndex:w,"aria-disabled":n,"aria-pressed":b&&y===KBe?!0:void 0,"aria-roledescription":v,"aria-describedby":h.draggable}),[n,y,w,b,v,h.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:$,isDragging:b,listeners:n?void 0:D,node:S,over:x,setNodeRef:T,setActivatorNodeRef:I,transform:N}}function Ets(){return k.useContext(ult)}const Ats="Droppable",Mts={timeout:25};function Its(s){let{data:t,disabled:r=!1,id:n,resizeObserverConfig:a}=s;const i=NB(Ats),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=k.useContext(vpe),h=k.useRef({disabled:r}),m=k.useRef(!1),x=k.useRef(null),y=k.useRef(null),{disabled:v,updateMeasurementsFor:w,timeout:b}={...Mts,...a},N=D8(w??n),S=k.useCallback(()=>{if(!m.current){m.current=!0;return}y.current!=null&&clearTimeout(y.current),y.current=setTimeout(()=>{d(Array.isArray(N.current)?N.current:[N.current]),y.current=null},b)},[b]),T=ype({callback:S,disabled:v||!l}),A=k.useCallback(($,F)=>{T&&(F&&(T.unobserve(F),m.current=!1),$&&T.observe($))},[T]),[I,D]=zue(A),R=D8(t);return k.useEffect(()=>{!T||!I.current||(T.disconnect(),m.current=!1,T.observe(I.current))},[I,T]),k.useEffect(()=>(o({type:Ru.RegisterDroppable,element:{id:n,key:i,disabled:r,node:I,rect:x,data:R}}),()=>o({type:Ru.UnregisterDroppable,key:i,id:n})),[n]),k.useEffect(()=>{r!==h.current.disabled&&(o({type:Ru.SetDroppableDisabled,id:n,key:i,disabled:r}),h.current.disabled=r)},[n,i,r,o]),{active:l,rect:x,isOver:(c==null?void 0:c.id)===n,node:I,over:c,setNodeRef:D}}function _pe(s,t,r){const n=s.slice();return n.splice(r<0?n.length+r:r,0,n.splice(t,1)[0]),n}function Lts(s,t){return s.reduce((r,n,a)=>{const i=t.get(n);return i&&(r[a]=i),r},Array(s.length))}function x$(s){return s!==null&&s>=0}function Pts(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let r=0;r{var t;let{rects:r,activeNodeRect:n,activeIndex:a,overIndex:i,index:l}=s;const o=(t=r[a])!=null?t:n;if(!o)return null;const c=Rts(r,l,a);if(l===a){const d=r[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...g$}:l=i?{x:o.width+c,y:0,...g$}:{x:0,y:0,...g$}};function Rts(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return!n||!a&&!i?0:r{let{rects:t,activeIndex:r,overIndex:n,index:a}=s;const i=_pe(t,n,r),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}},y$={scaleX:1,scaleY:1},Ots=s=>{var t;let{activeIndex:r,activeNodeRect:n,index:a,rects:i,overIndex:l}=s;const o=(t=i[r])!=null?t:n;if(!o)return null;if(a===r){const d=i[l];return d?{x:0,y:rr&&a<=l?{x:0,y:-o.height-c,...y$}:a=l?{x:0,y:o.height+c,...y$}:{x:0,y:0,...y$}};function Fts(s,t,r){const n=s[t],a=s[t-1],i=s[t+1];return n?rn.map(D=>typeof D=="object"&&"id"in D?D.id:D),[n]),v=l!=null,w=l?y.indexOf(l.id):-1,b=d?y.indexOf(d.id):-1,N=k.useRef(y),S=!Pts(y,N.current),T=b!==-1&&w===-1||S,A=Dts(i);Sv(()=>{S&&v&&h(y)},[S,y,v,h]),k.useEffect(()=>{N.current=y},[y]);const I=k.useMemo(()=>({activeIndex:w,containerId:m,disabled:A,disableTransforms:T,items:y,overIndex:b,useDragOverlay:x,sortedRects:Lts(y,c),strategy:a}),[w,m,A.draggable,A.droppable,T,y,b,c,x,a]);return wt.createElement(flt.Provider,{value:I},t)}const Bts=s=>{let{id:t,items:r,activeIndex:n,overIndex:a}=s;return _pe(r,n,a).indexOf(t)},zts=s=>{let{containerId:t,isSorting:r,wasDragging:n,index:a,items:i,newIndex:l,previousItems:o,previousContainerId:c,transition:d}=s;return!d||!n||o!==i&&a===l?!1:r?!0:l!==a&&t===c},$ts={duration:200,easing:"ease"},plt="transform",Uts=Oj.Transition.toString({property:plt,duration:0,easing:"linear"}),qts={roleDescription:"sortable"};function Vts(s){let{disabled:t,index:r,node:n,rect:a}=s;const[i,l]=k.useState(null),o=k.useRef(r);return Sv(()=>{if(!t&&r!==o.current&&n.current){const c=a.current;if(c){const d=eL(n.current,{ignoreTransform:!0}),h={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(h.x||h.y)&&l(h)}}r!==o.current&&(o.current=r)},[t,r,n,a]),k.useEffect(()=>{i&&l(null)},[i]),i}function jpe(s){let{animateLayoutChanges:t=zts,attributes:r,disabled:n,data:a,getNewIndex:i=Bts,id:l,strategy:o,resizeObserverConfig:c,transition:d=$ts}=s;const{items:h,containerId:m,activeIndex:x,disabled:y,disableTransforms:v,sortedRects:w,overIndex:b,useDragOverlay:N,strategy:S}=k.useContext(flt),T=Hts(n,y),A=h.indexOf(l),I=k.useMemo(()=>({sortable:{containerId:m,index:A,items:h},...a}),[m,a,A,h]),D=k.useMemo(()=>h.slice(h.indexOf(l)),[h,l]),{rect:R,node:$,isOver:F,setNodeRef:z}=Its({id:l,data:I,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:D,...c}}),{active:Q,activatorEvent:K,activeNodeRect:X,attributes:Z,setNodeRef:re,listeners:le,isDragging:oe,over:ne,setActivatorNodeRef:ie,transform:ye}=Tts({id:l,data:I,attributes:{...qts,...r},disabled:T.draggable}),ce=hes(z,re),ve=!!Q,be=ve&&!v&&x$(x)&&x$(b),Ue=!N&&oe,Be=Ue&&be?ye:null,Ae=be?Be??(o??S)({rects:w,activeNodeRect:X,activeIndex:x,overIndex:b,index:A}):null,He=x$(x)&&x$(b)?i({id:l,items:h,activeIndex:x,overIndex:b}):A,Le=Q==null?void 0:Q.id,Ie=k.useRef({activeId:Le,items:h,newIndex:He,containerId:m}),Te=h!==Ie.current.items,xe=t({active:Q,containerId:m,isDragging:oe,isSorting:ve,id:l,index:A,items:h,newIndex:Ie.current.newIndex,previousItems:Ie.current.items,previousContainerId:Ie.current.containerId,transition:d,wasDragging:Ie.current.activeId!=null}),et=Vts({disabled:!xe,index:A,node:$,rect:R});return k.useEffect(()=>{ve&&Ie.current.newIndex!==He&&(Ie.current.newIndex=He),m!==Ie.current.containerId&&(Ie.current.containerId=m),h!==Ie.current.items&&(Ie.current.items=h)},[ve,He,m,h]),k.useEffect(()=>{if(Le===Ie.current.activeId)return;if(Le!=null&&Ie.current.activeId==null){Ie.current.activeId=Le;return}const it=setTimeout(()=>{Ie.current.activeId=Le},50);return()=>clearTimeout(it)},[Le]),{active:Q,activeIndex:x,attributes:Z,data:I,rect:R,index:A,newIndex:He,items:h,isOver:F,isSorting:ve,isDragging:oe,listeners:le,node:$,overIndex:b,over:ne,setNodeRef:ce,setActivatorNodeRef:ie,setDroppableNodeRef:z,setDraggableNodeRef:re,transform:et??Ae,transition:fe()};function fe(){if(et||Te&&Ie.current.newIndex===A)return Uts;if(!(Ue&&!y5e(K)||!d)&&(ve||xe))return Oj.Transition.toString({...d,property:plt})}}function Hts(s,t){var r,n;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(r=s==null?void 0:s.draggable)!=null?r:t.draggable,droppable:(n=s==null?void 0:s.droppable)!=null?n:t.droppable}}function que(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 Gts=[So.Down,So.Right,So.Up,So.Left],xlt=(s,t)=>{let{context:{active:r,collisionRect:n,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(Gts.includes(s.code)){if(s.preventDefault(),!r||!n)return;const c=[];i.getEnabled().forEach(m=>{if(!m||m!=null&&m.disabled)return;const x=a.get(m.id);if(x)switch(s.code){case So.Down:n.topx.top&&c.push(m);break;case So.Left:n.left>x.left&&c.push(m);break;case So.Right:n.left1&&(h=d[1].id),h!=null){const m=i.get(r.id),x=i.get(h),y=x?a.get(x.id):null,v=x==null?void 0:x.node.current;if(v&&y&&m&&x){const b=xpe(v).some((D,R)=>o[R]!==D),N=glt(m,x),S=Wts(m,x),T=b||!N?{x:0,y:0}:{x:S?n.width-y.width:0,y:S?n.height-y.height:0},A={x:y.left,y:y.top};return T.x&&T.y?A:R8(A,T)}}}};function glt(s,t){return!que(s)||!que(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function Wts(s,t){return!que(s)||!que(t)||!glt(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>r(s),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Ge,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(on,{className:"h-2.5 w-2.5"}),_s(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:It("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(on,{className:"h-3 w-3"}),s.post_date?_s(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(_o,{className:"w-auto p-0",align:"start",children:[e.jsx(Yp,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:m=>n(s.id,m?_s(m,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>n(s.id,null),children:"Clear date"})})]})]})]})]})})}const Yts=()=>{const s=Xt(),[t,r]=k.useState("all"),[n,a]=k.useState(!1),[i,l]=k.useState(_s(new Date,"yyyy-MM")),[o,c]=k.useState([]),[d,h]=k.useState(!1),[m,x]=k.useState(null),[y,v]=k.useState(null),[w,b]=k.useState(""),[N,S]=k.useState(null),[T,A]=k.useState(!1),[I,D]=k.useState(!1),[R,$]=k.useState(_s(new Date,"yyyy-MM")),[F,z]=k.useState(null),[Q,K]=k.useState(""),[X,Z]=k.useState(""),[re,le]=k.useState(""),[oe,ne]=k.useState(!1),ie=fpe($M(tL,{activationConstraint:{distance:5}}),$M(gpe,{coordinateGetter:xlt})),{data:ye=[],isLoading:ce}=mt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:Ze,error:lt}=await V.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(lt)throw lt;return Ze}}),{data:ve=[]}=mt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:Ze,error:lt}=await V.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(lt)throw lt;return Ze}}),{data:be=[]}=mt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:Ze,error:lt}=await V.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(lt)throw lt;return Ze}}),Ue=[...new Set(ye.map(Ze=>Ze.month))].sort((Ze,lt)=>lt.localeCompare(Ze)),Be=t==="all"?ye:ye.filter(Ze=>Ze.month===t),De=Ze=>{const lt=r4e(Ze,"yyyy-MM",new Date);return _s(lt,"MMMM yyyy")},Ae=Ze=>{v(Ze),b(Ze.caption),S(Ze.post_date)},He=async()=>{if(y){A(!0);try{const{error:Ze}=await V.from("social_swag_2").update({caption:w,post_date:N}).eq("id",y.id);if(Ze)throw Ze;ue.success("Image updated"),v(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ue.error("Failed to update image")}finally{A(!1)}}},Le=async Ze=>{const{active:lt,over:xt}=Ze;if(!xt||lt.id===xt.id)return;const Xe=Be,Je=Xe.findIndex(Ns=>Ns.id===lt.id),jt=Xe.findIndex(Ns=>Ns.id===xt.id);if(Je===-1||jt===-1)return;const ns=_pe(Xe,Je,jt);s.setQueryData(["admin-social-swag-2"],Ns=>{if(!Ns)return Ns;const Ys={};return ns.forEach((rs,bt)=>{Ys[rs.id]=bt}),Ns.map(rs=>Ys[rs.id]!==void 0?{...rs,sort_order:Ys[rs.id]}:rs).sort((rs,bt)=>rs.month!==bt.month?bt.month.localeCompare(rs.month):rs.sort_order-bt.sort_order)});try{await Promise.all(ns.map((Ns,Ys)=>V.from("social_swag_2").update({sort_order:Ys}).eq("id",Ns.id)))}catch{ue.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Ie=Ze=>{const xt=Array.from(Ze.target.files||[]).sort((Xe,Je)=>Xe.name.localeCompare(Je.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(Xe=>({file:Xe,preview:URL.createObjectURL(Xe),caption:""}));c(Xe=>[...Xe,...xt].slice(0,16))},Te=Ze=>{c(lt=>{const xt=[...lt];return URL.revokeObjectURL(xt[Ze].preview),xt.splice(Ze,1),xt})},xe=(Ze,lt)=>{c(xt=>{const Xe=[...xt];return Xe[Ze]={...Xe[Ze],caption:lt},Xe})},et=async()=>{var lt;if(o.length===0){ue.error("Please add at least one image");return}if(o.filter(xt=>!xt.caption.trim()).length>0){ue.error("Please add captions to all images");return}h(!0);try{const{data:xt}=await V.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),Xe=(((lt=xt==null?void 0:xt[0])==null?void 0:lt.sort_order)??-1)+1;for(let Je=0;Je{const lt=Ze.image_url.split("/social-swag-2/");lt[1]&&await V.storage.from("social-swag-2").remove([lt[1]]);const{error:xt}=await V.from("social_swag_2").delete().eq("id",Ze.id);if(xt)throw xt},onSuccess:()=>{ue.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ue.error("Failed to delete image")}),it=Ct({mutationFn:async({id:Ze,postDate:lt})=>{const{error:xt}=await V.from("social_swag_2").update({post_date:lt}).eq("id",Ze);if(xt)throw xt},onSuccess:()=>{ue.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ue.error("Failed to update post date")}),Oe=Ct({mutationFn:async({month:Ze,link:lt})=>{const{error:xt}=await V.from("social_swag_2_months").upsert({month:Ze,canva_link:lt||null},{onConflict:"month"});if(xt)throw xt},onSuccess:()=>{ue.success("Canva link updated"),x(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ue.error("Failed to update Canva link")}),Ye=Ze=>{var lt;return((lt=ve.find(xt=>xt.month===Ze))==null?void 0:lt.canva_link)||""},We=Ze=>be.find(lt=>lt.month===Ze)||null,_e=Ze=>{var xt;const lt=(xt=Ze.target.files)==null?void 0:xt[0];lt&&(z(lt),K(URL.createObjectURL(lt)))},Re=()=>{Q&&URL.revokeObjectURL(Q),z(null),K(""),Z(""),le("")},tt=async()=>{if(!F){ue.error("Please select an image");return}ne(!0);try{const Ze=F.name.split(".").pop(),lt=`reels/${R}-${Date.now()}.${Ze}`,{error:xt}=await V.storage.from("social-swag-2").upload(lt,F);if(xt)throw xt;const{data:{publicUrl:Xe}}=V.storage.from("social-swag-2").getPublicUrl(lt),{error:Je}=await V.from("social_swag_2_reels").upsert({month:R,image_url:Xe,canva_link:re||null,caption:X||null},{onConflict:"month"});if(Je)throw Je;ue.success("Reel uploaded successfully!"),A2e(`${De(R)} Reel`,"social-swag-2"),Re(),D(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(Ze){console.error("Reel upload error:",Ze),ue.error("Failed to upload reel")}finally{ne(!1)}},Ke=Ct({mutationFn:async Ze=>{const lt=Ze.image_url.split("/social-swag-2/");lt[1]&&await V.storage.from("social-swag-2").remove([lt[1]]);const{error:xt}=await V.from("social_swag_2_reels").delete().eq("id",Ze.id);if(xt)throw xt},onSuccess:()=>{ue.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ue.error("Failed to delete reel")});return e.jsxs(ws,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(fs,{open:n,onOpenChange:a,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(ms,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Month"}),e.jsx(Ne,{type:"month",value:i,onChange:Ze=>l(Ze.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{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:Ie,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(da,{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((Ze,lt)=>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:Ze.preview,alt:`Upload ${lt+1}`,className:"w-full h-full object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Te(lt),children:e.jsx(vr,{className:"h-3 w-3"})})]}),e.jsx(or,{placeholder:"Caption...",value:Ze.caption,onChange:xt=>xe(lt,xt.target.value),className:"text-xs h-20"})]},lt))}),e.jsx(G,{onClick:et,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(fs,{open:I,onOpenChange:Ze=>{D(Ze),Ze||Re()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"gap-2",children:[e.jsx(gh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(ms,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Month"}),e.jsx(Ne,{type:"month",value:R,onChange:Ze=>$(Ze.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Reel Preview Image"}),Q?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:Q,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(Q),z(null),K("")},children:e.jsx(vr,{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:_e,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(gh,{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(he,{children:"Canva Download Link"}),e.jsx(Ne,{value:re,onChange:Ze=>le(Ze.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Caption"}),e.jsx(or,{value:X,onChange:Ze=>Z(Ze.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(G,{onClick:tt,disabled:oe||!F,className:"w-full gap-2",children:oe?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ye.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Ue.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(On,{value:t,onValueChange:r,children:e.jsxs(Rn,{children:[e.jsx(Kt,{value:"all",children:"All"}),Ue.map(Ze=>e.jsx(Kt,{value:Ze,children:De(Ze)},Ze))]})}),t!=="all"&&e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(po,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(he,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",De(t)]}),(m==null?void 0:m.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(Ne,{value:m.link,onChange:Ze=>x({...m,link:Ze.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(G,{size:"sm",onClick:()=>Oe.mutate(m),children:"Save"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>x(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:Ye(t)||"No link set"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>x({month:t,link:Ye(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(gh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(he,{className:"text-sm text-muted-foreground",children:["Reel for ",De(t)]}),(()=>{const Ze=We(t);return Ze?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:Ze.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:Ze.caption||"No caption"}),Ze.canva_link&&e.jsx("a",{href:Ze.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(G,{variant:"destructive",size:"sm",onClick:()=>Ke.mutate(Ze),children:e.jsx(yr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),ce?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):Be.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ml,{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(bpe,{sensors:ie,collisionDetection:ppe,onDragEnd:Le,children:e.jsx(wpe,{items:Be.map(Ze=>Ze.id),strategy:kB,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Be.map(Ze=>e.jsx(Kts,{item:Ze,onEdit:Ae,onDelete:lt=>fe.mutate(lt),onDateChange:(lt,xt)=>it.mutate({id:lt,postDate:xt})},Ze.id))})})})]}),e.jsx(fs,{open:!!y,onOpenChange:Ze=>{Ze||v(null)},children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Edit Image"})}),y&&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:y.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Caption"}),e.jsx(or,{value:w,onChange:Ze=>b(Ze.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("flex-1 justify-start gap-2 font-normal",!N&&"text-muted-foreground"),children:[e.jsx(on,{className:"h-4 w-4"}),N?_s(new Date(N+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:N?new Date(N+"T00:00:00"):void 0,onSelect:Ze=>S(Ze?_s(Ze,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),N&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>S(null),children:e.jsx(vr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>v(null),children:"Cancel"}),e.jsx(G,{onClick:He,disabled:T,className:"gap-2",children:T?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Zts=()=>{const{toast:s}=Ma(),t=Xt(),[r,n]=k.useState("categories"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({name:"",description:"",icon:""}),[h,m]=k.useState(!1),[x,y]=k.useState(null),[v,w]=k.useState({name:"",description:"",icon:""}),[b,N]=k.useState(!1),[S,T]=k.useState(null),[A,I]=k.useState(""),{data:D=[],isLoading:R}=mt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Le,error:Ie}=await V.from("community_categories").select("*").order("sort_order");if(Ie)throw Ie;return Le}}),{data:$=[],isLoading:F}=mt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Le,error:Ie}=await V.from("community_private_groups").select("*").order("sort_order");if(Ie)throw Ie;return Le}}),{data:z=[]}=mt({queryKey:["admin-group-members",S==null?void 0:S.id],queryFn:async()=>{if(!S)return[];const{data:Le,error:Ie}=await V.from("community_private_group_members").select("*").eq("group_id",S.id);if(Ie)throw Ie;return Le},enabled:!!S}),{data:Q=[]}=mt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Ie=[],Te=0,xe=!0;for(;xe;){const{data:et,error:fe}=await V.from("profiles").select("id, name, email, brokerage_id").order("name").range(Te,Te+1e3-1);if(fe)throw fe;et&&et.length>0?(Ie=[...Ie,...et],Te+=1e3,xe=et.length===1e3):xe=!1}return Ie}}),{data:K=[]}=mt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Le,error:Ie}=await V.from("brokerages").select("*").order("name");if(Ie)throw Ie;return Le}}),X=Ct({mutationFn:async Le=>{if(Le.id){const{error:Ie}=await V.from("community_categories").update({name:Le.name,description:Le.description||null,icon:Le.icon||null}).eq("id",Le.id);if(Ie)throw Ie}else{const Ie=Math.max(...D.map(xe=>xe.sort_order),0),{error:Te}=await V.from("community_categories").insert({name:Le.name,description:Le.description||null,icon:Le.icon||null,sort_order:Ie+1});if(Te)throw Te}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Le=>{s({title:"Error",description:Le.message,variant:"destructive"})}}),Z=Ct({mutationFn:async Le=>{const{error:Ie}=await V.from("community_categories").delete().eq("id",Le);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),re=Ct({mutationFn:async({id:Le,direction:Ie})=>{const Te=D.findIndex(xe=>xe.id===Le);if(Ie==="up"&&Te>0){const xe=D[Te-1],et=D[Te];await V.from("community_categories").update({sort_order:et.sort_order}).eq("id",xe.id),await V.from("community_categories").update({sort_order:xe.sort_order}).eq("id",et.id)}else if(Ie==="down"&&Tet.invalidateQueries({queryKey:["admin-community-categories"]})}),le=Ct({mutationFn:async Le=>{if(Le.id){const{error:Ie}=await V.from("community_private_groups").update({name:Le.name,description:Le.description||null,icon:Le.icon||null}).eq("id",Le.id);if(Ie)throw Ie}else{const Ie=Math.max(...$.map(xe=>xe.sort_order),0),{error:Te}=await V.from("community_private_groups").insert({name:Le.name,description:Le.description||null,icon:Le.icon||null,sort_order:Ie+1});if(Te)throw Te}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),m(!1),y(null),w({name:"",description:"",icon:""}),s({title:x?"Private group updated!":"Private group created!"})},onError:Le=>{s({title:"Error",description:Le.message,variant:"destructive"})}}),oe=Ct({mutationFn:async Le=>{const{error:Ie}=await V.from("community_private_groups").delete().eq("id",Le);if(Ie)throw Ie},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ne=Ct({mutationFn:async({id:Le,direction:Ie})=>{const Te=$.findIndex(xe=>xe.id===Le);if(Ie==="up"&&Te>0){const xe=$[Te-1],et=$[Te];await V.from("community_private_groups").update({sort_order:et.sort_order}).eq("id",xe.id),await V.from("community_private_groups").update({sort_order:xe.sort_order}).eq("id",et.id)}else if(Ie==="down"&&Te<$.length-1){const xe=$[Te+1],et=$[Te];await V.from("community_private_groups").update({sort_order:et.sort_order}).eq("id",xe.id),await V.from("community_private_groups").update({sort_order:xe.sort_order}).eq("id",et.id)}},onSuccess:()=>t.invalidateQueries({queryKey:["admin-private-groups"]})}),ie=Ct({mutationFn:async({groupId:Le,userId:Ie,isMember:Te})=>{if(Te){const{error:xe}=await V.from("community_private_group_members").delete().eq("group_id",Le).eq("user_id",Ie);if(xe)throw xe}else{const{error:xe}=await V.from("community_private_group_members").insert({group_id:Le,user_id:Ie});if(xe)throw xe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",S==null?void 0:S.id]})}}),ye=Ct({mutationFn:async({groupId:Le,brokerageId:Ie,isMember:Te})=>{if(Te){const{error:xe}=await V.from("community_private_group_members").delete().eq("group_id",Le).eq("brokerage_id",Ie);if(xe)throw xe}else{const{error:xe}=await V.from("community_private_group_members").insert({group_id:Le,brokerage_id:Ie});if(xe)throw xe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",S==null?void 0:S.id]})}}),ce=Le=>{o(Le),d({name:Le.name,description:Le.description||"",icon:Le.icon||""}),i(!0)},ve=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},be=Le=>{y(Le),w({name:Le.name,description:Le.description||"",icon:Le.icon||""}),m(!0)},Ue=()=>{y(null),w({name:"",description:"",icon:""}),m(!0)},Be=Le=>{T(Le),I(""),N(!0)},De=Le=>z.some(Ie=>Ie.user_id===Le),Ae=Le=>z.some(Ie=>Ie.brokerage_id===Le),He=Q.filter(Le=>Le.name.toLowerCase().includes(A.toLowerCase())||Le.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(ws,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(On,{value:r,onValueChange:n,children:[e.jsxs(Rn,{children:[e.jsx(Kt,{value:"categories",children:"Public Categories"}),e.jsxs(Kt,{value:"private-groups",children:[e.jsx(Hc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(ts,{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(G,{onClick:ve,children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[50px]",children:"Order"}),e.jsx(Nt,{className:"w-[80px]",children:"Icon"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx($n,{children:R?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):D.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):D.map((Le,Ie)=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===0,onClick:()=>re.mutate({id:Le.id,direction:"up"}),children:"↑"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===D.length-1,onClick:()=>re.mutate({id:Le.id,direction:"down"}),children:"↓"})]})}),e.jsx(dt,{className:"text-2xl",children:Le.icon||"📁"}),e.jsx(dt,{className:"font-medium",children:Le.name}),e.jsx(dt,{className:"text-muted-foreground",children:Le.description||"—"}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ce(Le),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&Z.mutate(Le.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Le.id))})]})})})]}),e.jsxs(ts,{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(Sa,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(G,{onClick:Ue,children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[50px]",children:"Order"}),e.jsx(Nt,{className:"w-[80px]",children:"Icon"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{className:"w-[120px]",children:"Members"}),e.jsx(Nt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx($n,{children:F?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):$.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):$.map((Le,Ie)=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===0,onClick:()=>ne.mutate({id:Le.id,direction:"up"}),children:"↑"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ie===$.length-1,onClick:()=>ne.mutate({id:Le.id,direction:"down"}),children:"↓"})]})}),e.jsx(dt,{className:"text-2xl",children:Le.icon||"🔒"}),e.jsx(dt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Le.name,Le.brokerage_id?e.jsxs(Ge,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[e.jsx(Hc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(dt,{className:"text-muted-foreground",children:Le.description||"—"}),e.jsx(dt,{children:e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>Be(Le),children:[e.jsx(pr,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Le.brokerage_id&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>be(Le),children:e.jsx(Ea,{className:"h-4 w-4"})}),!Le.brokerage_id&&e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&oe.mutate(Le.id)},children:e.jsx(yr,{className:"h-4 w-4"})}),Le.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Le.id))})]})})})]})]}),e.jsx(fs,{open:a,onOpenChange:i,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{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(Ne,{value:c.icon,onChange:Le=>d(Ie=>({...Ie,icon:Le.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(Ne,{value:c.name,onChange:Le=>d(Ie=>({...Ie,name:Le.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(or,{value:c.description,onChange:Le=>d(Ie=>({...Ie,description:Le.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>X.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(fs,{open:h,onOpenChange:m,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:x?"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(Ne,{value:v.icon,onChange:Le=>w(Ie=>({...Ie,icon:Le.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(Ne,{value:v.name,onChange:Le=>w(Ie=>({...Ie,name:Le.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(or,{value:v.description,onChange:Le=>w(Ie=>({...Ie,description:Le.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>le.mutate({...v,id:x==null?void 0:x.id}),disabled:!v.name.trim(),children:x?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(fs,{open:b,onOpenChange:N,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Manage Members: ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(On,{defaultValue:"brokerages",children:[e.jsxs(Rn,{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(ts,{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(Qa,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[K.map(Le=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Si,{checked:Ae(Le.id),onCheckedChange:()=>{S&&ye.mutate({groupId:S.id,brokerageId:Le.id,isMember:Ae(Le.id)})}}),e.jsx("span",{className:"font-medium",children:Le.name})]}),e.jsxs(Ge,{variant:"secondary",children:[Q.filter(Ie=>Ie.brokerage_id===Le.id).length," agents"]})]},Le.id)),K.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(ts,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search users...",value:A,onChange:Le=>I(Le.target.value),className:"pl-9"})]}),e.jsx(Qa,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[He.map(Le=>e.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Si,{checked:De(Le.id),onCheckedChange:()=>{S&&ie.mutate({groupId:S.id,userId:Le.id,isMember:De(Le.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Le.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Le.email})]})]})},Le.id)),He.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(G,{onClick:()=>N(!1),children:"Done"})})]})]})})]})})},YBe=s=>{switch(s){case"academy_video":return e.jsx(Uo,{className:"h-3 w-3"});case"template":return e.jsx(ln,{className:"h-3 w-3"});case"toolbox":return e.jsx(Il,{className:"h-3 w-3"});case"newsletter":return e.jsx(iv,{className:"h-3 w-3"});case"social_swag":return e.jsx(jr,{className:"h-3 w-3"});default:return e.jsx(Qr,{className:"h-3 w-3"})}},Xts=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}},Qts=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}},Jts=()=>{const{toast:s}=Ma(),[t,r]=k.useState([]),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,h]=k.useState(""),[m,x]=k.useState(null),[y,v]=k.useState([]),[w,b]=k.useState([]);k.useEffect(()=>{N()},[]);const N=async()=>{try{c(!0);const{data:z,error:Q}=await V.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(Q)throw Q;const{data:K,error:X}=await V.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(X)throw X;const Z=[...new Set((K==null?void 0:K.map(ce=>ce.user_id))||[])],{data:re}=await V.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",Z),le=new Map((re==null?void 0:re.map(ce=>[ce.id,ce]))||[]),oe=(z==null?void 0:z.map(ce=>{var ve,be,Ue,Be;return{id:ce.id,user_id:ce.user_id,app_name:ce.app_name,launched_at:ce.launched_at,user_name:((ve=ce.profiles)==null?void 0:ve.name)||"Unknown",user_email:((be=ce.profiles)==null?void 0:be.email)||"Unknown",brokerage_name:((Be=(Ue=ce.profiles)==null?void 0:Ue.brokerages)==null?void 0:Be.name)||null}}))||[],ne=(K==null?void 0:K.map(ce=>{var be;const ve=le.get(ce.user_id);return{id:ce.id,user_id:ce.user_id,resource_type:ce.resource_type,resource_id:ce.resource_id,resource_title:ce.resource_title,action_type:ce.action_type,created_at:ce.created_at,user_name:(ve==null?void 0:ve.name)||"Unknown",user_email:(ve==null?void 0:ve.email)||"Unknown",brokerage_name:((be=ve==null?void 0:ve.brokerages)==null?void 0:be.name)||null}}))||[];r(oe),a(ne);const ie=new Map;oe.forEach(ce=>{if(!ie.has(ce.user_id))ie.set(ce.user_id,{user_id:ce.user_id,user_name:ce.user_name,user_email:ce.user_email,brokerage_name:ce.brokerage_name,last_activity_type:"app",last_activity_name:ce.app_name,last_activity_at:ce.launched_at,total_app_launches:1,total_content_views:0});else{const ve=ie.get(ce.user_id);ve.total_app_launches++,new Date(ce.launched_at)>new Date(ve.last_activity_at)&&(ve.last_activity_type="app",ve.last_activity_name=ce.app_name,ve.last_activity_at=ce.launched_at)}}),ne.forEach(ce=>{if(!ie.has(ce.user_id))ie.set(ce.user_id,{user_id:ce.user_id,user_name:ce.user_name,user_email:ce.user_email,brokerage_name:ce.brokerage_name,last_activity_type:ce.resource_type,last_activity_name:ce.resource_title,last_activity_at:ce.created_at,total_app_launches:0,total_content_views:1});else{const ve=ie.get(ce.user_id);ve.total_content_views++,new Date(ce.created_at)>new Date(ve.last_activity_at)&&(ve.last_activity_type=ce.resource_type,ve.last_activity_name=ce.resource_title,ve.last_activity_at=ce.created_at)}});const ye=Array.from(ie.values()).sort((ce,ve)=>new Date(ve.last_activity_at).getTime()-new Date(ce.last_activity_at).getTime());l(ye)}catch(z){console.error("Error loading activity:",z),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},S=z=>{x({id:z.user_id,name:z.user_name,email:z.user_email});const Q=t.filter(X=>X.user_id===z.user_id),K=n.filter(X=>X.user_id===z.user_id);v(Q),b(K)},T=()=>{x(null),v([]),b([])},{sortKey:A,sortDirection:I,handleSort:D,sortData:R}=bB("last_activity_at","desc"),$=i.filter(z=>{var K;if(!d)return!0;const Q=d.toLowerCase();return z.user_name.toLowerCase().includes(Q)||z.user_email.toLowerCase().includes(Q)||((K=z.brokerage_name)==null?void 0:K.toLowerCase().includes(Q))}),F=R($,{user:z=>{var Q;return((Q=z.user_name)==null?void 0:Q.toLowerCase())||""},brokerage:z=>{var Q;return((Q=z.brokerage_name)==null?void 0:Q.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(ke,{children:e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"User Activity"}),e.jsx(Nr,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:z=>h(z.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(El,{sortKey:"user",currentSortKey:A,currentDirection:I,onSort:D,children:"User"}),e.jsx(El,{sortKey:"brokerage",currentSortKey:A,currentDirection:I,onSort:D,children:"Brokerage"}),e.jsx(Nt,{children:"Last Activity"}),e.jsx(El,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:I,onSort:D,children:"Last Active"}),e.jsx(El,{sortKey:"apps",currentSortKey:A,currentDirection:I,onSort:D,className:"text-right",children:"Apps"}),e.jsx(El,{sortKey:"content",currentSortKey:A,currentDirection:I,onSort:D,className:"text-right",children:"Content"})]})}),e.jsx($n,{children:F.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):F.map(z=>e.jsxs(Ds,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>S(z),children:[e.jsx(dt,{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(dt,{children:z.brokerage_name?e.jsx(Ge,{variant:"outline",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(dt,{children:e.jsx("div",{className:"flex items-center gap-2",children:z.last_activity_type==="app"?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(Qr,{className:"h-3 w-3 mr-1"}),z.last_activity_name]}):e.jsxs(Ge,{variant:"outline",className:"flex items-center gap-1",children:[YBe(z.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:z.last_activity_name})]})})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:rl(new Date(z.last_activity_at),{addSuffix:!0})}),e.jsx(dt,{className:"text-right",children:e.jsx(Ge,{variant:"outline",children:z.total_app_launches})}),e.jsx(dt,{className:"text-right",children:e.jsx(Ge,{variant:"outline",children:z.total_content_views})})]},z.user_id))})]})})]})]}),e.jsx(fs,{open:!!m,onOpenChange:z=>!z&&T(),children:e.jsxs(ms,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:[m==null?void 0:m.name,"'s Activity"]}),e.jsx(Hr,{children:m==null?void 0:m.email})]}),e.jsxs(On,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"content",children:["Content (",w.length,")"]}),e.jsxs(Kt,{value:"apps",children:["App Launches (",y.length,")"]})]}),e.jsx(ts,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Resource"}),e.jsx(Nt,{children:"Action"}),e.jsx(Nt,{children:"Time"})]})}),e.jsx($n,{children:w.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):w.map(z=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs(Ge,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[YBe(z.resource_type),Xts(z.resource_type)]})}),e.jsx(dt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:z.resource_title})}),e.jsx(dt,{children:e.jsx(Ge,{variant:"secondary",children:Qts(z.action_type)})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:rl(new Date(z.created_at),{addSuffix:!0})})]},z.id))})]})})}),e.jsx(ts,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"App"}),e.jsx(Nt,{children:"Time"})]})}),e.jsx($n,{children:y.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):y.map(z=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx(Ge,{variant:"secondary",children:z.app_name})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:rl(new Date(z.launched_at),{addSuffix:!0})})]},z.id))})]})})})]})]})})]})},ess=()=>{const{toast:s}=Ma(),[t,r]=k.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[n,a]=k.useState(!0);k.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await V.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await V.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await V.from("brokerages").select("*",{count:"exact",head:!0}),{count:h}=await V.from("activity_logs").select("*",{count:"exact",head:!0}),m=new Date;m.setDate(m.getDate()-7);const{count:x}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",m.toISOString()),y=new Date;y.setMonth(y.getMonth()-1);const{count:v}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",y.toISOString()),{data:w}=await V.from("activity_logs").select("user_id").gte("launched_at",m.toISOString()),b=new Set(w==null?void 0:w.map(N=>N.user_id)).size;r({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:h||0,launchesThisWeek:x||0,launchesThisMonth:v||0,uniqueActiveThisWeek:b})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return n?e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(fn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(vh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(vh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(vh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(bo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},ZBe={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},XBe={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 ylt({brokerageOnly:s=!1,brokerageId:t}){const[r,n]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(""),[c,d]=k.useState("all");k.useEffect(()=>{h()},[t]);const h=async()=>{i(!0);try{let D=[];if(s&&t){const{data:Z}=await V.from("profiles").select("id").eq("brokerage_id",t);if(D=(Z==null?void 0:Z.map(re=>re.id))||[],D.length===0){n([]),i(!1);return}}let R=V.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&D.length>0&&(R=R.or(`sender_id.in.(${D.join(",")}),recipient_id.in.(${D.join(",")})`));const{data:$,error:F}=await R;if(F)throw F;const z=new Set;$==null||$.forEach(Z=>{z.add(Z.sender_id),z.add(Z.recipient_id)});const{data:Q}=await V.from("profiles").select("id, name, email").in("id",Array.from(z)),K=new Map((Q==null?void 0:Q.map(Z=>[Z.id,Z]))||[]),X=($==null?void 0:$.map(Z=>({...Z,sender:K.get(Z.sender_id),recipient:K.get(Z.recipient_id)})))||[];n(X)}catch(D){console.error("Error loading shares:",D)}finally{i(!1)}},{sortKey:m,sortDirection:x,handleSort:y,sortData:v}=bB("created_at","desc"),w=r.filter(D=>{var F,z;const R=l===""||D.resource_title.toLowerCase().includes(l.toLowerCase())||((F=D.sender)==null?void 0:F.name.toLowerCase().includes(l.toLowerCase()))||((z=D.recipient)==null?void 0:z.name.toLowerCase().includes(l.toLowerCase())),$=c==="all"||D.resource_type===c;return R&&$}),b=v(w,{resource:D=>{var R;return((R=D.resource_title)==null?void 0:R.toLowerCase())||""},type:D=>D.resource_type,sender:D=>{var R,$;return(($=(R=D.sender)==null?void 0:R.name)==null?void 0:$.toLowerCase())||""},recipient:D=>{var R,$;return(($=(R=D.recipient)==null?void 0:R.name)==null?void 0:$.toLowerCase())||""},status:D=>D.is_read?1:0,created_at:D=>new Date(D.created_at).getTime()}),N=r.length,S=new Set(r.map(D=>D.sender_id)).size,T=new Set(r.map(D=>D.recipient_id)).size,A=r.length>0?Math.round(r.filter(D=>D.is_read).length/r.length*100):0,I=r.reduce((D,R)=>(D[R.resource_type]=(D[R.resource_type]||0)+1,D),{});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((D,R)=>e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Fs,{className:"h-4 w-20"})}),e.jsx(Pe,{children:e.jsx(Fs,{className:"h-8 w-16"})})]},R))}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-6",children:e.jsx(Fs,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Ec,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:N})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:S})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(bo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:T})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(I).map(([D,R])=>e.jsxs(Ge,{variant:"secondary",className:XBe[D],children:[ZBe[D],": ",R]},D)),Object.keys(I).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Share History"}),e.jsxs(Nr,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Pe,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:D=>o(D.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:c,onValueChange:d,children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"Resource type"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),e.jsx(ct,{value:"event",children:"Events"}),e.jsx(ct,{value:"template",children:"Templates"}),e.jsx(ct,{value:"academy_video",children:"Academy Videos"}),e.jsx(ct,{value:"resource_kit",children:"Resource Kits"}),e.jsx(ct,{value:"newsletter",children:"Newsletters"}),e.jsx(ct,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Qa,{className:"h-[400px]",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(El,{sortKey:"resource",currentSortKey:m,currentDirection:x,onSort:y,children:"Resource"}),e.jsx(El,{sortKey:"type",currentSortKey:m,currentDirection:x,onSort:y,children:"Type"}),e.jsx(El,{sortKey:"sender",currentSortKey:m,currentDirection:x,onSort:y,children:"Sender"}),e.jsx(El,{sortKey:"recipient",currentSortKey:m,currentDirection:x,onSort:y,children:"Recipient"}),e.jsx(El,{sortKey:"status",currentSortKey:m,currentDirection:x,onSort:y,children:"Status"}),e.jsx(El,{sortKey:"created_at",currentSortKey:m,currentDirection:x,onSort:y,children:"Date"})]})}),e.jsx($n,{children:b.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):b.map(D=>{var R,$;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium max-w-[200px] truncate",children:D.resource_title}),e.jsx(dt,{children:e.jsx(Ge,{variant:"secondary",className:XBe[D.resource_type],children:ZBe[D.resource_type]})}),e.jsx(dt,{children:((R=D.sender)==null?void 0:R.name)||"Unknown"}),e.jsx(dt,{children:(($=D.recipient)==null?void 0:$.name)||"Unknown"}),e.jsx(dt,{children:e.jsx(Ge,{variant:D.is_read?"default":"outline",children:D.is_read?"Read":"Unread"})}),e.jsx(dt,{className:"text-muted-foreground",children:_s(new Date(D.created_at),"MMM d, yyyy")})]},D.id)})})]})})]})]})]})}const P1e={academy_video:{label:"Academy Videos",icon:Jr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:bn},template:{label:"Templates",icon:Y1,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:Bu},toolbox:{label:"Toolkit",icon:Ay,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:Ya},newsletter:{label:"Newsletters",icon:Vs,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:Bu},social_swag:{label:"Social Swag",icon:fl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:Bu},event:{label:"Events",icon:on,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:Bu}};function QBe(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function tss(s,t){return s==="toolbox"?t.downloads:t.clicks}function sss(){var D;const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(null),l=k.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:h}=bB("total_views","desc");k.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:R,error:$}=await V.rpc("get_admin_content_engagement");if($)throw $;t(R||[])}catch(R){console.error("Error loading content engagement:",R)}finally{n(!1)}},x=R=>{i($=>{const F=$===R?null:R;return requestAnimationFrame(()=>{var z;(z=l.current)==null||z.scrollIntoView({behavior:"smooth",block:"start"})}),F})};if(r)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((R,$)=>e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Fs,{className:"h-4 w-20"})}),e.jsx(Pe,{children:e.jsx(Fs,{className:"h-8 w-16"})})]},$))}),e.jsx(ke,{children:e.jsx(Pe,{className:"py-8",children:e.jsx(Fs,{className:"h-64 w-full"})})})]});const y=s.reduce((R,$)=>R+$.total_views,0),v=s.reduce((R,$)=>R+$.total_clicks,0),w=s.reduce((R,$)=>R+$.total_downloads,0),b=s.length,N=s.reduce((R,$)=>(R[$.resource_type]||(R[$.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),R[$.resource_type].views+=$.total_views,R[$.resource_type].clicks+=$.total_clicks,R[$.resource_type].downloads+=$.total_downloads,R[$.resource_type].assets+=1,R[$.resource_type].uniqueUsers+=$.unique_users,R),{}),S=a?s.filter(R=>R.resource_type===a):s,T=h(S,{asset:R=>{var $;return(($=R.resource_title)==null?void 0:$.toLowerCase())||""},type:R=>R.resource_type,views:R=>R.total_views,actions:R=>QBe(R),unique_users:R=>R.unique_users,last_activity:R=>R.last_engaged_at?new Date(R.last_engaged_at).getTime():0}),A=a?P1e[a]||{label:a,icon:bn,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Bu}:null,I=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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(Bu,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:w.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(bo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Bu,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[y>0?Math.round((v+w)/y*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Nr,{children:"Click a category to see individual asset performance"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(N).map(([R,$])=>{const F=P1e[R]||{label:R,icon:bn,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Bu},z=F.icon,Q=a===R;return e.jsxs("button",{type:"button",onClick:()=>x(R),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${Q?"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(bn,{className:"h-3 w-3"})," ",$.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(F.actionIcon,{className:"h-3 w-3"})," ",tss(R,$)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"})," ",$.uniqueUsers]})]})]}),e.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[$.assets," items"]})]},R)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{className:"text-sm font-medium flex items-center gap-2",children:A&&I?e.jsxs(e.Fragment,{children:[e.jsx(I,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Nr,{children:a?`${S.length} ${((D=A==null?void 0:A.label)==null?void 0:D.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Pe,{children:S.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(Qa,{className:"h-[400px]",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[40px]",children:"#"}),e.jsx(El,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(El,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(El,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(El,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(El,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(El,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx($n,{children:T.map((R,$)=>{const F=P1e[R.resource_type]||{label:R.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Bu};return e.jsxs(Ds,{children:[e.jsx(dt,{className:"text-muted-foreground text-xs",children:$+1}),e.jsx(dt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:R.resource_title})}),!a&&e.jsx(dt,{children:e.jsx(Ge,{className:`text-[10px] ${F.color}`,children:F.label})}),e.jsx(dt,{className:"text-right font-medium",children:R.total_views}),e.jsx(dt,{className:"text-right font-medium",children:QBe(R)}),e.jsx(dt,{className:"text-right",children:R.unique_users}),e.jsx(dt,{className:"text-xs text-muted-foreground",children:R.last_engaged_at?rl(new Date(R.last_engaged_at),{addSuffix:!0}):"—"})]},`${R.resource_type}-${R.resource_id}`)})})]})})})]})})]})}var rss=Array.isArray,ip=rss,nss=typeof Zd=="object"&&Zd&&Zd.Object===Object&&Zd,vlt=nss,ass=vlt,iss=typeof self=="object"&&self&&self.Object===Object&&self,oss=ass||iss||Function("return this")(),Fv=oss,lss=Fv,css=lss.Symbol,SB=css,JBe=SB,blt=Object.prototype,dss=blt.hasOwnProperty,uss=blt.toString,aD=JBe?JBe.toStringTag:void 0;function hss(s){var t=dss.call(s,aD),r=s[aD];try{s[aD]=void 0;var n=!0}catch{}var a=uss.call(s);return n&&(t?s[aD]=r:delete s[aD]),a}var mss=hss,fss=Object.prototype,pss=fss.toString;function xss(s){return pss.call(s)}var gss=xss,eze=SB,yss=mss,vss=gss,bss="[object Null]",_ss="[object Undefined]",tze=eze?eze.toStringTag:void 0;function wss(s){return s==null?s===void 0?_ss:bss:tze&&tze in Object(s)?yss(s):vss(s)}var Gb=wss;function jss(s){return s!=null&&typeof s=="object"}var Wb=jss,Nss=Gb,kss=Wb,Sss="[object Symbol]";function Css(s){return typeof s=="symbol"||kss(s)&&Nss(s)==Sss}var sL=Css,Tss=ip,Ess=sL,Ass=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Mss=/^\w*$/;function Iss(s,t){if(Tss(s))return!1;var r=typeof s;return r=="number"||r=="symbol"||r=="boolean"||s==null||Ess(s)?!0:Mss.test(s)||!Ass.test(s)||t!=null&&s in Object(t)}var _5e=Iss;function Lss(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var o2=Lss;const rL=Ao(o2);var Pss=Gb,Dss=o2,Rss="[object AsyncFunction]",Oss="[object Function]",Fss="[object GeneratorFunction]",Bss="[object Proxy]";function zss(s){if(!Dss(s))return!1;var t=Pss(s);return t==Oss||t==Fss||t==Rss||t==Bss}var w5e=zss;const ki=Ao(w5e);var $ss=Fv,Uss=$ss["__core-js_shared__"],qss=Uss,D1e=qss,sze=function(){var s=/[^.]+$/.exec(D1e&&D1e.keys&&D1e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function Vss(s){return!!sze&&sze in s}var Hss=Vss,Gss=Function.prototype,Wss=Gss.toString;function Kss(s){if(s!=null){try{return Wss.call(s)}catch{}try{return s+""}catch{}}return""}var _lt=Kss,Yss=w5e,Zss=Hss,Xss=o2,Qss=_lt,Jss=/[\\^$.*+?()[\]{}|]/g,ers=/^\[object .+?Constructor\]$/,trs=Function.prototype,srs=Object.prototype,rrs=trs.toString,nrs=srs.hasOwnProperty,ars=RegExp("^"+rrs.call(nrs).replace(Jss,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function irs(s){if(!Xss(s)||Zss(s))return!1;var t=Yss(s)?ars:ers;return t.test(Qss(s))}var ors=irs;function lrs(s,t){return s==null?void 0:s[t]}var crs=lrs,drs=ors,urs=crs;function hrs(s,t){var r=urs(s,t);return drs(r)?r:void 0}var c5=hrs,mrs=c5,frs=mrs(Object,"create"),Npe=frs,rze=Npe;function prs(){this.__data__=rze?rze(null):{},this.size=0}var xrs=prs;function grs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var yrs=grs,vrs=Npe,brs="__lodash_hash_undefined__",_rs=Object.prototype,wrs=_rs.hasOwnProperty;function jrs(s){var t=this.__data__;if(vrs){var r=t[s];return r===brs?void 0:r}return wrs.call(t,s)?t[s]:void 0}var Nrs=jrs,krs=Npe,Srs=Object.prototype,Crs=Srs.hasOwnProperty;function Trs(s){var t=this.__data__;return krs?t[s]!==void 0:Crs.call(t,s)}var Ers=Trs,Ars=Npe,Mrs="__lodash_hash_undefined__";function Irs(s,t){var r=this.__data__;return this.size+=this.has(s)?0:1,r[s]=Ars&&t===void 0?Mrs:t,this}var Lrs=Irs,Prs=xrs,Drs=yrs,Rrs=Nrs,Ors=Ers,Frs=Lrs;function nL(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t-1}var tns=ens,sns=kpe;function rns(s,t){var r=this.__data__,n=sns(r,s);return n<0?(++this.size,r.push([s,t])):r[n][1]=t,this}var nns=rns,ans=$rs,ins=Yrs,ons=Qrs,lns=tns,cns=nns;function aL(s){var t=-1,r=s==null?0:s.length;for(this.clear();++t0?1:-1},c4=function(t){return U3(t)&&t.indexOf("%")===t.length-1},Sn=function(t){return Mas(t)&&!CB(t)},Das=function(t){return Pi(t)},qu=function(t){return Sn(t)||U3(t)},Ras=0,oL=function(t){var r=++Ras;return"".concat(t||"").concat(r)},hf=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Sn(t)&&!U3(t))return n;var i;if(c4(t)){var l=t.indexOf("%");i=r*parseFloat(t.slice(0,l))/100}else i=+t;return CB(i)&&(i=n),a&&i>r&&(i=r),i},vw=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},Oas=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Vas(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function O2e(s){"@babel/helpers - typeof";return O2e=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},O2e(s)}var dze={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"},_b=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},uze=null,O1e=null,I5e=function s(t){if(t===uze&&Array.isArray(O1e))return O1e;var r=[];return k.Children.forEach(t,function(n){Pi(n)||(Sas.isFragment(n)?r=r.concat(s(n.props.children)):r.push(n))}),O1e=r,uze=t,r};function Xp(s,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(a){return _b(a)}):n=[_b(t)],I5e(s).forEach(function(a){var i=Zp(a,"type.displayName")||Zp(a,"type.name");n.indexOf(i)!==-1&&r.push(a)}),r}function Mp(s,t){var r=Xp(s,t);return r&&r[0]}var hze=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,a=r.height;return!(!Sn(n)||n<=0||!Sn(a)||a<=0)},Has=["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"],Gas=function(t){return t&&t.type&&U3(t.type)&&Has.indexOf(t.type)>=0},Was=function(t){return t&&O2e(t)==="object"&&"clipDot"in t},Kas=function(t,r,n,a){var i,l=(i=R1e==null?void 0:R1e[a])!==null&&i!==void 0?i:[];return r.startsWith("data-")||!ki(t)&&(a&&l.includes(r)||zas.includes(r))||n&&M5e.includes(r)},ai=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(k.isValidElement(t)&&(a=t.props),!rL(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;Kas((o=a)===null||o===void 0?void 0:o[l],l,r,n)&&(i[l]=a[l])}),i},F2e=function s(t,r){if(t===r)return!0;var n=k.Children.count(t);if(n!==k.Children.count(r))return!1;if(n===0)return!0;if(n===1)return mze(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Jas(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function z2e(s){var t=s.children,r=s.width,n=s.height,a=s.viewBox,i=s.className,l=s.style,o=s.title,c=s.desc,d=Qas(s,Xas),h=a||{width:r,height:n,x:0,y:0},m=Fi("recharts-surface",i);return wt.createElement("svg",B2e({},ai(d,!0,"svg"),{className:m,width:r,height:n,style:l,viewBox:"".concat(h.x," ").concat(h.y," ").concat(h.width," ").concat(h.height)}),wt.createElement("title",null,o),wt.createElement("desc",null,c),t)}var eis=["children","className"];function $2e(){return $2e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function sis(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var Jo=wt.forwardRef(function(s,t){var r=s.children,n=s.className,a=tis(s,eis),i=Fi("recharts-layer",n);return wt.createElement("g",$2e({className:i},ai(a,!0),{ref:t}),r)}),Iy=function(t,r){for(var n=arguments.length,a=new Array(n>2?n-2:0),i=2;ia?0:a+t),r=r>a?a:r,r<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var i=Array(a);++n=n?s:ais(s,t,r)}var ois=iis,lis="\\ud800-\\udfff",cis="\\u0300-\\u036f",dis="\\ufe20-\\ufe2f",uis="\\u20d0-\\u20ff",his=cis+dis+uis,mis="\\ufe0e\\ufe0f",fis="\\u200d",pis=RegExp("["+fis+lis+his+mis+"]");function xis(s){return pis.test(s)}var Mlt=xis;function gis(s){return s.split("")}var yis=gis,Ilt="\\ud800-\\udfff",vis="\\u0300-\\u036f",bis="\\ufe20-\\ufe2f",_is="\\u20d0-\\u20ff",wis=vis+bis+_is,jis="\\ufe0e\\ufe0f",Nis="["+Ilt+"]",U2e="["+wis+"]",q2e="\\ud83c[\\udffb-\\udfff]",kis="(?:"+U2e+"|"+q2e+")",Llt="[^"+Ilt+"]",Plt="(?:\\ud83c[\\udde6-\\uddff]){2}",Dlt="[\\ud800-\\udbff][\\udc00-\\udfff]",Sis="\\u200d",Rlt=kis+"?",Olt="["+jis+"]?",Cis="(?:"+Sis+"(?:"+[Llt,Plt,Dlt].join("|")+")"+Olt+Rlt+")*",Tis=Olt+Rlt+Cis,Eis="(?:"+[Llt+U2e+"?",U2e,Plt,Dlt,Nis].join("|")+")",Ais=RegExp(q2e+"(?="+q2e+")|"+Eis+Tis,"g");function Mis(s){return s.match(Ais)||[]}var Iis=Mis,Lis=yis,Pis=Mlt,Dis=Iis;function Ris(s){return Pis(s)?Dis(s):Lis(s)}var Ois=Ris,Fis=ois,Bis=Mlt,zis=Ois,$is=klt;function Uis(s){return function(t){t=$is(t);var r=Bis(t)?zis(t):void 0,n=r?r[0]:t.charAt(0),a=r?Fis(r,1).join(""):t.slice(1);return n[s]()+a}}var qis=Uis,Vis=qis,His=Vis("toUpperCase"),Gis=His;const Bpe=Ao(Gis);function oc(s){return function(){return s}}const Flt=Math.cos,Gue=Math.sin,qy=Math.sqrt,Wue=Math.PI,zpe=2*Wue,V2e=Math.PI,H2e=2*V2e,UC=1e-6,Wis=H2e-UC;function Blt(s){this._+=s[0];for(let t=1,r=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return Blt;const r=10**t;return function(n){this._+=n[0];for(let a=1,i=n.length;aUC)if(!(Math.abs(m*c-d*h)>UC)||!i)this._append`L${this._x1=t},${this._y1=r}`;else{let y=n-l,v=a-o,w=c*c+d*d,b=y*y+v*v,N=Math.sqrt(w),S=Math.sqrt(x),T=i*Math.tan((V2e-Math.acos((w+x-b)/(2*N*S)))/2),A=T/S,I=T/N;Math.abs(A-1)>UC&&this._append`L${t+A*h},${r+A*m}`,this._append`A${i},${i},0,0,${+(m*y>h*v)},${this._x1=t+I*c},${this._y1=r+I*d}`}}arc(t,r,n,a,i,l){if(t=+t,r=+r,n=+n,l=!!l,n<0)throw new Error(`negative radius: ${n}`);let o=n*Math.cos(a),c=n*Math.sin(a),d=t+o,h=r+c,m=1^l,x=l?a-i:i-a;this._x1===null?this._append`M${d},${h}`:(Math.abs(this._x1-d)>UC||Math.abs(this._y1-h)>UC)&&this._append`L${d},${h}`,n&&(x<0&&(x=x%H2e+H2e),x>Wis?this._append`A${n},${n},0,1,${m},${t-o},${r-c}A${n},${n},0,1,${m},${this._x1=d},${this._y1=h}`:x>UC&&this._append`A${n},${n},0,${+(x>=V2e)},${m},${this._x1=t+n*Math.cos(i)},${this._y1=r+n*Math.sin(i)}`)}rect(t,r,n,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+a}h${-n}Z`}toString(){return this._}}function L5e(s){let t=3;return s.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return s},()=>new Yis(t)}function P5e(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function zlt(s){this._context=s}zlt.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 $pe(s){return new zlt(s)}function $lt(s){return s[0]}function Ult(s){return s[1]}function qlt(s,t){var r=oc(!0),n=null,a=$pe,i=null,l=L5e(o);s=typeof s=="function"?s:s===void 0?$lt:oc(s),t=typeof t=="function"?t:t===void 0?Ult:oc(t);function o(c){var d,h=(c=P5e(c)).length,m,x=!1,y;for(n==null&&(i=a(y=l())),d=0;d<=h;++d)!(d=y;--v)o.point(T[v],A[v]);o.lineEnd(),o.areaEnd()}N&&(T[x]=+s(b,x,m),A[x]=+t(b,x,m),o.point(n?+n(b,x,m):T[x],r?+r(b,x,m):A[x]))}if(S)return o=null,S+""||null}function h(){return qlt().defined(a).curve(l).context(i)}return d.x=function(m){return arguments.length?(s=typeof m=="function"?m:oc(+m),n=null,d):s},d.x0=function(m){return arguments.length?(s=typeof m=="function"?m:oc(+m),d):s},d.x1=function(m){return arguments.length?(n=m==null?null:typeof m=="function"?m:oc(+m),d):n},d.y=function(m){return arguments.length?(t=typeof m=="function"?m:oc(+m),r=null,d):t},d.y0=function(m){return arguments.length?(t=typeof m=="function"?m:oc(+m),d):t},d.y1=function(m){return arguments.length?(r=m==null?null:typeof m=="function"?m:oc(+m),d):r},d.lineX0=d.lineY0=function(){return h().x(s).y(t)},d.lineY1=function(){return h().x(s).y(r)},d.lineX1=function(){return h().x(n).y(t)},d.defined=function(m){return arguments.length?(a=typeof m=="function"?m:oc(!!m),d):a},d.curve=function(m){return arguments.length?(l=m,i!=null&&(o=l(i)),d):l},d.context=function(m){return arguments.length?(m==null?i=o=null:o=l(i=m),d):i},d}class Vlt{constructor(t,r){this._context=t,this._x=r}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,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function Zis(s){return new Vlt(s,!0)}function Xis(s){return new Vlt(s,!1)}const D5e={draw(s,t){const r=qy(t/Wue);s.moveTo(r,0),s.arc(0,0,r,0,zpe)}},Qis={draw(s,t){const r=qy(t/5)/2;s.moveTo(-3*r,-r),s.lineTo(-r,-r),s.lineTo(-r,-3*r),s.lineTo(r,-3*r),s.lineTo(r,-r),s.lineTo(3*r,-r),s.lineTo(3*r,r),s.lineTo(r,r),s.lineTo(r,3*r),s.lineTo(-r,3*r),s.lineTo(-r,r),s.lineTo(-3*r,r),s.closePath()}},Hlt=qy(1/3),Jis=Hlt*2,eos={draw(s,t){const r=qy(t/Jis),n=r*Hlt;s.moveTo(0,-r),s.lineTo(n,0),s.lineTo(0,r),s.lineTo(-n,0),s.closePath()}},tos={draw(s,t){const r=qy(t),n=-r/2;s.rect(n,n,r,r)}},sos=.8908130915292852,Glt=Gue(Wue/10)/Gue(7*Wue/10),ros=Gue(zpe/10)*Glt,nos=-Flt(zpe/10)*Glt,aos={draw(s,t){const r=qy(t*sos),n=ros*r,a=nos*r;s.moveTo(0,-r),s.lineTo(n,a);for(let i=1;i<5;++i){const l=zpe*i/5,o=Flt(l),c=Gue(l);s.lineTo(c*r,-o*r),s.lineTo(o*n-c*a,c*n+o*a)}s.closePath()}},F1e=qy(3),ios={draw(s,t){const r=-qy(t/(F1e*3));s.moveTo(0,r*2),s.lineTo(-F1e*r,-r),s.lineTo(F1e*r,-r),s.closePath()}},Ix=-.5,Lx=qy(3)/2,G2e=1/qy(12),oos=(G2e/2+1)*3,los={draw(s,t){const r=qy(t/oos),n=r/2,a=r*G2e,i=n,l=r*G2e+r,o=-i,c=l;s.moveTo(n,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(Ix*n-Lx*a,Lx*n+Ix*a),s.lineTo(Ix*i-Lx*l,Lx*i+Ix*l),s.lineTo(Ix*o-Lx*c,Lx*o+Ix*c),s.lineTo(Ix*n+Lx*a,Ix*a-Lx*n),s.lineTo(Ix*i+Lx*l,Ix*l-Lx*i),s.lineTo(Ix*o+Lx*c,Ix*c-Lx*o),s.closePath()}};function cos(s,t){let r=null,n=L5e(a);s=typeof s=="function"?s:oc(s||D5e),t=typeof t=="function"?t:oc(t===void 0?64:+t);function a(){let i;if(r||(r=i=n()),s.apply(this,arguments).draw(r,+t.apply(this,arguments)),i)return r=null,i+""||null}return a.type=function(i){return arguments.length?(s=typeof i=="function"?i:oc(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:oc(+i),a):t},a.context=function(i){return arguments.length?(r=i??null,a):r},a}function Kue(){}function Yue(s,t,r){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+r)/6)}function Wlt(s){this._context=s}Wlt.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:Yue(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:Yue(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function dos(s){return new Wlt(s)}function Klt(s){this._context=s}Klt.prototype={areaStart:Kue,areaEnd:Kue,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:Yue(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function uos(s){return new Klt(s)}function Ylt(s){this._context=s}Ylt.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 r=(this._x0+4*this._x1+s)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:Yue(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function hos(s){return new Ylt(s)}function Zlt(s){this._context=s}Zlt.prototype={areaStart:Kue,areaEnd:Kue,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 mos(s){return new Zlt(s)}function pze(s){return s<0?-1:1}function xze(s,t,r){var n=s._x1-s._x0,a=t-s._x1,i=(s._y1-s._y0)/(n||a<0&&-0),l=(r-s._y1)/(a||n<0&&-0),o=(i*a+l*n)/(n+a);return(pze(i)+pze(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function gze(s,t){var r=s._x1-s._x0;return r?(3*(s._y1-s._y0)/r-t)/2:t}function B1e(s,t,r){var n=s._x0,a=s._y0,i=s._x1,l=s._y1,o=(i-n)/3;s._context.bezierCurveTo(n+o,a+o*t,i-o,l-o*r,i,l)}function Zue(s){this._context=s}Zue.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:B1e(this,this._t0,gze(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 r=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,B1e(this,gze(this,r=xze(this,s,t)),r);break;default:B1e(this,this._t0,r=xze(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=r}}};function Xlt(s){this._context=new Qlt(s)}(Xlt.prototype=Object.create(Zue.prototype)).point=function(s,t){Zue.prototype.point.call(this,t,s)};function Qlt(s){this._context=s}Qlt.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,r,n,a,i){this._context.bezierCurveTo(t,s,n,r,i,a)}};function fos(s){return new Zue(s)}function pos(s){return new Xlt(s)}function Jlt(s){this._context=s}Jlt.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,r=s.length;if(r)if(this._line?this._context.lineTo(s[0],t[0]):this._context.moveTo(s[0],t[0]),r===2)this._context.lineTo(s[1],t[1]);else for(var n=yze(s),a=yze(t),i=0,l=1;l=0;--t)a[t]=(l[t]-a[t+1])/i[t];for(i[r-1]=(s[r]+a[r-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 r=this._x*(1-this._t)+s*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=s,this._y=t}};function gos(s){return new Upe(s,.5)}function yos(s){return new Upe(s,0)}function vos(s){return new Upe(s,1)}function UM(s,t){if((l=s.length)>1)for(var r=1,n,a,i=s[t[0]],l,o=i.length;r=0;)r[t]=t;return r}function bos(s,t){return s[t]}function _os(s){const t=[];return t.key=s,t}function wos(){var s=oc([]),t=W2e,r=UM,n=bos;function a(i){var l=Array.from(s.apply(this,arguments),_os),o,c=l.length,d=-1,h;for(const m of i)for(o=0,++d;o0){for(var r,n,a=0,i=s[0].length,l;a0){for(var r=0,n=s[t[0]],a,i=n.length;r0)||!((i=(a=s[t[0]]).length)>0))){for(var r=0,n=1,a,i,l;n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Mos(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var ect={symbolCircle:D5e,symbolCross:Qis,symbolDiamond:eos,symbolSquare:tos,symbolStar:aos,symbolTriangle:ios,symbolWye:los},Ios=Math.PI/180,Los=function(t){var r="symbol".concat(Bpe(t));return ect[r]||D5e},Pos=function(t,r,n){if(r==="area")return t;switch(n){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*Ios;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}},Dos=function(t,r){ect["symbol".concat(Bpe(t))]=r},R5e=function(t){var r=t.type,n=r===void 0?"circle":r,a=t.size,i=a===void 0?64:a,l=t.sizeType,o=l===void 0?"area":l,c=Aos(t,Sos),d=bze(bze({},c),{},{type:n,size:i,sizeType:o}),h=function(){var b=Los(n),N=cos().type(b).size(Pos(i,o,n));return N()},m=d.className,x=d.cx,y=d.cy,v=ai(d,!0);return x===+x&&y===+y&&i===+i?wt.createElement("path",K2e({},v,{className:Fi("recharts-symbols",m),transform:"translate(".concat(x,", ").concat(y,")"),d:h()})):null};R5e.registerSymbol=Dos;function qM(s){"@babel/helpers - typeof";return qM=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},qM(s)}function Y2e(){return Y2e=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var S=y.inactive?d:y.color;return wt.createElement("li",Y2e({className:b,style:m,key:"legend-item-".concat(v)},q3(n.props,y,v)),wt.createElement(z2e,{width:l,height:l,viewBox:h,style:x},n.renderIcon(y)),wt.createElement("span",{className:"recharts-legend-item-text",style:{color:S}},w?w(N,y,v):N))})}},{key:"render",value:function(){var n=this.props,a=n.payload,i=n.layout,l=n.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return wt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(k.PureComponent);B8(O5e,"displayName","Legend");B8(O5e,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var Hos=Spe;function Gos(){this.__data__=new Hos,this.size=0}var Wos=Gos;function Kos(s){var t=this.__data__,r=t.delete(s);return this.size=t.size,r}var Yos=Kos;function Zos(s){return this.__data__.get(s)}var Xos=Zos;function Qos(s){return this.__data__.has(s)}var Jos=Qos,els=Spe,tls=N5e,sls=k5e,rls=200;function nls(s,t){var r=this.__data__;if(r instanceof els){var n=r.__data__;if(!tls||n.lengtho))return!1;var d=i.get(s),h=i.get(t);if(d&&h)return d==t&&h==s;var m=-1,x=!0,y=r&Sls?new wls:void 0;for(i.set(s,t),i.set(t,s);++m-1&&s%1==0&&s-1&&s%1==0&&s<=Acs}var $5e=Mcs,Ics=Gb,Lcs=$5e,Pcs=Wb,Dcs="[object Arguments]",Rcs="[object Array]",Ocs="[object Boolean]",Fcs="[object Date]",Bcs="[object Error]",zcs="[object Function]",$cs="[object Map]",Ucs="[object Number]",qcs="[object Object]",Vcs="[object RegExp]",Hcs="[object Set]",Gcs="[object String]",Wcs="[object WeakMap]",Kcs="[object ArrayBuffer]",Ycs="[object DataView]",Zcs="[object Float32Array]",Xcs="[object Float64Array]",Qcs="[object Int8Array]",Jcs="[object Int16Array]",eds="[object Int32Array]",tds="[object Uint8Array]",sds="[object Uint8ClampedArray]",rds="[object Uint16Array]",nds="[object Uint32Array]",jc={};jc[Zcs]=jc[Xcs]=jc[Qcs]=jc[Jcs]=jc[eds]=jc[tds]=jc[sds]=jc[rds]=jc[nds]=!0;jc[Dcs]=jc[Rcs]=jc[Kcs]=jc[Ocs]=jc[Ycs]=jc[Fcs]=jc[Bcs]=jc[zcs]=jc[$cs]=jc[Ucs]=jc[qcs]=jc[Vcs]=jc[Hcs]=jc[Gcs]=jc[Wcs]=!1;function ads(s){return Pcs(s)&&Lcs(s.length)&&!!jc[Ics(s)]}var ids=ads;function ods(s){return function(t){return s(t)}}var uct=ods,ehe={exports:{}};ehe.exports;(function(s,t){var r=vlt,n=t&&!t.nodeType&&t,a=n&&!0&&s&&!s.nodeType&&s,i=a&&a.exports===n,l=i&&r.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})(ehe,ehe.exports);var lds=ehe.exports,cds=ids,dds=uct,Cze=lds,Tze=Cze&&Cze.isTypedArray,uds=Tze?dds(Tze):cds,hct=uds,hds=pcs,mds=B5e,fds=ip,pds=dct,xds=z5e,gds=hct,yds=Object.prototype,vds=yds.hasOwnProperty;function bds(s,t){var r=fds(s),n=!r&&mds(s),a=!r&&!n&&pds(s),i=!r&&!n&&!a&&gds(s),l=r||n||a||i,o=l?hds(s.length,String):[],c=o.length;for(var d in s)(t||vds.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||xds(d,c)))&&o.push(d);return o}var _ds=bds,wds=Object.prototype;function jds(s){var t=s&&s.constructor,r=typeof t=="function"&&t.prototype||wds;return s===r}var Nds=jds;function kds(s,t){return function(r){return s(t(r))}}var mct=kds,Sds=mct,Cds=Sds(Object.keys,Object),Tds=Cds,Eds=Nds,Ads=Tds,Mds=Object.prototype,Ids=Mds.hasOwnProperty;function Lds(s){if(!Eds(s))return Ads(s);var t=[];for(var r in Object(s))Ids.call(s,r)&&r!="constructor"&&t.push(r);return t}var Pds=Lds,Dds=w5e,Rds=$5e;function Ods(s){return s!=null&&Rds(s.length)&&!Dds(s)}var TB=Ods,Fds=_ds,Bds=Pds,zds=TB;function $ds(s){return zds(s)?Fds(s):Bds(s)}var qpe=$ds,Uds=rcs,qds=mcs,Vds=qpe;function Hds(s){return Uds(s,Vds,qds)}var Gds=Hds,Eze=Gds,Wds=1,Kds=Object.prototype,Yds=Kds.hasOwnProperty;function Zds(s,t,r,n,a,i){var l=r&Wds,o=Eze(s),c=o.length,d=Eze(t),h=d.length;if(c!=h&&!l)return!1;for(var m=c;m--;){var x=o[m];if(!(l?x in t:Yds.call(t,x)))return!1}var y=i.get(s),v=i.get(t);if(y&&v)return y==t&&v==s;var w=!0;i.set(s,t),i.set(t,s);for(var b=l;++m-1}var Khs=Whs;function Yhs(s,t,r){for(var n=-1,a=s==null?0:s.length;++n=dms){var d=t?null:lms(s);if(d)return cms(d);l=!1,a=oms,c=new nms}else c=t?[]:o;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Sms(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Cms(s){return s.value}function Tms(s,t){if(wt.isValidElement(s))return wt.cloneElement(s,t);if(typeof s=="function")return wt.createElement(s,t);t.ref;var r=kms(t,gms);return wt.createElement(O5e,r)}var Hze=1,VA=function(s){function t(){var r;yms(this,t);for(var n=arguments.length,a=new Array(n),i=0;iHze||Math.abs(a.height-this.lastBoundingBox.height)>Hze)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,n&&n(a)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?I1({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,h=a.chartHeight,m,x;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(l==="center"&&i==="vertical"){var y=this.getBBoxSnapshot();m={left:((d||0)-y.width)/2}}else m=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(o==="middle"){var v=this.getBBoxSnapshot();x={top:((h||0)-v.height)/2}}else x=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return I1(I1({},m),x)}},{key:"render",value:function(){var n=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,h=a.payload,m=I1(I1({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return wt.createElement("div",{className:"recharts-legend-wrapper",style:m,ref:function(y){n.wrapperNode=y}},Tms(i,I1(I1({},this.props),{},{payload:bct(h,d,Cms)})))}}],[{key:"getWithHeight",value:function(n,a){var i=I1(I1({},this.defaultProps),n.props),l=i.layout;return l==="vertical"&&Sn(n.props.height)?{height:n.props.height}:l==="horizontal"?{width:n.props.width||a}:null}}])}(k.PureComponent);Vpe(VA,"displayName","Legend");Vpe(VA,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Gze=SB,Ems=B5e,Ams=ip,Wze=Gze?Gze.isConcatSpreadable:void 0;function Mms(s){return Ams(s)||Ems(s)||!!(Wze&&s&&s[Wze])}var Ims=Mms,Lms=lct,Pms=Ims;function jct(s,t,r,n,a){var i=-1,l=s.length;for(r||(r=Pms),a||(a=[]);++i0&&r(o)?t>1?jct(o,t-1,r,n,a):Lms(a,o):n||(a[a.length]=o)}return a}var Nct=jct;function Dms(s){return function(t,r,n){for(var a=-1,i=Object(t),l=n(t),o=l.length;o--;){var c=l[s?o:++a];if(r(i[c],c,i)===!1)break}return t}}var Rms=Dms,Oms=Rms,Fms=Oms(),Bms=Fms,zms=Bms,$ms=qpe;function Ums(s,t){return s&&zms(s,t,$ms)}var kct=Ums,qms=TB;function Vms(s,t){return function(r,n){if(r==null)return r;if(!qms(r))return s(r,n);for(var a=r.length,i=t?a:-1,l=Object(r);(t?i--:++it||i&&l&&c&&!o&&!d||n&&l&&c||!r&&c||!a)return 1;if(!n&&!i&&!d&&s=o)return c;var d=r[n];return c*(d=="desc"?-1:1)}}return s.index-t.index}var nfs=rfs,q1e=C5e,afs=T5e,ifs=Bv,ofs=Sct,lfs=Jms,cfs=uct,dfs=nfs,ufs=dL,hfs=ip;function mfs(s,t,r){t.length?t=q1e(t,function(i){return hfs(i)?function(l){return afs(l,i.length===1?i[0]:i)}:i}):t=[ufs];var n=-1;t=q1e(t,cfs(ifs));var a=ofs(s,function(i,l,o){var c=q1e(t,function(d){return d(i)});return{criteria:c,index:++n,value:i}});return lfs(a,function(i,l){return dfs(i,l,r)})}var ffs=mfs;function pfs(s,t,r){switch(r.length){case 0:return s.call(t);case 1:return s.call(t,r[0]);case 2:return s.call(t,r[0],r[1]);case 3:return s.call(t,r[0],r[1],r[2])}return s.apply(t,r)}var xfs=pfs,gfs=xfs,Yze=Math.max;function yfs(s,t,r){return t=Yze(t===void 0?s.length-1:t,0),function(){for(var n=arguments,a=-1,i=Yze(n.length-t,0),l=Array(i);++a0){if(++t>=Tfs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Ifs=Mfs,Lfs=Cfs,Pfs=Ifs,Dfs=Pfs(Lfs),Rfs=Dfs,Ofs=dL,Ffs=vfs,Bfs=Rfs;function zfs(s,t){return Bfs(Ffs(s,t,Ofs),s+"")}var $fs=zfs,Ufs=j5e,qfs=TB,Vfs=z5e,Hfs=o2;function Gfs(s,t,r){if(!Hfs(r))return!1;var n=typeof t;return(n=="number"?qfs(r)&&Vfs(t,r.length):n=="string"&&t in r)?Ufs(r[t],s):!1}var Hpe=Gfs,Wfs=Nct,Kfs=ffs,Yfs=$fs,Xze=Hpe,Zfs=Yfs(function(s,t){if(s==null)return[];var r=t.length;return r>1&&Xze(s,t[0],t[1])?t=[]:r>2&&Xze(t[0],t[1],t[2])&&(t=[t[0]]),Kfs(s,Wfs(t,1),[])}),Xfs=Zfs;const V5e=Ao(Xfs);function z8(s){"@babel/helpers - typeof";return z8=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},z8(s)}function rNe(){return rNe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=t.x),"".concat(iD,"-left"),Sn(r)&&t&&Sn(t.x)&&r=t.y),"".concat(iD,"-top"),Sn(n)&&t&&Sn(t.y)&&nw?Math.max(h,c[n]):Math.max(m,c[n])}function hps(s){var t=s.translateX,r=s.translateY,n=s.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function mps(s){var t=s.allowEscapeViewBox,r=s.coordinate,n=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,h,m;return l.height>0&&l.width>0&&r?(h=e7e({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),m=e7e({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=hps({translateX:h,translateY:m,useTranslate3d:o})):d=dps,{cssProperties:d,cssClasses:ups({translateX:h,translateY:m,coordinate:r})}}function HM(s){"@babel/helpers - typeof";return HM=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},HM(s)}function t7e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function s7e(s){for(var t=1;tr7e||Math.abs(n.height-this.state.lastBoundingBox.height)>r7e)&&this.setState({lastBoundingBox:{width:n.width,height:n.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 n,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.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 n=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,h=a.coordinate,m=a.hasPayload,x=a.isAnimationActive,y=a.offset,v=a.position,w=a.reverseDirection,b=a.useTranslate3d,N=a.viewBox,S=a.wrapperStyle,T=mps({allowEscapeViewBox:l,coordinate:h,offsetTopLeft:y,position:v,reverseDirection:w,tooltipBox:this.state.lastBoundingBox,useTranslate3d:b,viewBox:N}),A=T.cssClasses,I=T.cssProperties,D=s7e(s7e({transition:x&&i?"transform ".concat(o,"ms ").concat(c):void 0},I),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&m?"visible":"hidden",position:"absolute",top:0,left:0},S);return wt.createElement("div",{tabIndex:-1,className:A,style:D,ref:function($){n.wrapperNode=$}},d)}}])}(k.PureComponent),jps=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},pv={isSsr:jps(),get:function(t){return pv[t]},set:function(t,r){if(typeof t=="string")pv[t]=r;else{var n=Object.keys(t);n&&n.length&&n.forEach(function(a){pv[a]=t[a]})}}};function GM(s){"@babel/helpers - typeof";return GM=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},GM(s)}function n7e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function a7e(s){for(var t=1;t0;return wt.createElement(wps,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:x,active:i,coordinate:h,hasPayload:D,offset:y,position:b,reverseDirection:N,useTranslate3d:S,viewBox:T,wrapperStyle:A},Lps(d,a7e(a7e({},this.props),{},{payload:I})))}}])}(k.PureComponent);H5e(Bf,"displayName","Tooltip");H5e(Bf,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!pv.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 Pps=Fv,Dps=function(){return Pps.Date.now()},Rps=Dps,Ops=/\s/;function Fps(s){for(var t=s.length;t--&&Ops.test(s.charAt(t)););return t}var Bps=Fps,zps=Bps,$ps=/^\s+/;function Ups(s){return s&&s.slice(0,zps(s)+1).replace($ps,"")}var qps=Ups,Vps=qps,i7e=o2,Hps=sL,o7e=NaN,Gps=/^[-+]0x[0-9a-f]+$/i,Wps=/^0b[01]+$/i,Kps=/^0o[0-7]+$/i,Yps=parseInt;function Zps(s){if(typeof s=="number")return s;if(Hps(s))return o7e;if(i7e(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=i7e(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Vps(s);var r=Wps.test(s);return r||Kps.test(s)?Yps(s.slice(2),r?2:8):Gps.test(s)?o7e:+s}var Ict=Zps,Xps=o2,H1e=Rps,l7e=Ict,Qps="Expected a function",Jps=Math.max,exs=Math.min;function txs(s,t,r){var n,a,i,l,o,c,d=0,h=!1,m=!1,x=!0;if(typeof s!="function")throw new TypeError(Qps);t=l7e(t)||0,Xps(r)&&(h=!!r.leading,m="maxWait"in r,i=m?Jps(l7e(r.maxWait)||0,t):i,x="trailing"in r?!!r.trailing:x);function y(D){var R=n,$=a;return n=a=void 0,d=D,l=s.apply($,R),l}function v(D){return d=D,o=setTimeout(N,t),h?y(D):l}function w(D){var R=D-c,$=D-d,F=t-R;return m?exs(F,i-$):F}function b(D){var R=D-c,$=D-d;return c===void 0||R>=t||R<0||m&&$>=i}function N(){var D=H1e();if(b(D))return S(D);o=setTimeout(N,w(D))}function S(D){return o=void 0,x&&n?y(D):(n=a=void 0,l)}function T(){o!==void 0&&clearTimeout(o),d=0,n=c=a=o=void 0}function A(){return o===void 0?l:S(H1e())}function I(){var D=H1e(),R=b(D);if(n=arguments,a=this,c=D,R){if(o===void 0)return v(c);if(m)return clearTimeout(o),o=setTimeout(N,t),y(c)}return o===void 0&&(o=setTimeout(N,t)),l}return I.cancel=T,I.flush=A,I}var sxs=txs,rxs=sxs,nxs=o2,axs="Expected a function";function ixs(s,t,r){var n=!0,a=!0;if(typeof s!="function")throw new TypeError(axs);return nxs(r)&&(n="leading"in r?!!r.leading:n,a="trailing"in r?!!r.trailing:a),rxs(s,t,{leading:n,maxWait:t,trailing:a})}var oxs=ixs;const Lct=Ao(oxs);function U8(s){"@babel/helpers - typeof";return U8=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},U8(s)}function c7e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function w$(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&(X=Lct(X,w,{trailing:!0,leading:!1}));var Z=new ResizeObserver(X),re=I.current.getBoundingClientRect(),le=re.width,oe=re.height;return Q(le,oe),Z.observe(I.current),function(){Z.disconnect()}},[Q,w]);var K=k.useMemo(function(){var X=F.containerWidth,Z=F.containerHeight;if(X<0||Z<0)return null;Iy(c4(l)||c4(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),Iy(!r||r>0,"The aspect(%s) must be greater than zero.",r);var re=c4(l)?X:l,le=c4(c)?Z:c;r&&r>0&&(re?le=re/r:le&&(re=le*r),x&&le>x&&(le=x)),Iy(re>0||le>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.`,re,le,l,c,h,m,r);var oe=!Array.isArray(y)&&_b(y.type).endsWith("Chart");return wt.Children.map(y,function(ne){return wt.isValidElement(ne)?k.cloneElement(ne,w$({width:re,height:le},oe?{style:w$({height:"100%",width:"100%",maxHeight:le,maxWidth:re},ne.props.style)}:{})):ne})},[r,y,c,x,m,h,F,l]);return wt.createElement("div",{id:b?"".concat(b):void 0,className:Fi("recharts-responsive-container",N),style:w$(w$({},A),{},{width:l,height:c,minWidth:h,minHeight:m,maxHeight:x}),ref:I},K)}),EB=function(t){return null};EB.displayName="Cell";function q8(s){"@babel/helpers - typeof";return q8=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},q8(s)}function u7e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function oNe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||pv.isSsr)return{width:0,height:0};var n=_xs(r),a=JSON.stringify({text:t,copyStyle:n});if(rE.widthCache[a])return rE.widthCache[a];try{var i=document.getElementById(h7e);i||(i=document.createElement("span"),i.setAttribute("id",h7e),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=oNe(oNe({},bxs),n);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return rE.widthCache[a]=c,++rE.cacheCount>vxs&&(rE.cacheCount=0,rE.widthCache={}),c}catch{return{width:0,height:0}}},wxs=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function V8(s){"@babel/helpers - typeof";return V8=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},V8(s)}function nhe(s,t){return Sxs(s)||kxs(s,t)||Nxs(s,t)||jxs()}function jxs(){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 Nxs(s,t){if(s){if(typeof s=="string")return m7e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return m7e(s,t)}}function m7e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function zxs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function v7e(s,t){return Vxs(s)||qxs(s,t)||Uxs(s,t)||$xs()}function $xs(){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 Uxs(s,t){if(s){if(typeof s=="string")return b7e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return b7e(s,t)}}function b7e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[];return re.reduce(function(le,oe){var ne=oe.word,ie=oe.width,ye=le[le.length-1];if(ye&&(a==null||i||ye.width+ie+noe.width?le:oe})};if(!h)return y;for(var w="…",b=function(re){var le=m.slice(0,re),oe=Oct({breakAll:d,style:c,children:le+w}).wordsWithComputedWidth,ne=x(oe),ie=ne.length>l||v(ne).width>Number(a);return[ie,ne]},N=0,S=m.length-1,T=0,A;N<=S&&T<=m.length-1;){var I=Math.floor((N+S)/2),D=I-1,R=b(D),$=v7e(R,2),F=$[0],z=$[1],Q=b(I),K=v7e(Q,1),X=K[0];if(!F&&!X&&(N=I+1),F&&X&&(S=I-1),!F&&X){A=z;break}T++}return A||y},_7e=function(t){var r=Pi(t)?[]:t.toString().split(Rct);return[{words:r}]},Gxs=function(t){var r=t.width,n=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((r||n)&&!pv.isSsr){var c,d,h=Oct({breakAll:l,children:a,style:i});if(h){var m=h.wordsWithComputedWidth,x=h.spaceWidth;c=m,d=x}else return _7e(a);return Hxs({breakAll:l,children:a,maxLines:o,style:i},c,d,r,n)}return _7e(a)},w7e="#808080",V3=function(t){var r=t.x,n=r===void 0?0:r,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,h=t.scaleToFit,m=h===void 0?!1:h,x=t.textAnchor,y=x===void 0?"start":x,v=t.verticalAnchor,w=v===void 0?"end":v,b=t.fill,N=b===void 0?w7e:b,S=y7e(t,Fxs),T=k.useMemo(function(){return Gxs({breakAll:S.breakAll,children:S.children,maxLines:S.maxLines,scaleToFit:m,style:S.style,width:S.width})},[S.breakAll,S.children,S.maxLines,m,S.style,S.width]),A=S.dx,I=S.dy,D=S.angle,R=S.className,$=S.breakAll,F=y7e(S,Bxs);if(!qu(n)||!qu(i))return null;var z=n+(Sn(A)?A:0),Q=i+(Sn(I)?I:0),K;switch(w){case"start":K=G1e("calc(".concat(d,")"));break;case"middle":K=G1e("calc(".concat((T.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:K=G1e("calc(".concat(T.length-1," * -").concat(o,")"));break}var X=[];if(m){var Z=T[0].width,re=S.width;X.push("scale(".concat((Sn(re)?re/Z:1)/Z,")"))}return D&&X.push("rotate(".concat(D,", ").concat(z,", ").concat(Q,")")),X.length&&(F.transform=X.join(" ")),wt.createElement("text",lNe({},ai(F,!0),{x:z,y:Q,className:Fi("recharts-text",R),textAnchor:y,fill:N.includes("url")?w7e:N}),T.map(function(le,oe){var ne=le.words.join($?"":" ");return wt.createElement("tspan",{x:z,dy:oe===0?K:o,key:"".concat(ne,"-").concat(oe)},ne)}))};function vj(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function Wxs(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function G5e(s){let t,r,n;s.length!==2?(t=vj,r=(o,c)=>vj(s(o),c),n=(o,c)=>s(o)-c):(t=s===vj||s===Wxs?s:Kxs,r=s,n=s);function a(o,c,d=0,h=o.length){if(d>>1;r(o[m],c)<0?d=m+1:h=m}while(d>>1;r(o[m],c)<=0?d=m+1:h=m}while(dd&&n(o[m-1],c)>-n(o[m],c)?m-1:m}return{left:a,center:l,right:i}}function Kxs(){return 0}function Fct(s){return s===null?NaN:+s}function*Yxs(s,t){for(let r of s)r!=null&&(r=+r)>=r&&(yield r)}const Zxs=G5e(vj),AB=Zxs.right;G5e(Fct).center;class j7e extends Map{constructor(t,r=Jxs){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,a]of t)this.set(n,a)}get(t){return super.get(N7e(this,t))}has(t){return super.has(N7e(this,t))}set(t,r){return super.set(Xxs(this,t),r)}delete(t){return super.delete(Qxs(this,t))}}function N7e({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):r}function Xxs({_intern:s,_key:t},r){const n=t(r);return s.has(n)?s.get(n):(s.set(n,r),r)}function Qxs({_intern:s,_key:t},r){const n=t(r);return s.has(n)&&(r=s.get(n),s.delete(n)),r}function Jxs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function egs(s=vj){if(s===vj)return Bct;if(typeof s!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=s(t,r);return n||n===0?n:(s(r,r)===0)-(s(t,t)===0)}}function Bct(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const tgs=Math.sqrt(50),sgs=Math.sqrt(10),rgs=Math.sqrt(2);function ahe(s,t,r){const n=(t-s)/Math.max(0,r),a=Math.floor(Math.log10(n)),i=n/Math.pow(10,a),l=i>=tgs?10:i>=sgs?5:i>=rgs?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 n=t=a))return[];const o=i-a+1,c=new Array(o);if(n)if(l<0)for(let d=0;d=n)&&(r=n);return r}function S7e(s,t){let r;for(const n of s)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function zct(s,t,r=0,n=1/0,a){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(s.length-1,n)),!(r<=t&&t<=n))return s;for(a=a===void 0?Bct:egs(a);n>r;){if(n-r>600){const c=n-r+1,d=t-r+1,h=Math.log(c),m=.5*Math.exp(2*h/3),x=.5*Math.sqrt(h*m*(c-m)/c)*(d-c/2<0?-1:1),y=Math.max(r,Math.floor(t-d*m/c+x)),v=Math.min(n,Math.floor(t+(c-d)*m/c+x));zct(s,t,y,v,a)}const i=s[t];let l=r,o=n;for(oD(s,r,t),a(s[n],i)>0&&oD(s,r,n);l0;)--o}a(s[r],i)===0?oD(s,r,o):(++o,oD(s,o,n)),o<=t&&(r=o+1),t<=o&&(n=o-1)}return s}function oD(s,t,r){const n=s[t];s[t]=s[r],s[r]=n}function ngs(s,t,r){if(s=Float64Array.from(Yxs(s)),!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return S7e(s);if(t>=1)return k7e(s);var n,a=(n-1)*t,i=Math.floor(a),l=k7e(zct(s,i).subarray(0,i+1)),o=S7e(s.subarray(i+1));return l+(o-l)*(a-i)}}function ags(s,t,r=Fct){if(!(!(n=s.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(s[0],0,s);if(t>=1)return+r(s[n-1],n-1,s);var n,a=(n-1)*t,i=Math.floor(a),l=+r(s[i],i,s),o=+r(s[i+1],i+1,s);return l+(o-l)*(a-i)}}function igs(s,t,r){s=+s,t=+t,r=(a=arguments.length)<2?(t=s,s=0,1):a<3?1:+r;for(var n=-1,a=Math.max(0,Math.ceil((t-s)/r))|0,i=new Array(a);++n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?N$(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?N$(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=lgs.exec(s))?new Gf(t[1],t[2],t[3],1):(t=cgs.exec(s))?new Gf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=dgs.exec(s))?N$(t[1],t[2],t[3],t[4]):(t=ugs.exec(s))?N$(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=hgs.exec(s))?L7e(t[1],t[2]/100,t[3]/100,1):(t=mgs.exec(s))?L7e(t[1],t[2]/100,t[3]/100,t[4]):C7e.hasOwnProperty(s)?A7e(C7e[s]):s==="transparent"?new Gf(NaN,NaN,NaN,0):null}function A7e(s){return new Gf(s>>16&255,s>>8&255,s&255,1)}function N$(s,t,r,n){return n<=0&&(s=t=r=NaN),new Gf(s,t,r,n)}function xgs(s){return s instanceof MB||(s=K8(s)),s?(s=s.rgb(),new Gf(s.r,s.g,s.b,s.opacity)):new Gf}function mNe(s,t,r,n){return arguments.length===1?xgs(s):new Gf(s,t,r,n??1)}function Gf(s,t,r,n){this.r=+s,this.g=+t,this.b=+r,this.opacity=+n}K5e(Gf,mNe,Uct(MB,{brighter(s){return s=s==null?ihe:Math.pow(ihe,s),new Gf(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?G8:Math.pow(G8,s),new Gf(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new Gf(h3(this.r),h3(this.g),h3(this.b),ohe(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:M7e,formatHex:M7e,formatHex8:ggs,formatRgb:I7e,toString:I7e}));function M7e(){return`#${d4(this.r)}${d4(this.g)}${d4(this.b)}`}function ggs(){return`#${d4(this.r)}${d4(this.g)}${d4(this.b)}${d4((isNaN(this.opacity)?1:this.opacity)*255)}`}function I7e(){const s=ohe(this.opacity);return`${s===1?"rgb(":"rgba("}${h3(this.r)}, ${h3(this.g)}, ${h3(this.b)}${s===1?")":`, ${s})`}`}function ohe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function h3(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function d4(s){return s=h3(s),(s<16?"0":"")+s.toString(16)}function L7e(s,t,r,n){return n<=0?s=t=r=NaN:r<=0||r>=1?s=t=NaN:t<=0&&(s=NaN),new yy(s,t,r,n)}function qct(s){if(s instanceof yy)return new yy(s.h,s.s,s.l,s.opacity);if(s instanceof MB||(s=K8(s)),!s)return new yy;if(s instanceof yy)return s;s=s.rgb();var t=s.r/255,r=s.g/255,n=s.b/255,a=Math.min(t,r,n),i=Math.max(t,r,n),l=NaN,o=i-a,c=(i+a)/2;return o?(t===i?l=(r-n)/o+(r0&&c<1?0:l,new yy(l,o,c,s.opacity)}function ygs(s,t,r,n){return arguments.length===1?qct(s):new yy(s,t,r,n??1)}function yy(s,t,r,n){this.h=+s,this.s=+t,this.l=+r,this.opacity=+n}K5e(yy,ygs,Uct(MB,{brighter(s){return s=s==null?ihe:Math.pow(ihe,s),new yy(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?G8:Math.pow(G8,s),new yy(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,r=this.l,n=r+(r<.5?r:1-r)*t,a=2*r-n;return new Gf(W1e(s>=240?s-240:s+120,a,n),W1e(s,a,n),W1e(s<120?s+240:s-120,a,n),this.opacity)},clamp(){return new yy(P7e(this.h),k$(this.s),k$(this.l),ohe(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=ohe(this.opacity);return`${s===1?"hsl(":"hsla("}${P7e(this.h)}, ${k$(this.s)*100}%, ${k$(this.l)*100}%${s===1?")":`, ${s})`}`}}));function P7e(s){return s=(s||0)%360,s<0?s+360:s}function k$(s){return Math.max(0,Math.min(1,s||0))}function W1e(s,t,r){return(s<60?t+(r-t)*s/60:s<180?r:s<240?t+(r-t)*(240-s)/60:t)*255}const Y5e=s=>()=>s;function vgs(s,t){return function(r){return s+r*t}}function bgs(s,t,r){return s=Math.pow(s,r),t=Math.pow(t,r)-s,r=1/r,function(n){return Math.pow(s+n*t,r)}}function _gs(s){return(s=+s)==1?Vct:function(t,r){return r-t?bgs(t,r,s):Y5e(isNaN(t)?r:t)}}function Vct(s,t){var r=t-s;return r?vgs(s,r):Y5e(isNaN(s)?t:s)}const D7e=function s(t){var r=_gs(t);function n(a,i){var l=r((a=mNe(a)).r,(i=mNe(i)).r),o=r(a.g,i.g),c=r(a.b,i.b),d=Vct(a.opacity,i.opacity);return function(h){return a.r=l(h),a.g=o(h),a.b=c(h),a.opacity=d(h),a+""}}return n.gamma=s,n}(1);function wgs(s,t){t||(t=[]);var r=s?Math.min(t.length,s.length):0,n=t.slice(),a;return function(i){for(a=0;ar&&(i=t.slice(r,i),o[l]?o[l]+=i:o[++l]=i),(n=n[0])===(a=a[0])?o[l]?o[l]+=a:o[++l]=a:(o[++l]=null,c.push({i:l,x:lhe(n,a)})),r=K1e.lastIndex;return rt&&(r=s,s=t,t=r),function(n){return Math.max(s,Math.min(t,n))}}function Lgs(s,t,r){var n=s[0],a=s[1],i=t[0],l=t[1];return a2?Pgs:Lgs,c=d=null,m}function m(x){return x==null||isNaN(x=+x)?i:(c||(c=o(s.map(n),t,r)))(n(l(x)))}return m.invert=function(x){return l(a((d||(d=o(t,s.map(n),lhe)))(x)))},m.domain=function(x){return arguments.length?(s=Array.from(x,che),h()):s.slice()},m.range=function(x){return arguments.length?(t=Array.from(x),h()):t.slice()},m.rangeRound=function(x){return t=Array.from(x),r=Z5e,h()},m.clamp=function(x){return arguments.length?(l=x?!0:mf,h()):l!==mf},m.interpolate=function(x){return arguments.length?(r=x,h()):r},m.unknown=function(x){return arguments.length?(i=x,m):i},function(x,y){return n=x,a=y,h()}}function X5e(){return Gpe()(mf,mf)}function Dgs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function dhe(s,t){if((r=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var r,n=s.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+s.slice(r+1)]}function WM(s){return s=dhe(Math.abs(s)),s?s[1]:NaN}function Rgs(s,t){return function(r,n){for(var a=r.length,i=[],l=0,o=s[0],c=0;a>0&&o>0&&(c+o+1>n&&(o=Math.max(1,n-c)),i.push(r.substring(a-=o,a+o)),!((c+=o+1)>n));)o=s[l=(l+1)%s.length];return i.reverse().join(t)}}function Ogs(s){return function(t){return t.replace(/[0-9]/g,function(r){return s[+r]})}}var Fgs=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Y8(s){if(!(t=Fgs.exec(s)))throw new Error("invalid format: "+s);var t;return new Q5e({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]})}Y8.prototype=Q5e.prototype;function Q5e(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+""}Q5e.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 Bgs(s){e:for(var t=s.length,r=1,n=-1,a;r0&&(n=0);break}return n>0?s.slice(0,n)+s.slice(a+1):s}var Hct;function zgs(s,t){var r=dhe(s,t);if(!r)return s+"";var n=r[0],a=r[1],i=a-(Hct=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,l=n.length;return i===l?n:i>l?n+new Array(i-l+1).join("0"):i>0?n.slice(0,i)+"."+n.slice(i):"0."+new Array(1-i).join("0")+dhe(s,Math.max(0,t+i-1))[0]}function O7e(s,t){var r=dhe(s,t);if(!r)return s+"";var n=r[0],a=r[1];return a<0?"0."+new Array(-a).join("0")+n:n.length>a+1?n.slice(0,a+1)+"."+n.slice(a+1):n+new Array(a-n.length+2).join("0")}const F7e={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Dgs,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)=>O7e(s*100,t),r:O7e,s:zgs,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function B7e(s){return s}var z7e=Array.prototype.map,$7e=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function $gs(s){var t=s.grouping===void 0||s.thousands===void 0?B7e:Rgs(z7e.call(s.grouping,Number),s.thousands+""),r=s.currency===void 0?"":s.currency[0]+"",n=s.currency===void 0?"":s.currency[1]+"",a=s.decimal===void 0?".":s.decimal+"",i=s.numerals===void 0?B7e:Ogs(z7e.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(m){m=Y8(m);var x=m.fill,y=m.align,v=m.sign,w=m.symbol,b=m.zero,N=m.width,S=m.comma,T=m.precision,A=m.trim,I=m.type;I==="n"?(S=!0,I="g"):F7e[I]||(T===void 0&&(T=12),A=!0,I="g"),(b||x==="0"&&y==="=")&&(b=!0,x="0",y="=");var D=w==="$"?r:w==="#"&&/[boxX]/.test(I)?"0"+I.toLowerCase():"",R=w==="$"?n:/[%p]/.test(I)?l:"",$=F7e[I],F=/[defgprs%]/.test(I);T=T===void 0?6:/[gprs]/.test(I)?Math.max(1,Math.min(21,T)):Math.max(0,Math.min(20,T));function z(Q){var K=D,X=R,Z,re,le;if(I==="c")X=$(Q)+X,Q="";else{Q=+Q;var oe=Q<0||1/Q<0;if(Q=isNaN(Q)?c:$(Math.abs(Q),T),A&&(Q=Bgs(Q)),oe&&+Q==0&&v!=="+"&&(oe=!1),K=(oe?v==="("?v:o:v==="-"||v==="("?"":v)+K,X=(I==="s"?$7e[8+Hct/3]:"")+X+(oe&&v==="("?")":""),F){for(Z=-1,re=Q.length;++Zle||le>57){X=(le===46?a+Q.slice(Z+1):Q.slice(Z))+X,Q=Q.slice(0,Z);break}}}S&&!b&&(Q=t(Q,1/0));var ne=K.length+Q.length+X.length,ie=ne>1)+K+Q+X+ie.slice(ne);break;default:Q=ie+K+Q+X;break}return i(Q)}return z.toString=function(){return m+""},z}function h(m,x){var y=d((m=Y8(m),m.type="f",m)),v=Math.max(-8,Math.min(8,Math.floor(WM(x)/3)))*3,w=Math.pow(10,-v),b=$7e[8+v/3];return function(N){return y(w*N)+b}}return{format:d,formatPrefix:h}}var S$,J5e,Gct;Ugs({thousands:",",grouping:[3],currency:["$",""]});function Ugs(s){return S$=$gs(s),J5e=S$.format,Gct=S$.formatPrefix,S$}function qgs(s){return Math.max(0,-WM(Math.abs(s)))}function Vgs(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(WM(t)/3)))*3-WM(Math.abs(s)))}function Hgs(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,WM(t)-WM(s))+1}function Wct(s,t,r,n){var a=uNe(s,t,r),i;switch(n=Y8(n??",f"),n.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return n.precision==null&&!isNaN(i=Vgs(a,l))&&(n.precision=i),Gct(n,l)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(i=Hgs(a,Math.max(Math.abs(s),Math.abs(t))))&&(n.precision=i-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(i=qgs(a))&&(n.precision=i-(n.type==="%")*2);break}}return J5e(n)}function l2(s){var t=s.domain;return s.ticks=function(r){var n=t();return cNe(n[0],n[n.length-1],r??10)},s.tickFormat=function(r,n){var a=t();return Wct(a[0],a[a.length-1],r??10,n)},s.nice=function(r){r==null&&(r=10);var n=t(),a=0,i=n.length-1,l=n[a],o=n[i],c,d,h=10;for(o0;){if(d=dNe(l,o,r),d===c)return n[a]=l,n[i]=o,t(n);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 uhe(){var s=X5e();return s.copy=function(){return IB(s,uhe())},jg.apply(s,arguments),l2(s)}function Kct(s){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(s=Array.from(n,che),r):s.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return Kct(s).unknown(t)},s=arguments.length?Array.from(s,che):[0,1],l2(r)}function Yct(s,t){s=s.slice();var r=0,n=s.length-1,a=s[r],i=s[n],l;return iMath.pow(s,t)}function Zgs(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 V7e(s){return(t,r)=>-s(-t,r)}function eTe(s){const t=s(U7e,q7e),r=t.domain;let n=10,a,i;function l(){return a=Zgs(n),i=Ygs(n),r()[0]<0?(a=V7e(a),i=V7e(i),s(Ggs,Wgs)):s(U7e,q7e),t}return t.base=function(o){return arguments.length?(n=+o,l()):n},t.domain=function(o){return arguments.length?(r(o),l()):r()},t.ticks=o=>{const c=r();let d=c[0],h=c[c.length-1];const m=h0){for(;x<=y;++x)for(v=1;vh)break;N.push(w)}}else for(;x<=y;++x)for(v=n-1;v>=1;--v)if(w=x>0?v/i(-x):v*i(x),!(wh)break;N.push(w)}N.length*2{if(o==null&&(o=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=Y8(c)).precision==null&&(c.trim=!0),c=J5e(c)),o===1/0)return c;const d=Math.max(1,n*o/t.ticks().length);return h=>{let m=h/i(Math.round(a(h)));return m*nr(Yct(r(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function Zct(){const s=eTe(Gpe()).domain([1,10]);return s.copy=()=>IB(s,Zct()).base(s.base()),jg.apply(s,arguments),s}function H7e(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function G7e(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function tTe(s){var t=1,r=s(H7e(t),G7e(t));return r.constant=function(n){return arguments.length?s(H7e(t=+n),G7e(t)):t},l2(r)}function Xct(){var s=tTe(Gpe());return s.copy=function(){return IB(s,Xct()).constant(s.constant())},jg.apply(s,arguments)}function W7e(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function Xgs(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function Qgs(s){return s<0?-s*s:s*s}function sTe(s){var t=s(mf,mf),r=1;function n(){return r===1?s(mf,mf):r===.5?s(Xgs,Qgs):s(W7e(r),W7e(1/r))}return t.exponent=function(a){return arguments.length?(r=+a,n()):r},l2(t)}function rTe(){var s=sTe(Gpe());return s.copy=function(){return IB(s,rTe()).exponent(s.exponent())},jg.apply(s,arguments),s}function Jgs(){return rTe.apply(null,arguments).exponent(.5)}function K7e(s){return Math.sign(s)*s*s}function eys(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function Qct(){var s=X5e(),t=[0,1],r=!1,n;function a(i){var l=eys(s(i));return isNaN(l)?n:r?Math.round(l):l}return a.invert=function(i){return s.invert(K7e(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,che)).map(K7e)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(r=!!i,a):r},a.clamp=function(i){return arguments.length?(s.clamp(i),a):s.clamp()},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return Qct(s.domain(),t).round(r).clamp(s.clamp()).unknown(n)},jg.apply(a,arguments),l2(a)}function Jct(){var s=[],t=[],r=[],n;function a(){var l=0,o=Math.max(1,t.length);for(r=new Array(o-1);++l0?r[o-1]:s[0],o=r?[n[r-1],t]:[n[d-1],n[d]]},l.unknown=function(c){return arguments.length&&(i=c),l},l.thresholds=function(){return n.slice()},l.copy=function(){return edt().domain([s,t]).range(a).unknown(i)},jg.apply(l2(l),arguments)}function tdt(){var s=[.5],t=[0,1],r,n=1;function a(i){return i!=null&&i<=i?t[AB(s,i,0,n)]:r}return a.domain=function(i){return arguments.length?(s=Array.from(i),n=Math.min(s.length,t.length-1),a):s.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),n=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?(r=i,a):r},a.copy=function(){return tdt().domain(s).range(t).unknown(r)},jg.apply(a,arguments)}const Y1e=new Date,Z1e=new Date;function th(s,t,r,n){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(dth(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););}),r&&(a.count=(i,l)=>(Y1e.setTime(+i),Z1e.setTime(+l),s(Y1e),s(Z1e),Math.floor(r(Y1e,Z1e))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(n?l=>n(l)%i===0:l=>a.count(0,l)%i===0):a)),a}const hhe=th(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);hhe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?th(t=>{t.setTime(Math.floor(t/s)*s)},(t,r)=>{t.setTime(+t+r*s)},(t,r)=>(r-t)/s):hhe);hhe.range;const ob=1e3,sg=ob*60,lb=sg*60,Lb=lb*24,nTe=Lb*7,Y7e=Lb*30,X1e=Lb*365,u4=th(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*ob)},(s,t)=>(t-s)/ob,s=>s.getUTCSeconds());u4.range;const aTe=th(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*ob)},(s,t)=>{s.setTime(+s+t*sg)},(s,t)=>(t-s)/sg,s=>s.getMinutes());aTe.range;const iTe=th(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*sg)},(s,t)=>(t-s)/sg,s=>s.getUTCMinutes());iTe.range;const oTe=th(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*ob-s.getMinutes()*sg)},(s,t)=>{s.setTime(+s+t*lb)},(s,t)=>(t-s)/lb,s=>s.getHours());oTe.range;const lTe=th(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*lb)},(s,t)=>(t-s)/lb,s=>s.getUTCHours());lTe.range;const LB=th(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*sg)/Lb,s=>s.getDate()-1);LB.range;const Wpe=th(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/Lb,s=>s.getUTCDate()-1);Wpe.range;const sdt=th(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/Lb,s=>Math.floor(s/Lb));sdt.range;function d5(s){return th(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*sg)/nTe)}const Kpe=d5(0),mhe=d5(1),tys=d5(2),sys=d5(3),KM=d5(4),rys=d5(5),nys=d5(6);Kpe.range;mhe.range;tys.range;sys.range;KM.range;rys.range;nys.range;function u5(s){return th(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/nTe)}const Ype=u5(0),fhe=u5(1),ays=u5(2),iys=u5(3),YM=u5(4),oys=u5(5),lys=u5(6);Ype.range;fhe.range;ays.range;iys.range;YM.range;oys.range;lys.range;const cTe=th(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());cTe.range;const dTe=th(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());dTe.range;const Pb=th(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());Pb.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:th(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*s)});Pb.range;const Db=th(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());Db.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:th(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*s)});Db.range;function rdt(s,t,r,n,a,i){const l=[[u4,1,ob],[u4,5,5*ob],[u4,15,15*ob],[u4,30,30*ob],[i,1,sg],[i,5,5*sg],[i,15,15*sg],[i,30,30*sg],[a,1,lb],[a,3,3*lb],[a,6,6*lb],[a,12,12*lb],[n,1,Lb],[n,2,2*Lb],[r,1,nTe],[t,1,Y7e],[t,3,3*Y7e],[s,1,X1e]];function o(d,h,m){const x=hb).right(l,x);if(y===l.length)return s.every(uNe(d/X1e,h/X1e,m));if(y===0)return hhe.every(Math.max(uNe(d,h,m),1));const[v,w]=l[x/l[y-1][2]53)return null;"w"in xe||(xe.w=1),"Z"in xe?(fe=J1e(lD(xe.y,0,1)),it=fe.getUTCDay(),fe=it>4||it===0?fhe.ceil(fe):fhe(fe),fe=Wpe.offset(fe,(xe.V-1)*7),xe.y=fe.getUTCFullYear(),xe.m=fe.getUTCMonth(),xe.d=fe.getUTCDate()+(xe.w+6)%7):(fe=Q1e(lD(xe.y,0,1)),it=fe.getDay(),fe=it>4||it===0?mhe.ceil(fe):mhe(fe),fe=LB.offset(fe,(xe.V-1)*7),xe.y=fe.getFullYear(),xe.m=fe.getMonth(),xe.d=fe.getDate()+(xe.w+6)%7)}else("W"in xe||"U"in xe)&&("w"in xe||(xe.w="u"in xe?xe.u%7:"W"in xe?1:0),it="Z"in xe?J1e(lD(xe.y,0,1)).getUTCDay():Q1e(lD(xe.y,0,1)).getDay(),xe.m=0,xe.d="W"in xe?(xe.w+6)%7+xe.W*7-(it+5)%7:xe.w+xe.U*7-(it+6)%7);return"Z"in xe?(xe.H+=xe.Z/100|0,xe.M+=xe.Z%100,J1e(xe)):Q1e(xe)}}function $(Le,Ie,Te,xe){for(var et=0,fe=Ie.length,it=Te.length,Oe,Ye;et=it)return-1;if(Oe=Ie.charCodeAt(et++),Oe===37){if(Oe=Ie.charAt(et++),Ye=I[Oe in Z7e?Ie.charAt(et++):Oe],!Ye||(xe=Ye(Le,Te,xe))<0)return-1}else if(Oe!=Te.charCodeAt(xe++))return-1}return xe}function F(Le,Ie,Te){var xe=d.exec(Ie.slice(Te));return xe?(Le.p=h.get(xe[0].toLowerCase()),Te+xe[0].length):-1}function z(Le,Ie,Te){var xe=y.exec(Ie.slice(Te));return xe?(Le.w=v.get(xe[0].toLowerCase()),Te+xe[0].length):-1}function Q(Le,Ie,Te){var xe=m.exec(Ie.slice(Te));return xe?(Le.w=x.get(xe[0].toLowerCase()),Te+xe[0].length):-1}function K(Le,Ie,Te){var xe=N.exec(Ie.slice(Te));return xe?(Le.m=S.get(xe[0].toLowerCase()),Te+xe[0].length):-1}function X(Le,Ie,Te){var xe=w.exec(Ie.slice(Te));return xe?(Le.m=b.get(xe[0].toLowerCase()),Te+xe[0].length):-1}function Z(Le,Ie,Te){return $(Le,t,Ie,Te)}function re(Le,Ie,Te){return $(Le,r,Ie,Te)}function le(Le,Ie,Te){return $(Le,n,Ie,Te)}function oe(Le){return l[Le.getDay()]}function ne(Le){return i[Le.getDay()]}function ie(Le){return c[Le.getMonth()]}function ye(Le){return o[Le.getMonth()]}function ce(Le){return a[+(Le.getHours()>=12)]}function ve(Le){return 1+~~(Le.getMonth()/3)}function be(Le){return l[Le.getUTCDay()]}function Ue(Le){return i[Le.getUTCDay()]}function Be(Le){return c[Le.getUTCMonth()]}function De(Le){return o[Le.getUTCMonth()]}function Ae(Le){return a[+(Le.getUTCHours()>=12)]}function He(Le){return 1+~~(Le.getUTCMonth()/3)}return{format:function(Le){var Ie=D(Le+="",T);return Ie.toString=function(){return Le},Ie},parse:function(Le){var Ie=R(Le+="",!1);return Ie.toString=function(){return Le},Ie},utcFormat:function(Le){var Ie=D(Le+="",A);return Ie.toString=function(){return Le},Ie},utcParse:function(Le){var Ie=R(Le+="",!0);return Ie.toString=function(){return Le},Ie}}}var Z7e={"-":"",_:" ",0:"0"},Th=/^\s*\d+/,fys=/^%/,pys=/[\\^$*+?|[\]().{}]/g;function al(s,t,r){var n=s<0?"-":"",a=(n?-s:s)+"",i=a.length;return n+(i[t.toLowerCase(),r]))}function gys(s,t,r){var n=Th.exec(t.slice(r,r+1));return n?(s.w=+n[0],r+n[0].length):-1}function yys(s,t,r){var n=Th.exec(t.slice(r,r+1));return n?(s.u=+n[0],r+n[0].length):-1}function vys(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.U=+n[0],r+n[0].length):-1}function bys(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.V=+n[0],r+n[0].length):-1}function _ys(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.W=+n[0],r+n[0].length):-1}function X7e(s,t,r){var n=Th.exec(t.slice(r,r+4));return n?(s.y=+n[0],r+n[0].length):-1}function Q7e(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function wys(s,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(s.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function jys(s,t,r){var n=Th.exec(t.slice(r,r+1));return n?(s.q=n[0]*3-3,r+n[0].length):-1}function Nys(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.m=n[0]-1,r+n[0].length):-1}function J7e(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.d=+n[0],r+n[0].length):-1}function kys(s,t,r){var n=Th.exec(t.slice(r,r+3));return n?(s.m=0,s.d=+n[0],r+n[0].length):-1}function e9e(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.H=+n[0],r+n[0].length):-1}function Sys(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.M=+n[0],r+n[0].length):-1}function Cys(s,t,r){var n=Th.exec(t.slice(r,r+2));return n?(s.S=+n[0],r+n[0].length):-1}function Tys(s,t,r){var n=Th.exec(t.slice(r,r+3));return n?(s.L=+n[0],r+n[0].length):-1}function Eys(s,t,r){var n=Th.exec(t.slice(r,r+6));return n?(s.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function Ays(s,t,r){var n=fys.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function Mys(s,t,r){var n=Th.exec(t.slice(r));return n?(s.Q=+n[0],r+n[0].length):-1}function Iys(s,t,r){var n=Th.exec(t.slice(r));return n?(s.s=+n[0],r+n[0].length):-1}function t9e(s,t){return al(s.getDate(),t,2)}function Lys(s,t){return al(s.getHours(),t,2)}function Pys(s,t){return al(s.getHours()%12||12,t,2)}function Dys(s,t){return al(1+LB.count(Pb(s),s),t,3)}function ndt(s,t){return al(s.getMilliseconds(),t,3)}function Rys(s,t){return ndt(s,t)+"000"}function Oys(s,t){return al(s.getMonth()+1,t,2)}function Fys(s,t){return al(s.getMinutes(),t,2)}function Bys(s,t){return al(s.getSeconds(),t,2)}function zys(s){var t=s.getDay();return t===0?7:t}function $ys(s,t){return al(Kpe.count(Pb(s)-1,s),t,2)}function adt(s){var t=s.getDay();return t>=4||t===0?KM(s):KM.ceil(s)}function Uys(s,t){return s=adt(s),al(KM.count(Pb(s),s)+(Pb(s).getDay()===4),t,2)}function qys(s){return s.getDay()}function Vys(s,t){return al(mhe.count(Pb(s)-1,s),t,2)}function Hys(s,t){return al(s.getFullYear()%100,t,2)}function Gys(s,t){return s=adt(s),al(s.getFullYear()%100,t,2)}function Wys(s,t){return al(s.getFullYear()%1e4,t,4)}function Kys(s,t){var r=s.getDay();return s=r>=4||r===0?KM(s):KM.ceil(s),al(s.getFullYear()%1e4,t,4)}function Yys(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+al(t/60|0,"0",2)+al(t%60,"0",2)}function s9e(s,t){return al(s.getUTCDate(),t,2)}function Zys(s,t){return al(s.getUTCHours(),t,2)}function Xys(s,t){return al(s.getUTCHours()%12||12,t,2)}function Qys(s,t){return al(1+Wpe.count(Db(s),s),t,3)}function idt(s,t){return al(s.getUTCMilliseconds(),t,3)}function Jys(s,t){return idt(s,t)+"000"}function e0s(s,t){return al(s.getUTCMonth()+1,t,2)}function t0s(s,t){return al(s.getUTCMinutes(),t,2)}function s0s(s,t){return al(s.getUTCSeconds(),t,2)}function r0s(s){var t=s.getUTCDay();return t===0?7:t}function n0s(s,t){return al(Ype.count(Db(s)-1,s),t,2)}function odt(s){var t=s.getUTCDay();return t>=4||t===0?YM(s):YM.ceil(s)}function a0s(s,t){return s=odt(s),al(YM.count(Db(s),s)+(Db(s).getUTCDay()===4),t,2)}function i0s(s){return s.getUTCDay()}function o0s(s,t){return al(fhe.count(Db(s)-1,s),t,2)}function l0s(s,t){return al(s.getUTCFullYear()%100,t,2)}function c0s(s,t){return s=odt(s),al(s.getUTCFullYear()%100,t,2)}function d0s(s,t){return al(s.getUTCFullYear()%1e4,t,4)}function u0s(s,t){var r=s.getUTCDay();return s=r>=4||r===0?YM(s):YM.ceil(s),al(s.getUTCFullYear()%1e4,t,4)}function h0s(){return"+0000"}function r9e(){return"%"}function n9e(s){return+s}function a9e(s){return Math.floor(+s/1e3)}var nE,ldt,cdt;m0s({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 m0s(s){return nE=mys(s),ldt=nE.format,nE.parse,cdt=nE.utcFormat,nE.utcParse,nE}function f0s(s){return new Date(s)}function p0s(s){return s instanceof Date?+s:+new Date(+s)}function uTe(s,t,r,n,a,i,l,o,c,d){var h=X5e(),m=h.invert,x=h.domain,y=d(".%L"),v=d(":%S"),w=d("%I:%M"),b=d("%I %p"),N=d("%a %d"),S=d("%b %d"),T=d("%B"),A=d("%Y");function I(D){return(c(D)t(a/(s.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(a,i)=>ngs(s,i/n))},r.copy=function(){return mdt(t).domain(s)},Kb.apply(r,arguments)}function Xpe(){var s=0,t=.5,r=1,n=1,a,i,l,o,c,d=mf,h,m=!1,x;function y(w){return isNaN(w=+w)?x:(w=.5+((w=+h(w))-i)*(n*wt}var gdt=w0s,j0s=Qpe,N0s=gdt,k0s=dL;function S0s(s){return s&&s.length?j0s(s,k0s,N0s):void 0}var C0s=S0s;const Jpe=Ao(C0s);function T0s(s,t){return ss.e^i.s<0?1:-1;for(n=i.d.length,a=s.d.length,t=0,r=ns.d[t]^i.s<0?1:-1;return n===a?0:n>a^i.s<0?1:-1};xa.decimalPlaces=xa.dp=function(){var s=this,t=s.d.length-1,r=(t-s.e)*kc;if(t=s.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};xa.dividedBy=xa.div=function(s){return wb(this,new this.constructor(s))};xa.dividedToIntegerBy=xa.idiv=function(s){var t=this,r=t.constructor;return Xl(wb(t,new r(s),0,1),r.precision)};xa.equals=xa.eq=function(s){return!this.cmp(s)};xa.exponent=function(){return _u(this)};xa.greaterThan=xa.gt=function(s){return this.cmp(s)>0};xa.greaterThanOrEqualTo=xa.gte=function(s){return this.cmp(s)>=0};xa.isInteger=xa.isint=function(){return this.e>this.d.length-2};xa.isNegative=xa.isneg=function(){return this.s<0};xa.isPositive=xa.ispos=function(){return this.s>0};xa.isZero=function(){return this.s===0};xa.lessThan=xa.lt=function(s){return this.cmp(s)<0};xa.lessThanOrEqualTo=xa.lte=function(s){return this.cmp(s)<1};xa.logarithm=xa.log=function(s){var t,r=this,n=r.constructor,a=n.precision,i=a+5;if(s===void 0)s=new n(10);else if(s=new n(s),s.s<1||s.eq(Bp))throw Error(xg+"NaN");if(r.s<1)throw Error(xg+(r.s?"NaN":"-Infinity"));return r.eq(Bp)?new n(0):(Vc=!1,t=wb(Z8(r,i),Z8(s,i),i),Vc=!0,Xl(t,a))};xa.minus=xa.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?wdt(t,s):bdt(t,(s.s=-s.s,s))};xa.modulo=xa.mod=function(s){var t,r=this,n=r.constructor,a=n.precision;if(s=new n(s),!s.s)throw Error(xg+"NaN");return r.s?(Vc=!1,t=wb(r,s,0,1).times(s),Vc=!0,r.minus(t)):Xl(new n(r),a)};xa.naturalExponential=xa.exp=function(){return _dt(this)};xa.naturalLogarithm=xa.ln=function(){return Z8(this)};xa.negated=xa.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};xa.plus=xa.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?bdt(t,s):wdt(t,(s.s=-s.s,s))};xa.precision=xa.sd=function(s){var t,r,n,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(m3+s);if(t=_u(a)+1,n=a.d.length-1,r=n*kc+1,n=a.d[n],n){for(;n%10==0;n/=10)r--;for(n=a.d[0];n>=10;n/=10)r++}return s&&t>r?t:r};xa.squareRoot=xa.sqrt=function(){var s,t,r,n,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(xg+"NaN")}for(s=_u(o),Vc=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=K0(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=mL((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),n=new c(t)):n=new c(a.toString()),r=c.precision,a=l=r+3;;)if(i=n,n=i.plus(wb(o,i,l+2)).times(.5),K0(i.d).slice(0,l)===(t=K0(n.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Xl(i,r+1,0),i.times(i).eq(o)){n=i;break}}else if(t!="9999")break;l+=4}return Vc=!0,Xl(n,r)};xa.times=xa.mul=function(s){var t,r,n,a,i,l,o,c,d,h=this,m=h.constructor,x=h.d,y=(s=new m(s)).d;if(!h.s||!s.s)return new m(0);for(s.s*=h.s,r=h.e+s.e,c=x.length,d=y.length,c=0;){for(t=0,a=c+n;a>n;)o=i[a]+y[n]*x[a-n-1]+t,i[a--]=o%hh|0,t=o/hh|0;i[a]=(i[a]+t)%hh|0}for(;!i[--l];)i.pop();return t?++r:i.shift(),s.d=i,s.e=r,Vc?Xl(s,m.precision):s};xa.toDecimalPlaces=xa.todp=function(s,t){var r=this,n=r.constructor;return r=new n(r),s===void 0?r:(Cv(s,0,hL),t===void 0?t=n.rounding:Cv(t,0,8),Xl(r,s+_u(r)+1,t))};xa.toExponential=function(s,t){var r,n=this,a=n.constructor;return s===void 0?r=H3(n,!0):(Cv(s,0,hL),t===void 0?t=a.rounding:Cv(t,0,8),n=Xl(new a(n),s+1,t),r=H3(n,!0,s+1)),r};xa.toFixed=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?H3(a):(Cv(s,0,hL),t===void 0?t=i.rounding:Cv(t,0,8),n=Xl(new i(a),s+_u(a)+1,t),r=H3(n.abs(),!1,s+_u(n)+1),a.isneg()&&!a.isZero()?"-"+r:r)};xa.toInteger=xa.toint=function(){var s=this,t=s.constructor;return Xl(new t(s),_u(s)+1,t.rounding)};xa.toNumber=function(){return+this};xa.toPower=xa.pow=function(s){var t,r,n,a,i,l,o=this,c=o.constructor,d=12,h=+(s=new c(s));if(!s.s)return new c(Bp);if(o=new c(o),!o.s){if(s.s<1)throw Error(xg+"Infinity");return o}if(o.eq(Bp))return o;if(n=c.precision,s.eq(Bp))return Xl(o,n);if(t=s.e,r=s.d.length-1,l=t>=r,i=o.s,l){if((r=h<0?-h:h)<=vdt){for(a=new c(Bp),t=Math.ceil(n/kc+4),Vc=!1;r%2&&(a=a.times(o),l9e(a.d,t)),r=mL(r/2),r!==0;)o=o.times(o),l9e(o.d,t);return Vc=!0,s.s<0?new c(Bp).div(a):Xl(a,n)}}else if(i<0)throw Error(xg+"NaN");return i=i<0&&s.d[Math.max(t,r)]&1?-1:1,o.s=1,Vc=!1,a=s.times(Z8(o,n+d)),Vc=!0,a=_dt(a),a.s=i,a};xa.toPrecision=function(s,t){var r,n,a=this,i=a.constructor;return s===void 0?(r=_u(a),n=H3(a,r<=i.toExpNeg||r>=i.toExpPos)):(Cv(s,1,hL),t===void 0?t=i.rounding:Cv(t,0,8),a=Xl(new i(a),s,t),r=_u(a),n=H3(a,s<=r||r<=i.toExpNeg,s)),n};xa.toSignificantDigits=xa.tosd=function(s,t){var r=this,n=r.constructor;return s===void 0?(s=n.precision,t=n.rounding):(Cv(s,1,hL),t===void 0?t=n.rounding:Cv(t,0,8)),Xl(new n(r),s,t)};xa.toString=xa.valueOf=xa.val=xa.toJSON=xa[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=_u(s),r=s.constructor;return H3(s,t<=r.toExpNeg||t>=r.toExpPos)};function bdt(s,t){var r,n,a,i,l,o,c,d,h=s.constructor,m=h.precision;if(!s.s||!t.s)return t.s||(t=new h(s)),Vc?Xl(t,m):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(n=c,i=-i,o=d.length):(n=d,a=l,o=c.length),l=Math.ceil(m/kc),o=l>o?l+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,n=d,d=c,c=n),r=0;i;)r=(c[--i]=c[i]+d[i]+r)/hh|0,c[i]%=hh;for(r&&(c.unshift(r),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Vc?Xl(t,m):t}function Cv(s,t,r){if(s!==~~s||sr)throw Error(m3+s)}function K0(s){var t,r,n,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 r(n,a,i){for(var l=0;i--;)n[i]-=l,l=n[i]1;)n.shift()}return function(n,a,i,l){var o,c,d,h,m,x,y,v,w,b,N,S,T,A,I,D,R,$,F=n.constructor,z=n.s==a.s?1:-1,Q=n.d,K=a.d;if(!n.s)return new F(n);if(!a.s)throw Error(xg+"Division by zero");for(c=n.e-a.e,R=K.length,I=Q.length,y=new F(z),v=y.d=[],d=0;K[d]==(Q[d]||0);)++d;if(K[d]>(Q[d]||0)&&--c,i==null?S=i=F.precision:l?S=i+(_u(n)-_u(a))+1:S=i,S<0)return new F(0);if(S=S/kc+2|0,d=0,R==1)for(h=0,K=K[0],S++;(d1&&(K=s(K,h),Q=s(Q,h),R=K.length,I=Q.length),A=R,w=Q.slice(0,R),b=w.length;b=hh/2&&++D;do h=0,o=t(K,w,R,b),o<0?(N=w[0],R!=b&&(N=N*hh+(w[1]||0)),h=N/D|0,h>1?(h>=hh&&(h=hh-1),m=s(K,h),x=m.length,b=w.length,o=t(m,w,x,b),o==1&&(h--,r(m,R16)throw Error(fTe+_u(s));if(!s.s)return new h(Bp);for(t==null?(Vc=!1,o=m):o=t,l=new h(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(n=Math.log(VC(2,d))/Math.LN10*2+5|0,o+=n,r=a=i=new h(Bp),h.precision=o;;){if(a=Xl(a.times(s),o),r=r.times(++c),l=i.plus(wb(a,r,o)),K0(l.d).slice(0,o)===K0(i.d).slice(0,o)){for(;d--;)i=Xl(i.times(i),o);return h.precision=m,t==null?(Vc=!0,Xl(i,m)):i}i=l}}function _u(s){for(var t=s.e*kc,r=s.d[0];r>=10;r/=10)t++;return t}function ebe(s,t,r){if(t>s.LN10.sd())throw Vc=!0,r&&(s.precision=r),Error(xg+"LN10 precision limit exceeded");return Xl(new s(s.LN10),t)}function cw(s){for(var t="";s--;)t+="0";return t}function Z8(s,t){var r,n,a,i,l,o,c,d,h,m=1,x=10,y=s,v=y.d,w=y.constructor,b=w.precision;if(y.s<1)throw Error(xg+(y.s?"NaN":"-Infinity"));if(y.eq(Bp))return new w(0);if(t==null?(Vc=!1,d=b):d=t,y.eq(10))return t==null&&(Vc=!0),ebe(w,d);if(d+=x,w.precision=d,r=K0(v),n=r.charAt(0),i=_u(y),Math.abs(i)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)y=y.times(s),r=K0(y.d),n=r.charAt(0),m++;i=_u(y),n>1?(y=new w("0."+r),i++):y=new w(n+"."+r.slice(1))}else return c=ebe(w,d+2,b).times(i+""),y=Z8(new w(n+"."+r.slice(1)),d-x).plus(c),w.precision=b,t==null?(Vc=!0,Xl(y,b)):y;for(o=l=y=wb(y.minus(Bp),y.plus(Bp),d),h=Xl(y.times(y),d),a=3;;){if(l=Xl(l.times(h),d),c=o.plus(wb(l,new w(a),d)),K0(c.d).slice(0,d)===K0(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(ebe(w,d+2,b).times(i+""))),o=wb(o,new w(m),d),w.precision=b,t==null?(Vc=!0,Xl(o,b)):o;o=c,a+=2}}function o9e(s,t){var r,n,a;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(n,a),t){if(a-=n,r=r-n-1,s.e=mL(r/kc),s.d=[],n=(r+1)%kc,r<0&&(n+=kc),nphe||s.e<-phe))throw Error(fTe+r)}else s.s=0,s.e=0,s.d=[0];return s}function Xl(s,t,r){var n,a,i,l,o,c,d,h,m=s.d;for(l=1,i=m[0];i>=10;i/=10)l++;if(n=t-l,n<0)n+=kc,a=t,d=m[h=0];else{if(h=Math.ceil((n+1)/kc),i=m.length,h>=i)return s;for(d=i=m[h],l=1;i>=10;i/=10)l++;n%=kc,a=n-kc+l}if(r!==void 0&&(i=VC(10,l-a-1),o=d/i%10|0,c=t<0||m[h+1]!==void 0||d%i,c=r<4?(o||c)&&(r==0||r==(s.s<0?3:2)):o>5||o==5&&(r==4||c||r==6&&(n>0?a>0?d/VC(10,l-a):0:m[h-1])%10&1||r==(s.s<0?8:7))),t<1||!m[0])return c?(i=_u(s),m.length=1,t=t-i-1,m[0]=VC(10,(kc-t%kc)%kc),s.e=mL(-t/kc)||0):(m.length=1,m[0]=s.e=s.s=0),s;if(n==0?(m.length=h,i=1,h--):(m.length=h+1,i=VC(10,kc-n),m[h]=a>0?(d/VC(10,l-a)%VC(10,a)|0)*i:0),c)for(;;)if(h==0){(m[0]+=i)==hh&&(m[0]=1,++s.e);break}else{if(m[h]+=i,m[h]!=hh)break;m[h--]=0,i=1}for(n=m.length;m[--n]===0;)m.pop();if(Vc&&(s.e>phe||s.e<-phe))throw Error(fTe+_u(s));return s}function wdt(s,t){var r,n,a,i,l,o,c,d,h,m,x=s.constructor,y=x.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new x(s),Vc?Xl(t,y):t;if(c=s.d,m=t.d,n=t.e,d=s.e,c=c.slice(),l=d-n,l){for(h=l<0,h?(r=c,l=-l,o=m.length):(r=m,n=d,o=c.length),a=Math.max(Math.ceil(y/kc),o)+2,l>a&&(l=a,r.length=1),r.reverse(),a=l;a--;)r.push(0);r.reverse()}else{for(a=c.length,o=m.length,h=a0;--a)c[o++]=0;for(a=m.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+cw(n):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+cw(-a-1)+i,r&&(n=r-l)>0&&(i+=cw(n))):a>=l?(i+=cw(a+1-l),r&&(n=r-a-1)>0&&(i=i+"."+cw(n))):((n=a+1)0&&(a+1===l&&(i+="."),i+=cw(n))),s.s<0?"-"+i:i}function l9e(s,t){if(s.length>t)return s.length=t,!0}function jdt(s){var t,r,n;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(m3+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 o9e(l,i.toString())}else if(typeof i!="string")throw Error(m3+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,Y0s.test(i))o9e(l,i);else throw Error(m3+i)}if(a.prototype=xa,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=jdt,a.config=a.set=Z0s,s===void 0&&(s={}),s)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=a[t+1]&&n<=a[t+2])this[r]=n;else throw Error(m3+r+": "+n);if((n=s[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(m3+r+": "+n);return this}var pTe=jdt(K0s);Bp=new pTe(1);const Dl=pTe;function X0s(s){return tvs(s)||evs(s)||J0s(s)||Q0s()}function Q0s(){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 J0s(s,t){if(s){if(typeof s=="string")return xNe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return xNe(s,t)}}function evs(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function tvs(s){if(Array.isArray(s))return xNe(s)}function xNe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=t?r.apply(void 0,a):s(t-l,c9e(function(){for(var o=arguments.length,c=new Array(o),d=0;ds.length)&&(t=s.length);for(var r=0,n=new Array(t);r"u"||!(Symbol.iterator in Object(s)))){var r=[],n=!0,a=!1,i=void 0;try{for(var l=s[Symbol.iterator](),o;!(n=(o=l.next()).done)&&(r.push(o.value),!(t&&r.length===t));n=!0);}catch(c){a=!0,i=c}finally{try{!n&&l.return!=null&&l.return()}finally{if(a)throw i}}return r}}function xvs(s){if(Array.isArray(s))return s}function Tdt(s){var t=X8(s,2),r=t[0],n=t[1],a=r,i=n;return r>n&&(a=n,i=r),[a,i]}function Edt(s,t,r){if(s.lte(0))return new Dl(0);var n=sxe.getDigitCount(s.toNumber()),a=new Dl(10).pow(n),i=s.div(a),l=n!==1?.05:.1,o=new Dl(Math.ceil(i.div(l).toNumber())).add(r).mul(l),c=o.mul(a);return t?c:new Dl(Math.ceil(c))}function gvs(s,t,r){var n=1,a=new Dl(s);if(!a.isint()&&r){var i=Math.abs(s);i<1?(n=new Dl(10).pow(sxe.getDigitCount(s)-1),a=new Dl(Math.floor(a.div(n).toNumber())).mul(n)):i>1&&(a=new Dl(Math.floor(s)))}else s===0?a=new Dl(Math.floor((t-1)/2)):r||(a=new Dl(Math.floor(s)));var l=Math.floor((t-1)/2),o=avs(nvs(function(c){return a.add(new Dl(c-l).mul(n)).toNumber()}),gNe);return o(0,t)}function Adt(s,t,r,n){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-s)/(r-1)))return{step:new Dl(0),tickMin:new Dl(0),tickMax:new Dl(0)};var i=Edt(new Dl(t).sub(s).div(r-1),n,a),l;s<=0&&t>=0?l=new Dl(0):(l=new Dl(s).add(t).div(2),l=l.sub(new Dl(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Dl(t).sub(l).div(i).toNumber()),d=o+c+1;return d>r?Adt(s,t,r,n,a+1):(d0?c+(r-d):c,o=t>0?o:o+(r-d)),{step:i,tickMin:l.sub(new Dl(o).mul(i)),tickMax:l.add(new Dl(c).mul(i))})}function yvs(s){var t=X8(s,2),r=t[0],n=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=Tdt([r,n]),c=X8(o,2),d=c[0],h=c[1];if(d===-1/0||h===1/0){var m=h===1/0?[d].concat(vNe(gNe(0,a-1).map(function(){return 1/0}))):[].concat(vNe(gNe(0,a-1).map(function(){return-1/0})),[h]);return r>n?yNe(m):m}if(d===h)return gvs(d,a,i);var x=Adt(d,h,l,i),y=x.step,v=x.tickMin,w=x.tickMax,b=sxe.rangeStep(v,w.add(new Dl(.1).mul(y)),y);return r>n?yNe(b):b}function vvs(s,t){var r=X8(s,2),n=r[0],a=r[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Tdt([n,a]),o=X8(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[n,a];if(c===d)return[c];var h=Math.max(t,2),m=Edt(new Dl(d).sub(c).div(h-1),i,0),x=[].concat(vNe(sxe.rangeStep(new Dl(c),new Dl(d).sub(new Dl(.99).mul(m)),m)),[d]);return n>a?yNe(x):x}var bvs=Sdt(yvs),_vs=Sdt(vvs),wvs="Invariant failed";function G3(s,t){throw new Error(wvs)}var jvs=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function ZM(s){"@babel/helpers - typeof";return ZM=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},ZM(s)}function xhe(){return xhe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Avs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Mvs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Ivs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1&&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=(r=n==null?void 0:n.length)!==null&&r!==void 0?r: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,m=a[d].coordinate,x=d>=o-1?a[0].coordinate:a[d+1].coordinate,y=void 0;if(uf(m-h)!==uf(x-m)){var v=[];if(uf(x-m)===uf(c[1]-c[0])){y=x;var w=m+c[1]-c[0];v[0]=Math.min(w,(w+h)/2),v[1]=Math.max(w,(w+h)/2)}else{y=h;var b=x+c[1]-c[0];v[0]=Math.min(m,(b+m)/2),v[1]=Math.max(m,(b+m)/2)}var N=[Math.min(m,(y+m)/2),Math.max(m,(y+m)/2)];if(t>N[0]&&t<=N[1]||t>=v[0]&&t<=v[1]){l=a[d].index;break}}else{var S=Math.min(h,x),T=Math.max(h,x);if(t>(S+m)/2&&t<=(T+m)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(n[A].coordinate+n[A-1].coordinate)/2&&t<=(n[A].coordinate+n[A+1].coordinate)/2||A===o-1&&t>(n[A].coordinate+n[A-1].coordinate)/2){l=n[A].index;break}return l},xTe=function(t){var r,n=t,a=n.type.displayName,i=(r=t.type)!==null&&r!==void 0&&r.defaultProps?kd(kd({},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},Yvs=function(t){var r=t.barSize,n=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(N&&N.length){var S=N[0].type.defaultProps,T=S!==void 0?kd(kd({},S),N[0].props):N[0].props,A=T.barSize,I=T[b];l[I]||(l[I]=[]);var D=Pi(A)?r:A;l[I].push({item:N[0],stackList:N.slice(1),barSize:Pi(D)?void 0:hf(D,n,0)})}}return l},Zvs=function(t){var r=t.barGap,n=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=hf(r,a,0,!0),h,m=[];if(l[0].barSize===+l[0].barSize){var x=!1,y=a/c,v=l.reduce(function(A,I){return A+I.barSize||0},0);v+=(c-1)*d,v>=a&&(v-=(c-1)*d,d=0),v>=a&&y>0&&(x=!0,y*=.9,v=c*y);var w=(a-v)/2>>0,b={offset:w-d,size:0};h=l.reduce(function(A,I){var D={item:I.item,position:{offset:b.offset+b.size+d,size:x?y:I.barSize}},R=[].concat(h9e(A),[D]);return b=R[R.length-1].position,I.stackList&&I.stackList.length&&I.stackList.forEach(function($){R.push({item:$,position:b})}),R},m)}else{var N=hf(n,a,0,!0);a-2*N-(c-1)*d<=0&&(d=0);var S=(a-2*N-(c-1)*d)/c;S>1&&(S>>=0);var T=o===+o?Math.min(S,o):S;h=l.reduce(function(A,I,D){var R=[].concat(h9e(A),[{item:I.item,position:{offset:N+(S+d)*D+(S-T)/2,size:T}}]);return I.stackList&&I.stackList.length&&I.stackList.forEach(function($){R.push({item:$,position:R[R.length-1].position})}),R},m)}return h},Xvs=function(t,r,n,a){var i=n.children,l=n.width,o=n.margin,c=l-(o.left||0)-(o.right||0),d=Pdt({children:i,legendWidth:c});if(d){var h=a||{},m=h.width,x=h.height,y=d.align,v=d.verticalAlign,w=d.layout;if((w==="vertical"||w==="horizontal"&&v==="middle")&&y!=="center"&&Sn(t[y]))return kd(kd({},t),{},WA({},y,t[y]+(m||0)));if((w==="horizontal"||w==="vertical"&&y==="center")&&v!=="middle"&&Sn(t[v]))return kd(kd({},t),{},WA({},v,t[v]+(x||0)))}return t},Qvs=function(t,r,n){return Pi(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},Ddt=function(t,r,n,a,i){var l=r.props.children,o=Xp(l,DB).filter(function(d){return Qvs(a,i,d.props.direction)});if(o&&o.length){var c=o.map(function(d){return d.props.dataKey});return t.reduce(function(d,h){var m=$u(h,n);if(Pi(m))return d;var x=Array.isArray(m)?[exe(m),Jpe(m)]:[m,m],y=c.reduce(function(v,w){var b=$u(h,w,0),N=x[0]-Math.abs(Array.isArray(b)?b[0]:b),S=x[1]+Math.abs(Array.isArray(b)?b[1]:b);return[Math.min(N,v[0]),Math.max(S,v[1])]},[1/0,-1/0]);return[Math.min(y[0],d[0]),Math.max(y[1],d[1])]},[1/0,-1/0])}return null},Jvs=function(t,r,n,a,i){var l=r.map(function(o){return Ddt(t,o,n,i,a)}).filter(function(o){return!Pi(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},Rdt=function(t,r,n,a,i){var l=r.map(function(c){var d=c.props.dataKey;return n==="number"&&d&&Ddt(t,c,d,a)||TO(t,d,n,i)});if(n==="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 h=0,m=d.length;h=2?uf(o[0]-o[1])*2*d:d,r&&(t.ticks||t.niceTicks)){var h=(t.ticks||t.niceTicks).map(function(m){var x=i?i.indexOf(m):m;return{coordinate:a(x)+d,value:m,offset:d}});return h.filter(function(m){return!CB(m.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(m,x){return{coordinate:a(m)+d,value:m,index:x,offset:d}}):a.ticks&&!n?a.ticks(t.tickCount).map(function(m){return{coordinate:a(m)+d,value:m,offset:d}}):a.domain().map(function(m,x){return{coordinate:a(m)+d,value:i?i[m]:m,index:x,offset:d}})},tbe=new WeakMap,C$=function(t,r){if(typeof r!="function")return t;tbe.has(t)||tbe.set(t,new WeakMap);var n=tbe.get(t);if(n.has(r))return n.get(r);var a=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,a),a},Bdt=function(t,r,n){var a=t.scale,i=t.type,l=t.layout,o=t.axisType;if(a==="auto")return l==="radial"&&o==="radiusAxis"?{scale:H8(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:uhe(),realScaleType:"linear"}:i==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:CO(),realScaleType:"point"}:i==="category"?{scale:H8(),realScaleType:"band"}:{scale:uhe(),realScaleType:"linear"};if(U3(a)){var c="scale".concat(Bpe(a));return{scale:(i9e[c]||CO)(),realScaleType:i9e[c]?c:"point"}}return ki(a)?{scale:a}:{scale:CO(),realScaleType:"point"}},f9e=1e-4,zdt=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,a=t.range(),i=Math.min(a[0],a[1])-f9e,l=Math.max(a[0],a[1])+f9e,o=t(r[0]),c=t(r[n-1]);(ol||cl)&&t.domain([r[0],r[n-1]])}},e1s=function(t,r){if(!t)return null;for(var n=0,a=t.length;na)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]=0?(t[o][n][0]=i,t[o][n][1]=i+c,i=t[o][n][1]):(t[o][n][0]=l,t[o][n][1]=l+c,l=t[o][n][1])}},r1s=function(t){var r=t.length;if(!(r<=0))for(var n=0,a=t[0].length;n=0?(t[l][n][0]=i,t[l][n][1]=i+o,i=t[l][n][1]):(t[l][n][0]=0,t[l][n][1]=0)}},n1s={sign:s1s,expand:jos,none:UM,silhouette:Nos,wiggle:kos,positive:r1s},a1s=function(t,r,n){var a=r.map(function(o){return o.props.dataKey}),i=n1s[n],l=wos().keys(a).value(function(o,c){return+$u(o,c,0)}).order(W2e).offset(i);return l(t)},i1s=function(t,r,n,a,i,l){if(!t)return null;var o=l?r.reverse():r,c={},d=o.reduce(function(m,x){var y,v=(y=x.type)!==null&&y!==void 0&&y.defaultProps?kd(kd({},x.type.defaultProps),x.props):x.props,w=v.stackId,b=v.hide;if(b)return m;var N=v[n],S=m[N]||{hasStack:!1,stackGroups:{}};if(qu(w)){var T=S.stackGroups[w]||{numericAxisId:n,cateAxisId:a,items:[]};T.items.push(x),S.hasStack=!0,S.stackGroups[w]=T}else S.stackGroups[oL("_stackId_")]={numericAxisId:n,cateAxisId:a,items:[x]};return kd(kd({},m),{},WA({},N,S))},c),h={};return Object.keys(d).reduce(function(m,x){var y=d[x];if(y.hasStack){var v={};y.stackGroups=Object.keys(y.stackGroups).reduce(function(w,b){var N=y.stackGroups[b];return kd(kd({},w),{},WA({},b,{numericAxisId:n,cateAxisId:a,items:N.items,stackedData:a1s(t,N.items,i)}))},v)}return kd(kd({},m),{},WA({},x,y))},h)},$dt=function(t,r){var n=r.realScaleType,a=r.type,i=r.tickCount,l=r.originalDomain,o=r.allowDecimals,c=n||r.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 h=bvs(d,i,o);return t.domain([exe(h),Jpe(h)]),{niceTicks:h}}if(i&&a==="number"){var m=t.domain(),x=_vs(m,i,o);return{niceTicks:x}}return null};function p9e(s){var t=s.axis,r=s.ticks,n=s.bandSize,a=s.entry,i=s.index,l=s.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!Pi(a[t.dataKey])){var o=Vue(r,"value",a[t.dataKey]);if(o)return o.coordinate+n/2}return r[i]?r[i].coordinate+n/2:null}var c=$u(a,Pi(l)?t.dataKey:l);return Pi(c)?null:t.scale(c)}var x9e=function(t){var r=t.axis,n=t.ticks,a=t.offset,i=t.bandSize,l=t.entry,o=t.index;if(r.type==="category")return n[o]?n[o].coordinate+a:null;var c=$u(l,r.dataKey,r.domain[o]);return Pi(c)?null:r.scale(c)-i/2+a},o1s=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var a=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return a<=0&&i>=0?0:i<0?i:a}return n[0]},l1s=function(t,r){var n,a=(n=t.type)!==null&&n!==void 0&&n.defaultProps?kd(kd({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(qu(i)){var l=r[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},c1s=function(t){return t.reduce(function(r,n){return[exe(n.concat([r[0]]).filter(Sn)),Jpe(n.concat([r[1]]).filter(Sn))]},[1/0,-1/0])},Udt=function(t,r,n){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,h){var m=c1s(h.slice(r,n+1));return[Math.min(d[0],m[0]),Math.max(d[1],m[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})},g9e=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,y9e=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,jNe=function(t,r,n){if(ki(t))return t(r,n);if(!Array.isArray(t))return r;var a=[];if(Sn(t[0]))a[0]=n?t[0]:Math.min(t[0],r[0]);else if(g9e.test(t[0])){var i=+g9e.exec(t[0])[1];a[0]=r[0]-i}else ki(t[0])?a[0]=t[0](r[0]):a[0]=r[0];if(Sn(t[1]))a[1]=n?t[1]:Math.max(t[1],r[1]);else if(y9e.test(t[1])){var l=+y9e.exec(t[1])[1];a[1]=r[1]+l}else ki(t[1])?a[1]=t[1](r[1]):a[1]=r[1];return a},yhe=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!n||a>0)return a}if(t&&r&&r.length>=2){for(var i=V5e(r,function(m){return m.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var r=0,n=new Array(t);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},y1s=function(t,r,n,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,h=hf(t.cx,l,l/2),m=hf(t.cy,o,o/2),x=Hdt(l,o,n),y=hf(t.innerRadius,x,0),v=hf(t.outerRadius,x,x*.8),w=Object.keys(r);return w.reduce(function(b,N){var S=r[N],T=S.domain,A=S.reversed,I;if(Pi(S.range))a==="angleAxis"?I=[c,d]:a==="radiusAxis"&&(I=[y,v]),A&&(I=[I[1],I[0]]);else{I=S.range;var D=I,R=h1s(D,2);c=R[0],d=R[1]}var $=Bdt(S,i),F=$.realScaleType,z=$.scale;z.domain(T).range(I),zdt(z);var Q=$dt(z,U1(U1({},S),{},{realScaleType:F})),K=U1(U1(U1({},S),Q),{},{range:I,radius:v,realScaleType:F,scale:z,cx:h,cy:m,innerRadius:y,outerRadius:v,startAngle:c,endAngle:d});return U1(U1({},b),{},Vdt({},N,K))},{})},v1s=function(t,r){var n=t.x,a=t.y,i=r.x,l=r.y;return Math.sqrt(Math.pow(n-i,2)+Math.pow(a-l,2))},b1s=function(t,r){var n=t.x,a=t.y,i=r.cx,l=r.cy,o=v1s({x:n,y:a},{x:i,y:l});if(o<=0)return{radius:o};var c=(n-i)/o,d=Math.acos(c);return a>l&&(d=2*Math.PI-d),{radius:o,angle:g1s(d),angleInRadian:d}},_1s=function(t){var r=t.startAngle,n=t.endAngle,a=Math.floor(r/360),i=Math.floor(n/360),l=Math.min(a,i);return{startAngle:r-l*360,endAngle:n-l*360}},w1s=function(t,r){var n=r.startAngle,a=r.endAngle,i=Math.floor(n/360),l=Math.floor(a/360),o=Math.min(i,l);return t+o*360},w9e=function(t,r){var n=t.x,a=t.y,i=b1s({x:n,y:a},r),l=i.radius,o=i.angle,c=r.innerRadius,d=r.outerRadius;if(ld)return!1;if(l===0)return!0;var h=_1s(r),m=h.startAngle,x=h.endAngle,y=o,v;if(m<=x){for(;y>x;)y-=360;for(;y=m&&y<=x}else{for(;y>m;)y-=360;for(;y=x&&y<=m}return v?U1(U1({},r),{},{radius:l,angle:w1s(y,r)}):null},Gdt=function(t){return!k.isValidElement(t)&&!ki(t)&&typeof t!="boolean"?t.className:""};function tF(s){"@babel/helpers - typeof";return tF=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},tF(s)}var j1s=["offset"];function N1s(s){return T1s(s)||C1s(s)||S1s(s)||k1s()}function k1s(){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 S1s(s,t){if(s){if(typeof s=="string")return NNe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return NNe(s,t)}}function C1s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function T1s(s){if(Array.isArray(s))return NNe(s)}function NNe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function A1s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function j9e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function Mu(s){for(var t=1;t=0?1:-1,T,A;a==="insideStart"?(T=y+S*l,A=w):a==="insideEnd"?(T=v-S*l,A=!w):a==="end"&&(T=v+S*l,A=w),A=N<=0?A:!A;var I=hc(d,h,b,T),D=hc(d,h,b,T+(A?1:-1)*359),R="M".concat(I.x,",").concat(I.y,` A`).concat(b,",").concat(b,",0,1,").concat(A?0:1,`, `).concat(D.x,",").concat(D.y),$=Pi(t.id)?oL("recharts-radial-line-"):t.id;return wt.createElement("text",sF({},n,{dominantBaseline:"central",className:Fi("recharts-radial-bar-label",o)}),wt.createElement("defs",null,wt.createElement("path",{id:$,d:R})),wt.createElement("textPath",{xlinkHref:"#".concat($)},r))},O1s=function(t){var r=t.viewBox,n=t.offset,a=t.position,i=r,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,h=i.startAngle,m=i.endAngle,x=(h+m)/2;if(a==="outside"){var y=hc(l,o,d+n,x),v=y.x,w=y.y;return{x:v,y:w,textAnchor:v>=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 b=(c+d)/2,N=hc(l,o,b,x),S=N.x,T=N.y;return{x:S,y:T,textAnchor:"middle",verticalAnchor:"middle"}},F1s=function(t){var r=t.viewBox,n=t.parentViewBox,a=t.offset,i=t.position,l=r,o=l.x,c=l.y,d=l.width,h=l.height,m=h>=0?1:-1,x=m*a,y=m>0?"end":"start",v=m>0?"start":"end",w=d>=0?1:-1,b=w*a,N=w>0?"end":"start",S=w>0?"start":"end";if(i==="top"){var T={x:o+d/2,y:c-m*a,textAnchor:"middle",verticalAnchor:y};return Mu(Mu({},T),n?{height:Math.max(c-n.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+h+x,textAnchor:"middle",verticalAnchor:v};return Mu(Mu({},A),n?{height:Math.max(n.y+n.height-(c+h),0),width:d}:{})}if(i==="left"){var I={x:o-b,y:c+h/2,textAnchor:N,verticalAnchor:"middle"};return Mu(Mu({},I),n?{width:Math.max(I.x-n.x,0),height:h}:{})}if(i==="right"){var D={x:o+d+b,y:c+h/2,textAnchor:S,verticalAnchor:"middle"};return Mu(Mu({},D),n?{width:Math.max(n.x+n.width-D.x,0),height:h}:{})}var R=n?{width:d,height:h}:{};return i==="insideLeft"?Mu({x:o+b,y:c+h/2,textAnchor:S,verticalAnchor:"middle"},R):i==="insideRight"?Mu({x:o+d-b,y:c+h/2,textAnchor:N,verticalAnchor:"middle"},R):i==="insideTop"?Mu({x:o+d/2,y:c+x,textAnchor:"middle",verticalAnchor:v},R):i==="insideBottom"?Mu({x:o+d/2,y:c+h-x,textAnchor:"middle",verticalAnchor:y},R):i==="insideTopLeft"?Mu({x:o+b,y:c+x,textAnchor:S,verticalAnchor:v},R):i==="insideTopRight"?Mu({x:o+d-b,y:c+x,textAnchor:N,verticalAnchor:v},R):i==="insideBottomLeft"?Mu({x:o+b,y:c+h-x,textAnchor:S,verticalAnchor:y},R):i==="insideBottomRight"?Mu({x:o+d-b,y:c+h-x,textAnchor:N,verticalAnchor:y},R):rL(i)&&(Sn(i.x)||c4(i.x))&&(Sn(i.y)||c4(i.y))?Mu({x:o+hf(i.x,d),y:c+hf(i.y,h),textAnchor:"end",verticalAnchor:"end"},R):Mu({x:o+d/2,y:c+h/2,textAnchor:"middle",verticalAnchor:"middle"},R)},B1s=function(t){return"cx"in t&&Sn(t.cx)};function xh(s){var t=s.offset,r=t===void 0?5:t,n=E1s(s,j1s),a=Mu({offset:r},n),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,h=a.className,m=h===void 0?"":h,x=a.textBreakAll;if(!i||Pi(o)&&Pi(c)&&!k.isValidElement(d)&&!ki(d))return null;if(k.isValidElement(d))return k.cloneElement(d,a);var y;if(ki(d)){if(y=k.createElement(d,a),k.isValidElement(y))return y}else y=P1s(a);var v=B1s(i),w=ai(a,!0);if(v&&(l==="insideStart"||l==="insideEnd"||l==="end"))return R1s(a,y,w);var b=v?O1s(a):F1s(a);return wt.createElement(V3,sF({className:Fi("recharts-label",m)},w,b,{breakAll:x}),y)}xh.displayName="Label";var Wdt=function(t){var r=t.cx,n=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,h=t.outerRadius,m=t.x,x=t.y,y=t.top,v=t.left,w=t.width,b=t.height,N=t.clockWise,S=t.labelViewBox;if(S)return S;if(Sn(w)&&Sn(b)){if(Sn(m)&&Sn(x))return{x:m,y:x,width:w,height:b};if(Sn(y)&&Sn(v))return{x:y,y:v,width:w,height:b}}return Sn(m)&&Sn(x)?{x:m,y:x,width:0,height:0}:Sn(r)&&Sn(n)?{cx:r,cy:n,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:h||c||o||0,clockWise:N}:t.viewBox?t.viewBox:{}},z1s=function(t,r){return t?t===!0?wt.createElement(xh,{key:"label-implicit",viewBox:r}):qu(t)?wt.createElement(xh,{key:"label-implicit",viewBox:r,value:t}):k.isValidElement(t)?t.type===xh?k.cloneElement(t,{key:"label-implicit",viewBox:r}):wt.createElement(xh,{key:"label-implicit",content:t,viewBox:r}):ki(t)?wt.createElement(xh,{key:"label-implicit",content:t,viewBox:r}):rL(t)?wt.createElement(xh,sF({viewBox:r},t,{key:"label-implicit"})):null:null},$1s=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var a=t.children,i=Wdt(t),l=Xp(a,xh).map(function(c,d){return k.cloneElement(c,{viewBox:r||i,key:"label-".concat(d)})});if(!n)return l;var o=z1s(t.label,r||i);return[o].concat(N1s(l))};xh.parseViewBox=Wdt;xh.renderCallByParent=$1s;function U1s(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var q1s=U1s;const V1s=Ao(q1s);function rF(s){"@babel/helpers - typeof";return rF=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},rF(s)}var H1s=["valueAccessor"],G1s=["data","dataKey","clockWise","id","textBreakAll"];function W1s(s){return X1s(s)||Z1s(s)||Y1s(s)||K1s()}function K1s(){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 Y1s(s,t){if(s){if(typeof s=="string")return kNe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return kNe(s,t)}}function Z1s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function X1s(s){if(Array.isArray(s))return kNe(s)}function kNe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function tbs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var sbs=function(t){return Array.isArray(t.value)?V1s(t.value):t.value};function jb(s){var t=s.valueAccessor,r=t===void 0?sbs:t,n=S9e(s,H1s),a=n.data,i=n.dataKey,l=n.clockWise,o=n.id,c=n.textBreakAll,d=S9e(n,G1s);return!a||!a.length?null:wt.createElement(Jo,{className:"recharts-label-list"},a.map(function(h,m){var x=Pi(i)?r(h,m):$u(h&&h.payload,i),y=Pi(o)?{}:{id:"".concat(o,"-").concat(m)};return wt.createElement(xh,bhe({},ai(h,!0),d,y,{parentViewBox:h.parentViewBox,value:x,textBreakAll:c,viewBox:xh.parseViewBox(Pi(l)?h:k9e(k9e({},h),{},{clockWise:l})),key:"label-".concat(m),index:m}))}))}jb.displayName="LabelList";function rbs(s,t){return s?s===!0?wt.createElement(jb,{key:"labelList-implicit",data:t}):wt.isValidElement(s)||ki(s)?wt.createElement(jb,{key:"labelList-implicit",data:t,content:s}):rL(s)?wt.createElement(jb,bhe({data:t},s,{key:"labelList-implicit"})):null:null}function nbs(s,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!s||!s.children&&r&&!s.label)return null;var n=s.children,a=Xp(n,jb).map(function(l,o){return k.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!r)return a;var i=rbs(s.label,t);return[i].concat(W1s(a))}jb.renderCallByParent=nbs;function nF(s){"@babel/helpers - typeof";return nF=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},nF(s)}function SNe(){return SNe=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(m.x,",").concat(m.y,` `);if(a>0){var y=hc(r,n,a,l),v=hc(r,n,a,d);x+="L ".concat(v.x,",").concat(v.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(y.x,",").concat(y.y," Z")}else x+="L ".concat(r,",").concat(n," Z");return x},cbs=function(t){var r=t.cx,n=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,h=t.endAngle,m=uf(h-d),x=T$({cx:r,cy:n,radius:i,angle:d,sign:m,cornerRadius:l,cornerIsExternal:c}),y=x.circleTangency,v=x.lineTangency,w=x.theta,b=T$({cx:r,cy:n,radius:i,angle:h,sign:-m,cornerRadius:l,cornerIsExternal:c}),N=b.circleTangency,S=b.lineTangency,T=b.theta,A=c?Math.abs(d-h):Math.abs(d-h)-w-T;if(A<0)return o?"M ".concat(v.x,",").concat(v.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 `):Kdt({cx:r,cy:n,innerRadius:a,outerRadius:i,startAngle:d,endAngle:h});var I="M ".concat(v.x,",").concat(v.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(y.x,",").concat(y.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(m<0),",").concat(N.x,",").concat(N.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(S.x,",").concat(S.y,` `);if(a>0){var D=T$({cx:r,cy:n,radius:a,angle:d,sign:m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),R=D.circleTangency,$=D.lineTangency,F=D.theta,z=T$({cx:r,cy:n,radius:a,angle:h,sign:-m,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),Q=z.circleTangency,K=z.lineTangency,X=z.theta,Z=c?Math.abs(d-h):Math.abs(d-h)-F-X;if(Z<0&&l===0)return"".concat(I,"L").concat(r,",").concat(n,"Z");I+="L".concat(K.x,",").concat(K.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat(Q.x,",").concat(Q.y,` A`).concat(a,",").concat(a,",0,").concat(+(Z>180),",").concat(+(m>0),",").concat(R.x,",").concat(R.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(m<0),",").concat($.x,",").concat($.y,"Z")}else I+="L".concat(r,",").concat(n,"Z");return I},dbs={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Ydt=function(t){var r=T9e(T9e({},dbs),t),n=r.cx,a=r.cy,i=r.innerRadius,l=r.outerRadius,o=r.cornerRadius,c=r.forceCornerRadius,d=r.cornerIsExternal,h=r.startAngle,m=r.endAngle,x=r.className;if(l0&&Math.abs(h-m)<360?b=cbs({cx:n,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(w,v/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:h,endAngle:m}):b=Kdt({cx:n,cy:a,innerRadius:i,outerRadius:l,startAngle:h,endAngle:m}),wt.createElement("path",SNe({},ai(r,!0),{className:y,d:b,role:"img"}))};function aF(s){"@babel/helpers - typeof";return aF=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},aF(s)}function CNe(){return CNe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0;)if(!r.equals(s[n],t[n],n,n,s,t,r))return!1;return!0}function kbs(s,t){return fL(s.getTime(),t.getTime())}function R9e(s,t,r){if(s.size!==t.size)return!1;for(var n={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,h=0;(o=c.next())&&!o.done;){var m=l.value,x=m[0],y=m[1],v=o.value,w=v[0],b=v[1];!d&&!n[h]&&(d=r.equals(x,w,i,h,s,t,r)&&r.equals(y,b,x,w,s,t,r))&&(n[h]=!0),h++}if(!d)return!1;i++}return!0}function Sbs(s,t,r){var n=D9e(s),a=n.length;if(D9e(t).length!==a)return!1;for(var i;a-- >0;)if(i=n[a],i===eut&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!Jdt(t,i)||!r.equals(s[i],t[i],i,i,s,t,r))return!1;return!0}function mD(s,t,r){var n=L9e(s),a=n.length;if(L9e(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=n[a],i===eut&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!Jdt(t,i)||!r.equals(s[i],t[i],i,i,s,t,r)||(l=P9e(s,i),o=P9e(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function Cbs(s,t){return fL(s.valueOf(),t.valueOf())}function Tbs(s,t){return s.source===t.source&&s.flags===t.flags}function O9e(s,t,r){if(s.size!==t.size)return!1;for(var n={},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&&!n[d]&&(c=r.equals(i.value,l.value,i.value,l.value,s,t,r))&&(n[d]=!0),d++;if(!c)return!1}return!0}function Ebs(s,t){var r=s.length;if(t.length!==r)return!1;for(;r-- >0;)if(s[r]!==t[r])return!1;return!0}var Abs="[object Arguments]",Mbs="[object Boolean]",Ibs="[object Date]",Lbs="[object Map]",Pbs="[object Number]",Dbs="[object Object]",Rbs="[object RegExp]",Obs="[object Set]",Fbs="[object String]",Bbs=Array.isArray,F9e=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,B9e=Object.assign,zbs=Object.prototype.toString.call.bind(Object.prototype.toString);function $bs(s){var t=s.areArraysEqual,r=s.areDatesEqual,n=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(h,m,x){if(h===m)return!0;if(h==null||m==null||typeof h!="object"||typeof m!="object")return h!==h&&m!==m;var y=h.constructor;if(y!==m.constructor)return!1;if(y===Object)return a(h,m,x);if(Bbs(h))return t(h,m,x);if(F9e!=null&&F9e(h))return c(h,m,x);if(y===Date)return r(h,m,x);if(y===RegExp)return l(h,m,x);if(y===Map)return n(h,m,x);if(y===Set)return o(h,m,x);var v=zbs(h);return v===Ibs?r(h,m,x):v===Rbs?l(h,m,x):v===Lbs?n(h,m,x):v===Obs?o(h,m,x):v===Dbs?typeof h.then!="function"&&typeof m.then!="function"&&a(h,m,x):v===Abs?a(h,m,x):v===Mbs||v===Pbs||v===Fbs?i(h,m,x):!1}}function Ubs(s){var t=s.circular,r=s.createCustomConfig,n=s.strict,a={areArraysEqual:n?mD:Nbs,areDatesEqual:kbs,areMapsEqual:n?I9e(R9e,mD):R9e,areObjectsEqual:n?mD:Sbs,arePrimitiveWrappersEqual:Cbs,areRegExpsEqual:Tbs,areSetsEqual:n?I9e(O9e,mD):O9e,areTypedArraysEqual:n?mD:Ebs};if(r&&(a=B9e({},a,r(a))),t){var i=A$(a.areArraysEqual),l=A$(a.areMapsEqual),o=A$(a.areObjectsEqual),c=A$(a.areSetsEqual);a=B9e({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function qbs(s){return function(t,r,n,a,i,l,o){return s(t,r,o)}}function Vbs(s){var t=s.circular,r=s.comparator,n=s.createState,a=s.equals,i=s.strict;if(n)return function(c,d){var h=n(),m=h.cache,x=m===void 0?t?new WeakMap:void 0:m,y=h.meta;return r(c,d,{cache:x,equals:a,meta:y,strict:i})};if(t)return function(c,d){return r(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 r(c,d,l)}}var Hbs=d2();d2({strict:!0});d2({circular:!0});d2({circular:!0,strict:!0});d2({createInternalComparator:function(){return fL}});d2({strict:!0,createInternalComparator:function(){return fL}});d2({circular:!0,createInternalComparator:function(){return fL}});d2({circular:!0,createInternalComparator:function(){return fL},strict:!0});function d2(s){s===void 0&&(s={});var t=s.circular,r=t===void 0?!1:t,n=s.createInternalComparator,a=s.createState,i=s.strict,l=i===void 0?!1:i,o=Ubs(s),c=$bs(o),d=n?n(c):qbs(c);return Vbs({circular:r,comparator:c,createState:a,equals:d,strict:l})}function Gbs(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function z9e(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function a(i){r<0&&(r=i),i-r>t?(s(i),r=-1):Gbs(a)};requestAnimationFrame(n)}function TNe(s){"@babel/helpers - typeof";return TNe=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},TNe(s)}function Wbs(s){return Xbs(s)||Zbs(s)||Ybs(s)||Kbs()}function Kbs(){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 Ybs(s,t){if(s){if(typeof s=="string")return $9e(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return $9e(s,t)}}function $9e(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r1?1:N<0?0:N},w=function(N){for(var S=N>1?1:N,T=S,A=0;A<8;++A){var I=m(T)-S,D=y(T);if(Math.abs(I-S)0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(h,m,x){var y=-(h-m)*n,v=x*i,w=x+(y-v)*o/1e3,b=x*o/1e3+h;return Math.abs(b-m)s.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function T_s(s,t){if(s==null)return{};var r={},n=Object.keys(s),a,i;for(i=0;i=0)&&(r[a]=s[a]);return r}function sbe(s){return I_s(s)||M_s(s)||A_s(s)||E_s()}function E_s(){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 A_s(s,t){if(s){if(typeof s=="string")return LNe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return LNe(s,t)}}function M_s(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function I_s(s){if(Array.isArray(s))return LNe(s)}function LNe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r"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 Nhe(s){return Nhe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Nhe(s)}var Tv=function(s){O_s(r,s);var t=F_s(r);function r(n,a){var i;L_s(this,r),i=t.call(this,n,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,h=l.to,m=l.steps,x=l.children,y=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(RNe(i)),i.changeStyle=i.changeStyle.bind(RNe(i)),!o||y<=0)return i.state={style:{}},typeof x=="function"&&(i.state={style:h}),DNe(i);if(m&&m.length)i.state={style:m[0].style};else if(d){if(typeof x=="function")return i.state={style:d},DNe(i);i.state={style:c?FD({},c,d):d}}else i.state={style:{}};return i}return D_s(r,[{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,h=i.to,m=i.from,x=this.state.style;if(o){if(!l){var y={style:c?FD({},c,h):h};this.state&&x&&(c&&x[c]!==h||!c&&x!==h)&&this.setState(y);return}if(!(Hbs(a.to,h)&&a.canBegin&&a.isActive)){var v=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var w=v||d?m:a.to;if(this.state&&x){var b={style:c?FD({},c,w):w};(c&&x[c]!==w||!c&&x!==w)&&this.setState(b)}this.runAnimation(Jg(Jg({},this.props),{},{from:w,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,h=a.begin,m=a.onAnimationEnd,x=a.onAnimationStart,y=k_s(l,o,f_s(d),c,this.changeStyle),v=function(){i.stopJSAnimation=y()};this.manager.start([x,h,v,c,m])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],h=d.style,m=d.duration,x=m===void 0?0:m,y=function(w,b,N){if(N===0)return w;var S=b.duration,T=b.easing,A=T===void 0?"ease":T,I=b.style,D=b.properties,R=b.onAnimationEnd,$=N>0?l[N-1]:b,F=D||Object.keys(I);if(typeof A=="function"||A==="spring")return[].concat(sbe(w),[i.runJSAnimation.bind(i,{from:$.style,to:I,duration:S,easing:A}),S]);var z=V9e(F,S,A),Q=Jg(Jg(Jg({},$.style),I),{},{transition:z});return[].concat(sbe(w),[Q,S,R]).filter(s_s)};return this.manager.start([c].concat(sbe(l.reduce(y,[h,Math.max(x,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=Qbs());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,h=a.onAnimationStart,m=a.onAnimationEnd,x=a.steps,y=a.children,v=this.manager;if(this.unSubscribe=v.subscribe(this.handleStyleChange),typeof d=="function"||typeof y=="function"||d==="spring"){this.runJSAnimation(a);return}if(x.length>1){this.runStepAnimation(a);return}var w=o?FD({},o,c):c,b=V9e(Object.keys(w),l,d);v.start([h,i,Jg(Jg({},w),{},{transition:b}),l,m])}},{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=C_s(a,S_s),d=k.Children.count(i),h=this.state.style;if(typeof i=="function")return i(h);if(!o||d===0||l<=0)return i;var m=function(y){var v=y.props,w=v.style,b=w===void 0?{}:w,N=v.className,S=k.cloneElement(y,Jg(Jg({},c),{},{style:Jg(Jg({},b),h),className:N}));return S};return d===1?m(k.Children.only(i)):wt.createElement("div",null,k.Children.map(i,function(x){return m(x)}))}}]),r}(k.PureComponent);Tv.displayName="Animate";Tv.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Tv.propTypes={from:bl.oneOfType([bl.object,bl.string]),to:bl.oneOfType([bl.object,bl.string]),attributeName:bl.string,duration:bl.number,begin:bl.number,easing:bl.oneOfType([bl.string,bl.func]),steps:bl.arrayOf(bl.shape({duration:bl.number.isRequired,style:bl.object.isRequired,easing:bl.oneOfType([bl.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),bl.func]),properties:bl.arrayOf("string"),onAnimationEnd:bl.func})),children:bl.oneOfType([bl.node,bl.func]),isActive:bl.bool,canBegin:bl.bool,onAnimationEnd:bl.func,shouldReAnimate:bl.bool,onAnimationStart:bl.func,onAnimationReStart:bl.func};function lF(s){"@babel/helpers - typeof";return lF=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},lF(s)}function khe(){return khe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0?1:-1,c=n>=0?1:-1,d=a>=0&&n>=0||a<0&&n<0?1:0,h;if(l>0&&i instanceof Array){for(var m=[0,0,0,0],x=0,y=4;xl?l:i[x];h="M".concat(t,",").concat(r+o*m[0]),m[0]>0&&(h+="A ".concat(m[0],",").concat(m[0],",0,0,").concat(d,",").concat(t+c*m[0],",").concat(r)),h+="L ".concat(t+n-c*m[1],",").concat(r),m[1]>0&&(h+="A ".concat(m[1],",").concat(m[1],",0,0,").concat(d,`, `).concat(t+n,",").concat(r+o*m[1])),h+="L ".concat(t+n,",").concat(r+a-o*m[2]),m[2]>0&&(h+="A ".concat(m[2],",").concat(m[2],",0,0,").concat(d,`, `).concat(t+n-c*m[2],",").concat(r+a)),h+="L ".concat(t+c*m[3],",").concat(r+a),m[3]>0&&(h+="A ".concat(m[3],",").concat(m[3],",0,0,").concat(d,`, `).concat(t,",").concat(r+a-o*m[3])),h+="Z"}else if(l>0&&i===+i&&i>0){var v=Math.min(l,i);h="M ".concat(t,",").concat(r+o*v,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t+c*v,",").concat(r,` L `).concat(t+n-c*v,",").concat(r,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t+n,",").concat(r+o*v,` L `).concat(t+n,",").concat(r+a-o*v,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t+n-c*v,",").concat(r+a,` L `).concat(t+c*v,",").concat(r+a,` A `).concat(v,",").concat(v,",0,0,").concat(d,",").concat(t,",").concat(r+a-o*v," Z")}else h="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(a," h ").concat(-n," Z");return h},K_s=function(t,r){if(!t||!r)return!1;var n=t.x,a=t.y,i=r.x,l=r.y,o=r.width,c=r.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),h=Math.max(i,i+o),m=Math.min(l,l+c),x=Math.max(l,l+c);return n>=d&&n<=h&&a>=m&&a<=x}return!1},Y_s={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},gTe=function(t){var r=Q9e(Q9e({},Y_s),t),n=k.useRef(),a=k.useState(-1),i=z_s(a,2),l=i[0],o=i[1];k.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var A=n.current.getTotalLength();A&&o(A)}catch{}},[]);var c=r.x,d=r.y,h=r.width,m=r.height,x=r.radius,y=r.className,v=r.animationEasing,w=r.animationDuration,b=r.animationBegin,N=r.isAnimationActive,S=r.isUpdateAnimationActive;if(c!==+c||d!==+d||h!==+h||m!==+m||h===0||m===0)return null;var T=Fi("recharts-rectangle",y);return S?wt.createElement(Tv,{canBegin:l>0,from:{width:h,height:m,x:c,y:d},to:{width:h,height:m,x:c,y:d},duration:w,animationEasing:v,isActive:S},function(A){var I=A.width,D=A.height,R=A.x,$=A.y;return wt.createElement(Tv,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:w,isActive:N,easing:v},wt.createElement("path",khe({},ai(r,!0),{className:T,d:J9e(R,$,I,D,x),ref:n})))}):wt.createElement("path",khe({},ai(r,!0),{className:T,d:J9e(c,d,h,m,x)}))},Z_s=["points","className","baseLinePoints","connectNulls"];function KE(){return KE=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Q_s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function e$e(s){return sws(s)||tws(s)||ews(s)||J_s()}function J_s(){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 ews(s,t){if(s){if(typeof s=="string")return ONe(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ONe(s,t)}}function tws(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function sws(s){if(Array.isArray(s))return ONe(s)}function ONe(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){t$e(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),t$e(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},AO=function(t,r){var n=rws(t);r&&(n=[n.reduce(function(i,l){return[].concat(e$e(i),e$e(l))},[])]);var a=n.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 n.length===1?"".concat(a,"Z"):a},nws=function(t,r,n){var a=AO(t,n);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(AO(r.reverse(),n).slice(1))},aws=function(t){var r=t.points,n=t.className,a=t.baseLinePoints,i=t.connectNulls,l=X_s(t,Z_s);if(!r||!r.length)return null;var o=Fi("recharts-polygon",n);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=nws(r,a,i);return wt.createElement("g",{className:o},wt.createElement("path",KE({},ai(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?wt.createElement("path",KE({},ai(l,!0),{fill:"none",d:AO(r,i)})):null,c?wt.createElement("path",KE({},ai(l,!0),{fill:"none",d:AO(a,i)})):null)}var h=AO(r,i);return wt.createElement("path",KE({},ai(l,!0),{fill:h.slice(-1)==="Z"?l.fill:"none",className:o,d:h}))};function FNe(){return FNe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function hws(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var mws=function(t,r,n,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(r,"h").concat(n)},fws=function(t){var r=t.x,n=r===void 0?0:r,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,h=t.width,m=h===void 0?0:h,x=t.height,y=x===void 0?0:x,v=t.className,w=uws(t,iws),b=ows({x:n,y:i,top:o,left:d,width:m,height:y},w);return!Sn(n)||!Sn(i)||!Sn(m)||!Sn(y)||!Sn(o)||!Sn(d)?null:wt.createElement("path",BNe({},ai(b,!0),{className:Fi("recharts-cross",v),d:mws(n,i,m,y,o,d)}))},pws=Qpe,xws=gdt,gws=Bv;function yws(s,t){return s&&s.length?pws(s,gws(t),xws):void 0}var vws=yws;const bws=Ao(vws);var _ws=Qpe,wws=Bv,jws=ydt;function Nws(s,t){return s&&s.length?_ws(s,wws(t),jws):void 0}var kws=Nws;const Sws=Ao(kws);var Cws=["cx","cy","angle","ticks","axisLine"],Tws=["ticks","tick","angle","tickFormatter","stroke"];function QM(s){"@babel/helpers - typeof";return QM=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},QM(s)}function MO(){return MO=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Ews(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Aws(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function a$e(s,t){for(var r=0;rl$e?l=a==="outer"?"start":"end":i<-l$e?l=a==="outer"?"end":"start":l="middle",l}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,i=n.cy,l=n.radius,o=n.axisLine,c=n.axisLineType,d=kN(kN({},ai(this.props,!1)),{},{fill:"none"},ai(o,!1));if(c==="circle")return wt.createElement(rxe,ZC({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var h=this.props.ticks,m=h.map(function(x){return hc(a,i,l,x.coordinate)});return wt.createElement(aws,ZC({className:"recharts-polar-angle-axis-line"},d,{points:m}))}},{key:"renderTicks",value:function(){var n=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,h=ai(this.props,!1),m=ai(l,!1),x=kN(kN({},h),{},{fill:"none"},ai(o,!1)),y=i.map(function(v,w){var b=n.getTickLineCoord(v),N=n.getTickTextAnchor(v),S=kN(kN(kN({textAnchor:N},h),{},{stroke:"none",fill:d},m),{},{index:w,payload:v,x:b.x2,y:b.y2});return wt.createElement(Jo,ZC({className:Fi("recharts-polar-angle-axis-tick",Gdt(l)),key:"tick-".concat(v.coordinate)},q3(n.props,v,w)),o&&wt.createElement("line",ZC({className:"recharts-polar-angle-axis-tick-line"},x,b)),l&&t.renderTickItem(l,S,c?c(v.value,w):v.value))});return wt.createElement(Jo,{className:"recharts-polar-angle-axis-ticks"},y)}},{key:"render",value:function(){var n=this.props,a=n.ticks,i=n.radius,l=n.axisLine;return i<=0||!a||!a.length?null:wt.createElement(Jo,{className:Fi("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,a,i){var l;return wt.isValidElement(n)?l=wt.cloneElement(n,a):ki(n)?l=n(a):l=wt.createElement(V3,ZC({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(k.PureComponent);ixe(oxe,"displayName","PolarAngleAxis");ixe(oxe,"axisType","angleAxis");ixe(oxe,"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 Hws=mct,Gws=Hws(Object.getPrototypeOf,Object),Wws=Gws,Kws=Gb,Yws=Wws,Zws=Wb,Xws="[object Object]",Qws=Function.prototype,Jws=Object.prototype,uut=Qws.toString,ejs=Jws.hasOwnProperty,tjs=uut.call(Object);function sjs(s){if(!Zws(s)||Kws(s)!=Xws)return!1;var t=Yws(s);if(t===null)return!0;var r=ejs.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&uut.call(r)==tjs}var rjs=sjs;const njs=Ao(rjs);var ajs=Gb,ijs=Wb,ojs="[object Boolean]";function ljs(s){return s===!0||s===!1||ijs(s)&&ajs(s)==ojs}var cjs=ljs;const djs=Ao(cjs);function dF(s){"@babel/helpers - typeof";return dF=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},dF(s)}function The(){return The=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);r0,from:{upperWidth:0,lowerWidth:0,height:x,x:c,y:d},to:{upperWidth:h,lowerWidth:m,height:x,x:c,y:d},duration:w,animationEasing:v,isActive:N},function(T){var A=T.upperWidth,I=T.lowerWidth,D=T.height,R=T.x,$=T.y;return wt.createElement(Tv,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:b,duration:w,easing:v},wt.createElement("path",The({},ai(r,!0),{className:S,d:h$e(R,$,A,I,D),ref:n})))}):wt.createElement("g",null,wt.createElement("path",The({},ai(r,!0),{className:S,d:h$e(c,d,h,m,x)})))},_js=["option","shapeType","propTransformer","activeClassName","isActive"];function uF(s){"@babel/helpers - typeof";return uF=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},uF(s)}function wjs(s,t){if(s==null)return{};var r=jjs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function jjs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function m$e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function Ehe(s){for(var t=1;t0?Zp(T,"paddingAngle",0):0;if(I){var R=Dp(I.endAngle-I.startAngle,T.endAngle-T.startAngle),$=ic(ic({},T),{},{startAngle:S+D,endAngle:S+R(w)+D});b.push($),S=$.endAngle}else{var F=T.endAngle,z=T.startAngle,Q=Dp(0,F-z),K=Q(w),X=ic(ic({},T),{},{startAngle:S+D,endAngle:S+K+D});b.push(X),S=X.endAngle}}),wt.createElement(Jo,null,n.renderSectorsStatically(b))})}},{key:"attachKeyboardHandlers",value:function(n){var a=this;n.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 n=this.props,a=n.sectors,i=n.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!PB(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,h=a.cy,m=a.innerRadius,x=a.outerRadius,y=a.isAnimationActive,v=this.state.isAnimationFinished;if(i||!l||!l.length||!Sn(d)||!Sn(h)||!Sn(m)||!Sn(x))return null;var w=Fi("recharts-pie",o);return wt.createElement(Jo,{tabIndex:this.props.rootTabIndex,className:w,ref:function(N){n.pieRef=N}},this.renderSectors(),c&&this.renderLabels(l),xh.renderCallByParent(this.props,null,!1),(!y||v)&&jb.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return a.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:n.sectors!==a.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,a){return n>a?"start":n=360?S:S-1)*c,A=b-S*y-T,I=a.reduce(function($,F){var z=$u(F,N,0);return $+(Sn(z)?z:0)},0),D;if(I>0){var R;D=a.map(function($,F){var z=$u($,N,0),Q=$u($,h,F),K=(Sn(z)?z:0)/I,X;F?X=R.endAngle+uf(w)*c*(z!==0?1:0):X=l;var Z=X+uf(w)*((z!==0?y:0)+K*A),re=(X+Z)/2,le=(v.innerRadius+v.outerRadius)/2,oe=[{name:Q,value:z,payload:$,dataKey:N,type:x}],ne=hc(v.cx,v.cy,le,re);return R=ic(ic(ic({percent:K,cornerRadius:i,name:Q,tooltipPayload:oe,midAngle:re,middleRadius:le,tooltipPosition:ne},$),v),{},{value:$u($,N),startAngle:X,endAngle:Z,payload:$,paddingAngle:uf(w)*c}),R})}return ic(ic({},v),{},{sectors:D,data:a})});var Vjs=Math.ceil,Hjs=Math.max;function Gjs(s,t,r,n){for(var a=-1,i=Hjs(Vjs((t-s)/(r||1)),0),l=Array(i);i--;)l[n?i:++a]=s,s+=r;return l}var Wjs=Gjs,Kjs=Ict,g$e=1/0,Yjs=17976931348623157e292;function Zjs(s){if(!s)return s===0?s:0;if(s=Kjs(s),s===g$e||s===-g$e){var t=s<0?-1:1;return t*Yjs}return s===s?s:0}var put=Zjs,Xjs=Wjs,Qjs=Hpe,rbe=put;function Jjs(s){return function(t,r,n){return n&&typeof n!="number"&&Qjs(t,r,n)&&(r=n=void 0),t=rbe(t),r===void 0?(r=t,t=0):r=rbe(r),n=n===void 0?t0&&n.handleDrag(a.changedTouches[0])}),Cp(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=n.props,i=a.endIndex,l=a.onDragEnd,o=a.startIndex;l==null||l({endIndex:i,startIndex:o})}),n.detachDragEndListener()}),Cp(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Cp(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Cp(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Cp(n,"handleSlideDragStart",function(a){var i=w$e(a)?a.changedTouches[0]:a;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return m2s(t,s),c2s(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var a=n.startX,i=n.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,h=d.length-1,m=Math.min(a,i),x=Math.max(a,i),y=t.getIndexInRange(l,m),v=t.getIndexInRange(l,x);return{startIndex:y-y%c,endIndex:v===h?h:v-v%c}}},{key:"getTextOfTick",value:function(n){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=$u(i[n],o,n);return ki(l)?l(c,n):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(n){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,h=c.width,m=c.travellerWidth,x=c.startIndex,y=c.endIndex,v=c.onChange,w=n.pageX-i;w>0?w=Math.min(w,d+h-m-o,d+h-m-l):w<0&&(w=Math.max(w,d-l,d-o));var b=this.getIndex({startX:l+w,endX:o+w});(b.startIndex!==x||b.endIndex!==y)&&v&&v(b),this.setState({startX:l+w,endX:o+w,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,a){var i=w$e(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],h=this.props,m=h.x,x=h.width,y=h.travellerWidth,v=h.onChange,w=h.gap,b=h.data,N={startX:this.state.startX,endX:this.state.endX},S=n.pageX-i;S>0?S=Math.min(S,m+x-y-d):S<0&&(S=Math.max(S,m-d)),N[l]=d+S;var T=this.getIndex(N),A=T.startIndex,I=T.endIndex,D=function(){var $=b.length-1;return l==="startX"&&(o>c?A%w===0:I%w===0)||oc?I%w===0:A%w===0)||o>c&&I===$};this.setState(Cp(Cp({},l,d+S),"brushMoveStartX",n.pageX),function(){v&&D()&&v(T)})}},{key:"handleTravellerMoveKeyboard",value:function(n,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,h=this.state[a],m=o.indexOf(h);if(m!==-1){var x=m+n;if(!(x===-1||x>=o.length)){var y=o[x];a==="startX"&&y>=d||a==="endX"&&y<=c||this.setState(Cp({},a,y),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.fill,d=n.stroke;return wt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var n=this.props,a=n.x,i=n.y,l=n.width,o=n.height,c=n.data,d=n.children,h=n.padding,m=k.Children.only(d);return m?wt.cloneElement(m,{x:a,y:i,width:l,height:o,margin:h,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,a){var i,l,o=this,c=this.props,d=c.y,h=c.travellerWidth,m=c.height,x=c.traveller,y=c.ariaLabel,v=c.data,w=c.startIndex,b=c.endIndex,N=Math.max(n,this.props.x),S=nbe(nbe({},ai(this.props,!1)),{},{x:N,y:d,width:h,height:m}),T=y||"Min value: ".concat((i=v[w])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=v[b])===null||l===void 0?void 0:l.name);return wt.createElement(Jo,{tabIndex:0,role:"slider","aria-label":T,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(I){["ArrowLeft","ArrowRight"].includes(I.key)&&(I.preventDefault(),I.stopPropagation(),o.handleTravellerMoveKeyboard(I.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(x,S))}},{key:"renderSlide",value:function(n,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,h=Math.min(n,a)+d,m=Math.max(Math.abs(a-n)-d,0);return wt.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:h,y:l,width:m,height:o})}},{key:"renderText",value:function(){var n=this.props,a=n.startIndex,i=n.endIndex,l=n.y,o=n.height,c=n.travellerWidth,d=n.stroke,h=this.state,m=h.startX,x=h.endX,y=5,v={pointerEvents:"none",fill:d};return wt.createElement(Jo,{className:"recharts-brush-texts"},wt.createElement(V3,Ihe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(m,x)-y,y:l+o/2},v),this.getTextOfTick(a)),wt.createElement(V3,Ihe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(m,x)+c+y,y:l+o/2},v),this.getTextOfTick(i)))}},{key:"render",value:function(){var n=this.props,a=n.data,i=n.className,l=n.children,o=n.x,c=n.y,d=n.width,h=n.height,m=n.alwaysShowText,x=this.state,y=x.startX,v=x.endX,w=x.isTextActive,b=x.isSlideMoving,N=x.isTravellerMoving,S=x.isTravellerFocused;if(!a||!a.length||!Sn(o)||!Sn(c)||!Sn(d)||!Sn(h)||d<=0||h<=0)return null;var T=Fi("recharts-brush",i),A=wt.Children.count(l)===1,I=o2s("userSelect","none");return wt.createElement(Jo,{className:T,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:I},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(y,v),this.renderTravellerLayer(y,"startX"),this.renderTravellerLayer(v,"endX"),(w||b||N||S||m)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var a=n.x,i=n.y,l=n.width,o=n.height,c=n.stroke,d=Math.floor(i+o/2)-1;return wt.createElement(wt.Fragment,null,wt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),wt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),wt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,a){var i;return wt.isValidElement(n)?i=wt.cloneElement(n,a):ki(n)?i=n(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(n,a){var i=n.data,l=n.width,o=n.x,c=n.travellerWidth,d=n.updateId,h=n.startIndex,m=n.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return nbe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?p2s({data:i,width:l,x:o,travellerWidth:c,startIndex:h,endIndex:m}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var x=a.scale.domain().map(function(y){return a.scale(y)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(n.startIndex),endX:a.scale(n.endIndex),scaleValues:x}}return null}},{key:"getIndexInRange",value:function(n,a){for(var i=n.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);n[c]>a?o=c:l=c}return a>=n[o]?o:l}}])}(k.PureComponent);Cp(sI,"displayName","Brush");Cp(sI,"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 x2s=q5e;function g2s(s,t){var r;return x2s(s,function(n,a,i){return r=t(n,a,i),!r}),!!r}var y2s=g2s,v2s=act,b2s=Bv,_2s=y2s,w2s=ip,j2s=Hpe;function N2s(s,t,r){var n=w2s(s)?v2s:_2s;return r&&j2s(s,t,r)&&(t=void 0),n(s,b2s(t))}var k2s=N2s;const S2s=Ao(k2s);var gv=function(t,r){var n=t.alwaysShow,a=t.ifOverflow;return n&&(a="extendDomain"),a===r},j$e=Cct;function C2s(s,t,r){t=="__proto__"&&j$e?j$e(s,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):s[t]=r}var T2s=C2s,E2s=T2s,A2s=kct,M2s=Bv;function I2s(s,t){var r={};return t=M2s(t),A2s(s,function(n,a,i){E2s(r,a,t(n,a,i))}),r}var L2s=I2s;const P2s=Ao(L2s);function D2s(s,t){for(var r=-1,n=s==null?0:s.length;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Q2s(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function J2s(s,t){var r=s.x,n=s.y,a=X2s(s,W2s),i="".concat(r),l=parseInt(i,10),o="".concat(n),c=parseInt(o,10),d="".concat(t.height||a.height),h=parseInt(d,10),m="".concat(t.width||a.width),x=parseInt(m,10);return fD(fD(fD(fD(fD({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:h,width:x,name:t.name,radius:t.radius})}function k$e(s){return wt.createElement(hut,VNe({shapeType:"rectangle",propTransformer:J2s,activeClassName:"recharts-active-bar"},s))}var eNs=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,a){if(typeof t=="number")return t;var i=Sn(n)||Das(n);return i?t(n,a):(i||G3(),r)}},tNs=["value","background"],but;function rI(s){"@babel/helpers - typeof";return rI=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},rI(s)}function sNs(s,t){if(s==null)return{};var r=rNs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function rNs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Phe(){return Phe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(re)0&&Math.abs(Z)0&&(X=Math.min((Ue||0)-(Z[Be-1]||0),X))}),Number.isFinite(X)){var re=X/K,le=w.layout==="vertical"?n.height:n.width;if(w.padding==="gap"&&(R=re*le/2),w.padding==="no-gap"){var oe=hf(t.barCategoryGap,re*le),ne=re*le/2;R=ne-oe-(ne-oe)/le*oe}}}a==="xAxis"?$=[n.left+(T.left||0)+(R||0),n.left+n.width-(T.right||0)-(R||0)]:a==="yAxis"?$=c==="horizontal"?[n.top+n.height-(T.bottom||0),n.top+(T.top||0)]:[n.top+(T.top||0)+(R||0),n.top+n.height-(T.bottom||0)-(R||0)]:$=w.range,I&&($=[$[1],$[0]]);var ie=Bdt(w,i,x),ye=ie.scale,ce=ie.realScaleType;ye.domain(N).range($),zdt(ye);var ve=$dt(ye,uy(uy({},w),{},{realScaleType:ce}));a==="xAxis"?(Q=b==="top"&&!A||b==="bottom"&&A,F=n.left,z=m[D]-Q*w.height):a==="yAxis"&&(Q=b==="left"&&!A||b==="right"&&A,F=m[D]-Q*w.width,z=n.top);var be=uy(uy(uy({},w),ve),{},{realScaleType:ce,x:F,y:z,scale:ye,width:a==="xAxis"?n.width:w.width,height:a==="yAxis"?n.height:w.height});return be.bandSize=yhe(be,ve),!w.hide&&a==="xAxis"?m[D]+=(Q?-1:1)*be.height:w.hide||(m[D]+=(Q?-1:1)*be.width),uy(uy({},y),{},dxe({},v,be))},{})},kut=function(t,r){var n=t.x,a=t.y,i=r.x,l=r.y;return{x:Math.min(n,i),y:Math.min(a,l),width:Math.abs(i-n),height:Math.abs(l-a)}},fNs=function(t){var r=t.x1,n=t.y1,a=t.x2,i=t.y2;return kut({x:r,y:n},{x:a,y:i})},Sut=function(){function s(t){uNs(this,s),this.scale=t}return hNs(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(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=n.bandAware,i=n.position;if(r!==void 0){if(i)switch(i){case"start":return this.scale(r);case"middle":{var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+l}case"end":{var o=this.bandwidth?this.bandwidth():0;return this.scale(r)+o}default:return this.scale(r)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),a=n[0],i=n[n.length-1];return a<=i?r>=a&&r<=i:r>=i&&r<=a}}],[{key:"create",value:function(r){return new s(r)}}])}();dxe(Sut,"EPS",1e-4);var yTe=function(t){var r=Object.keys(t).reduce(function(n,a){return uy(uy({},n),{},dxe({},a,Sut.create(t[a])))},{});return uy(uy({},r),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return P2s(a,function(c,d){return r[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return vut(a,function(i,l){return r[l].isInRange(i)})}})};function pNs(s){return(s%180+180)%180}var xNs=function(t){var r=t.width,n=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=pNs(a),l=i*Math.PI/180,o=Math.atan(n/r),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var _Ns=bNs,wNs=put;function jNs(s){var t=wNs(s),r=t%1;return t===t?r?t-r:t:0}var NNs=jNs,kNs=vct,SNs=Bv,CNs=NNs,TNs=Math.max;function ENs(s,t,r){var n=s==null?0:s.length;if(!n)return-1;var a=r==null?0:CNs(r);return a<0&&(a=TNs(n+a,0)),kNs(s,SNs(t),a)}var ANs=ENs,MNs=_Ns,INs=ANs,LNs=MNs(INs),PNs=LNs;const DNs=Ao(PNs);var RNs=Bns(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("")}),vTe=k.createContext(void 0),bTe=k.createContext(void 0),Cut=k.createContext(void 0),Tut=k.createContext({}),Eut=k.createContext(void 0),Aut=k.createContext(0),Mut=k.createContext(0),A$e=function(t){var r=t.state,n=r.xAxisMap,a=r.yAxisMap,i=r.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,h=RNs(i);return wt.createElement(vTe.Provider,{value:n},wt.createElement(bTe.Provider,{value:a},wt.createElement(Tut.Provider,{value:i},wt.createElement(Cut.Provider,{value:h},wt.createElement(Eut.Provider,{value:l},wt.createElement(Aut.Provider,{value:d},wt.createElement(Mut.Provider,{value:c},o)))))))},ONs=function(){return k.useContext(Eut)},Iut=function(t){var r=k.useContext(vTe);r==null&&G3();var n=r[t];return n==null&&G3(),n},FNs=function(){var t=k.useContext(vTe);return vw(t)},BNs=function(){var t=k.useContext(bTe),r=DNs(t,function(n){return vut(n.domain,Number.isFinite)});return r||vw(t)},Lut=function(t){var r=k.useContext(bTe);r==null&&G3();var n=r[t];return n==null&&G3(),n},zNs=function(){var t=k.useContext(Cut);return t},$Ns=function(){return k.useContext(Tut)},_Te=function(){return k.useContext(Mut)},wTe=function(){return k.useContext(Aut)};function nI(s){"@babel/helpers - typeof";return nI=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},nI(s)}function UNs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function qNs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);rs*a)return!1;var i=r();return s*(t-s*i/2-n)>=0&&s*(t+s*i/2-a)<=0}function Nks(s,t){return zut(s,t+1)}function kks(s,t,r,n,a){for(var i=(n||[]).slice(),l=t.start,o=t.end,c=0,d=1,h=l,m=function(){var v=n==null?void 0:n[c];if(v===void 0)return{v:zut(n,d)};var w=c,b,N=function(){return b===void 0&&(b=r(v,w)),b},S=v.coordinate,T=c===0||Bhe(s,S,N,h,o);T||(c=0,h=l,d+=1),T&&(h=S+s*(N()/2+a),c+=d)},x;d<=i.length;)if(x=m(),x)return x.v;return[]}function xF(s){"@babel/helpers - typeof";return xF=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},xF(s)}function F$e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function pm(s){for(var t=1;t0?y.coordinate-b*s:y.coordinate})}else i[x]=y=pm(pm({},y),{},{tickCoord:y.coordinate});var N=Bhe(s,y.tickCoord,w,o,c);N&&(c=y.tickCoord-s*(w()/2+a),i[x]=pm(pm({},y),{},{isShow:!0}))},h=l-1;h>=0;h--)d(h);return i}function Aks(s,t,r,n,a,i){var l=(n||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var h=n[o-1],m=r(h,o-1),x=s*(h.coordinate+s*m/2-d);l[o-1]=h=pm(pm({},h),{},{tickCoord:x>0?h.coordinate-x*s:h.coordinate});var y=Bhe(s,h.tickCoord,function(){return m},c,d);y&&(d=h.tickCoord-s*(m/2+a),l[o-1]=pm(pm({},h),{},{isShow:!0}))}for(var v=i?o-1:o,w=function(S){var T=l[S],A,I=function(){return A===void 0&&(A=r(T,S)),A};if(S===0){var D=s*(T.coordinate-s*I()/2-c);l[S]=T=pm(pm({},T),{},{tickCoord:D<0?T.coordinate-D*s:T.coordinate})}else l[S]=T=pm(pm({},T),{},{tickCoord:T.coordinate});var R=Bhe(s,T.tickCoord,I,c,d);R&&(c=T.tickCoord+s*(I()/2+a),l[S]=pm(pm({},T),{},{isShow:!0}))},b=0;b=2?uf(a[1].coordinate-a[0].coordinate):1,N=jks(i,b,y);return c==="equidistantPreserveStart"?kks(b,N,w,a,l):(c==="preserveStart"||c==="preserveStartEnd"?x=Aks(b,N,w,a,l,c==="preserveStartEnd"):x=Eks(b,N,w,a,l),x.filter(function(S){return S.isShow}))}var Mks=["viewBox"],Iks=["viewBox"],Lks=["ticks"];function oI(s){"@babel/helpers - typeof";return oI=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},oI(s)}function ZE(){return ZE=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Pks(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Dks(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function z$e(s,t){for(var r=0;r0?c(this.props):c(y)),l<=0||o<=0||!v||!v.length?null:wt.createElement(Jo,{className:Fi("recharts-cartesian-axis",d),ref:function(b){n.layerReference=b}},i&&this.renderAxisLine(),this.renderTicks(v,this.state.fontSize,this.state.letterSpacing),xh.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,a,i){var l,o=Fi(a.className,"recharts-cartesian-axis-tick-value");return wt.isValidElement(n)?l=wt.cloneElement(n,Au(Au({},a),{},{className:o})):ki(n)?l=n(Au(Au({},a),{},{className:o})):l=wt.createElement(V3,ZE({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(k.Component);STe(pL,"displayName","CartesianAxis");STe(pL,"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 Uks=["x1","y1","x2","y2","key"],qks=["offset"];function W3(s){"@babel/helpers - typeof";return W3=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},W3(s)}function $$e(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function ym(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Wks(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}var Kks=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return wt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function qut(s,t){var r;if(wt.isValidElement(s))r=wt.cloneElement(s,t);else if(ki(s))r=s(t);else{var n=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=U$e(t,Uks),d=ai(c,!1);d.offset;var h=U$e(d,qks);r=wt.createElement("line",h4({},h,{x1:n,y1:a,x2:i,y2:l,fill:"none",key:o}))}return r}function Yks(s){var t=s.x,r=s.width,n=s.horizontal,a=n===void 0?!0:n,i=s.horizontalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=ym(ym({},s),{},{x1:t,y1:o,x2:t+r,y2:o,key:"line-".concat(c),index:c});return qut(a,d)});return wt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function Zks(s){var t=s.y,r=s.height,n=s.vertical,a=n===void 0?!0:n,i=s.verticalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=ym(ym({},s),{},{x1:o,y1:t,x2:o,y2:t+r,key:"line-".concat(c),index:c});return qut(a,d)});return wt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function Xks(s){var t=s.horizontalFill,r=s.fillOpacity,n=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 h=o.map(function(x){return Math.round(x+a-a)}).sort(function(x,y){return x-y});a!==h[0]&&h.unshift(0);var m=h.map(function(x,y){var v=!h[y+1],w=v?a+l-x:h[y+1]-x;if(w<=0)return null;var b=y%t.length;return wt.createElement("rect",{key:"react-".concat(y),y:x,x:n,height:w,width:i,stroke:"none",fill:t[b],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return wt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},m)}function Qks(s){var t=s.vertical,r=t===void 0?!0:t,n=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!r||!n||!n.length)return null;var h=d.map(function(x){return Math.round(x+i-i)}).sort(function(x,y){return x-y});i!==h[0]&&h.unshift(0);var m=h.map(function(x,y){var v=!h[y+1],w=v?i+o-x:h[y+1]-x;if(w<=0)return null;var b=y%n.length;return wt.createElement("rect",{key:"react-".concat(y),x,y:l,width:w,height:c,stroke:"none",fill:n[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return wt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},m)}var Jks=function(t,r){var n=t.xAxis,a=t.width,i=t.height,l=t.offset;return Fdt(kTe(ym(ym(ym({},pL.defaultProps),n),{},{ticks:cb(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,r)},eSs=function(t,r){var n=t.yAxis,a=t.width,i=t.height,l=t.offset;return Fdt(kTe(ym(ym(ym({},pL.defaultProps),n),{},{ticks:cb(n,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,r)},aE={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function Vut(s){var t,r,n,a,i,l,o=_Te(),c=wTe(),d=$Ns(),h=ym(ym({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:aE.stroke,fill:(r=s.fill)!==null&&r!==void 0?r:aE.fill,horizontal:(n=s.horizontal)!==null&&n!==void 0?n:aE.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:aE.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:aE.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:aE.verticalFill,x:Sn(s.x)?s.x:d.left,y:Sn(s.y)?s.y:d.top,width:Sn(s.width)?s.width:d.width,height:Sn(s.height)?s.height:d.height}),m=h.x,x=h.y,y=h.width,v=h.height,w=h.syncWithTicks,b=h.horizontalValues,N=h.verticalValues,S=FNs(),T=BNs();if(!Sn(y)||y<=0||!Sn(v)||v<=0||!Sn(m)||m!==+m||!Sn(x)||x!==+x)return null;var A=h.verticalCoordinatesGenerator||Jks,I=h.horizontalCoordinatesGenerator||eSs,D=h.horizontalPoints,R=h.verticalPoints;if((!D||!D.length)&&ki(I)){var $=b&&b.length,F=I({yAxis:T?ym(ym({},T),{},{ticks:$?b:T.ticks}):void 0,width:o,height:c,offset:d},$?!0:w);Iy(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(W3(F),"]")),Array.isArray(F)&&(D=F)}if((!R||!R.length)&&ki(A)){var z=N&&N.length,Q=A({xAxis:S?ym(ym({},S),{},{ticks:z?N:S.ticks}):void 0,width:o,height:c,offset:d},z?!0:w);Iy(Array.isArray(Q),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(W3(Q),"]")),Array.isArray(Q)&&(R=Q)}return wt.createElement("g",{className:"recharts-cartesian-grid"},wt.createElement(Kks,{fill:h.fill,fillOpacity:h.fillOpacity,x:h.x,y:h.y,width:h.width,height:h.height,ry:h.ry}),wt.createElement(Yks,h4({},h,{offset:d,horizontalPoints:D,xAxis:S,yAxis:T})),wt.createElement(Zks,h4({},h,{offset:d,verticalPoints:R,xAxis:S,yAxis:T})),wt.createElement(Xks,h4({},h,{horizontalPoints:D})),wt.createElement(Qks,h4({},h,{verticalPoints:R})))}Vut.displayName="CartesianGrid";var tSs=["type","layout","connectNulls","ref"],sSs=["key"];function lI(s){"@babel/helpers - typeof";return lI=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},lI(s)}function q$e(s,t){if(s==null)return{};var r=rSs(s,t),n,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function rSs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function IO(){return IO=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var r=0,n=new Array(t);rm){y=[].concat(iE(c.slice(0,v)),[m-w]);break}var b=y.length%2===0?[0,x]:[x];return[].concat(iE(t.repeat(c,h)),iE(y),b).map(function(N){return"".concat(N,"px")}).join(", ")}),hy(r,"id",oL("recharts-line-")),hy(r,"pathRef",function(l){r.mainCurve=l}),hy(r,"handleAnimationEnd",function(){r.setState({isAnimationFinished:!0}),r.props.onAnimationEnd&&r.props.onAnimationEnd()}),hy(r,"handleAnimationStart",function(){r.setState({isAnimationFinished:!1}),r.props.onAnimationStart&&r.props.onAnimationStart()}),r}return mSs(t,s),cSs(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();this.setState({totalLength:n})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var n=this.getTotalLength();n!==this.state.totalLength&&this.setState({totalLength:n})}}},{key:"getTotalLength",value:function(){var n=this.mainCurve;try{return n&&n.getTotalLength&&n.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(n,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,h=i.children,m=Xp(h,DB);if(!m)return null;var x=function(w,b){return{x:w.x,y:w.y,value:w.value,errorVal:$u(w.payload,b)}},y={clipPath:n?"url(#clipPath-".concat(a,")"):null};return wt.createElement(Jo,y,m.map(function(v){return wt.cloneElement(v,{key:"bar-".concat(v.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:x})}))}},{key:"renderDots",value:function(n,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,h=o.dataKey,m=ai(this.props,!1),x=ai(c,!0),y=d.map(function(w,b){var N=Np(Np(Np({key:"dot-".concat(b),r:3},m),x),{},{index:b,cx:w.x,cy:w.y,value:w.value,dataKey:h,payload:w.payload,points:d});return t.renderDotItem(c,N)}),v={clipPath:n?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return wt.createElement(Jo,IO({className:"recharts-line-dots",key:"dots"},v),y)}},{key:"renderCurveStatically",value:function(n,a,i,l){var o=this.props,c=o.type,d=o.layout,h=o.connectNulls;o.ref;var m=q$e(o,tSs),x=Np(Np(Np({},ai(m,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:n},l),{},{type:c,layout:d,connectNulls:h});return wt.createElement(_he,IO({},x,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(n,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,h=l.animationBegin,m=l.animationDuration,x=l.animationEasing,y=l.animationId,v=l.animateNewValues,w=l.width,b=l.height,N=this.state,S=N.prevPoints,T=N.totalLength;return wt.createElement(Tv,{begin:h,duration:m,isActive:d,easing:x,from:{t:0},to:{t:1},key:"line-".concat(y),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var I=A.t;if(S){var D=S.length/o.length,R=o.map(function(K,X){var Z=Math.floor(X*D);if(S[Z]){var re=S[Z],le=Dp(re.x,K.x),oe=Dp(re.y,K.y);return Np(Np({},K),{},{x:le(I),y:oe(I)})}if(v){var ne=Dp(w*2,K.x),ie=Dp(b/2,K.y);return Np(Np({},K),{},{x:ne(I),y:ie(I)})}return Np(Np({},K),{},{x:K.x,y:K.y})});return i.renderCurveStatically(R,n,a)}var $=Dp(0,T),F=$(I),z;if(c){var Q="".concat(c).split(/[,\s]+/gim).map(function(K){return parseFloat(K)});z=i.getStrokeDasharray(F,T,Q)}else z=i.generateSimpleStrokeDasharray(T,F);return i.renderCurveStatically(o,n,a,{strokeDasharray:z})})}},{key:"renderCurve",value:function(n,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,h=c.totalLength;return o&&l&&l.length&&(!d&&h>0||!PB(d,l))?this.renderCurveWithAnimation(n,a):this.renderCurveStatically(l,n,a)}},{key:"render",value:function(){var n,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,h=a.yAxis,m=a.top,x=a.left,y=a.width,v=a.height,w=a.isAnimationActive,b=a.id;if(i||!o||!o.length)return null;var N=this.state.isAnimationFinished,S=o.length===1,T=Fi("recharts-line",c),A=d&&d.allowDataOverflow,I=h&&h.allowDataOverflow,D=A||I,R=Pi(b)?this.id:b,$=(n=ai(l,!1))!==null&&n!==void 0?n:{r:3,strokeWidth:2},F=$.r,z=F===void 0?3:F,Q=$.strokeWidth,K=Q===void 0?2:Q,X=Was(l)?l:{},Z=X.clipDot,re=Z===void 0?!0:Z,le=z*2+K;return wt.createElement(Jo,{className:T},A||I?wt.createElement("defs",null,wt.createElement("clipPath",{id:"clipPath-".concat(R)},wt.createElement("rect",{x:A?x:x-y/2,y:I?m:m-v/2,width:A?y:y*2,height:I?v:v*2})),!re&&wt.createElement("clipPath",{id:"clipPath-dots-".concat(R)},wt.createElement("rect",{x:x-le/2,y:m-le/2,width:y+le,height:v+le}))):null,!S&&this.renderCurve(D,R),this.renderErrorBar(D,R),(S||l)&&this.renderDots(D,re,R),(!w||N)&&jb.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curPoints:n.points,prevPoints:a.curPoints}:n.points!==a.curPoints?{curPoints:n.points}:null}},{key:"repeat",value:function(n,a){for(var i=n.length%2!==0?[].concat(iE(n),[0]):n,l=[],o=0;os.length)&&(t=s.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function sCs(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function rCs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function nCs(s,t){for(var r=0;rs.length)&&(t=s.length);for(var r=0,n=new Array(t);r0?l:t&&t.length&&Sn(a)&&Sn(i)?t.slice(a,i+1):[]};function iht(s){return s==="number"?[0,"auto"]:void 0}var cke=function(t,r,n,a){var i=t.graphicalItems,l=t.tooltipAxis,o=pxe(r,t);return n<0||!i||!i.length||n>=o.length?null:i.reduce(function(c,d){var h,m=(h=d.props.data)!==null&&h!==void 0?h:r;m&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(m=m.slice(t.dataStartIndex,t.dataEndIndex+1));var x;if(l.dataKey&&!l.allowDuplicatedCategory){var y=m===void 0?o:m;x=Vue(y,l.dataKey,a)}else x=m&&m[n]||o[n];return x?[].concat(hI(c),[qdt(d,x)]):c},[])},X$e=function(t,r,n,a){var i=a||{x:t.chartX,y:t.chartY},l=xCs(i,n),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,h=Kvs(l,o,d,c);if(h>=0&&d){var m=d[h]&&d[h].value,x=cke(t,r,h,m),y=gCs(n,o,h,i);return{activeTooltipIndex:h,activeLabel:m,activePayload:x,activeCoordinate:y}}return null},yCs=function(t,r){var n=r.axes,a=r.graphicalItems,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.layout,m=t.children,x=t.stackOffset,y=Odt(h,i);return n.reduce(function(v,w){var b,N=w.type.defaultProps!==void 0?Ir(Ir({},w.type.defaultProps),w.props):w.props,S=N.type,T=N.dataKey,A=N.allowDataOverflow,I=N.allowDuplicatedCategory,D=N.scale,R=N.ticks,$=N.includeHidden,F=N[l];if(v[F])return v;var z=pxe(t.data,{graphicalItems:a.filter(function(ve){var be,Ue=l in ve.props?ve.props[l]:(be=ve.type.defaultProps)===null||be===void 0?void 0:be[l];return Ue===F}),dataStartIndex:c,dataEndIndex:d}),Q=z.length,K,X,Z;VSs(N.domain,A,S)&&(K=jNe(N.domain,null,A),y&&(S==="number"||D!=="auto")&&(Z=TO(z,T,"category")));var re=iht(S);if(!K||K.length===0){var le,oe=(le=N.domain)!==null&&le!==void 0?le:re;if(T){if(K=TO(z,T,S),S==="category"&&y){var ne=Oas(K);I&&ne?(X=K,K=Mhe(0,Q)):I||(K=v9e(oe,K,w).reduce(function(ve,be){return ve.indexOf(be)>=0?ve:[].concat(hI(ve),[be])},[]))}else if(S==="category")I?K=K.filter(function(ve){return ve!==""&&!Pi(ve)}):K=v9e(oe,K,w).reduce(function(ve,be){return ve.indexOf(be)>=0||be===""||Pi(be)?ve:[].concat(hI(ve),[be])},[]);else if(S==="number"){var ie=Jvs(z,a.filter(function(ve){var be,Ue,Be=l in ve.props?ve.props[l]:(be=ve.type.defaultProps)===null||be===void 0?void 0:be[l],De="hide"in ve.props?ve.props.hide:(Ue=ve.type.defaultProps)===null||Ue===void 0?void 0:Ue.hide;return Be===F&&($||!De)}),T,i,h);ie&&(K=ie)}y&&(S==="number"||D!=="auto")&&(Z=TO(z,T,"category"))}else y?K=Mhe(0,Q):o&&o[F]&&o[F].hasStack&&S==="number"?K=x==="expand"?[0,1]:Udt(o[F].stackGroups,c,d):K=Rdt(z,a.filter(function(ve){var be=l in ve.props?ve.props[l]:ve.type.defaultProps[l],Ue="hide"in ve.props?ve.props.hide:ve.type.defaultProps.hide;return be===F&&($||!Ue)}),S,h,!0);if(S==="number")K=ike(m,K,F,i,R),oe&&(K=jNe(oe,K,A));else if(S==="category"&&oe){var ye=oe,ce=K.every(function(ve){return ye.indexOf(ve)>=0});ce&&(K=ye)}}return Ir(Ir({},v),{},mi({},F,Ir(Ir({},N),{},{axisType:i,domain:K,categoricalDomain:Z,duplicateDomain:X,originalDomain:(b=N.domain)!==null&&b!==void 0?b:re,isCategorical:y,layout:h})))},{})},vCs=function(t,r){var n=r.graphicalItems,a=r.Axis,i=r.axisType,l=r.axisIdKey,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.layout,m=t.children,x=pxe(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:d}),y=x.length,v=Odt(h,i),w=-1;return n.reduce(function(b,N){var S=N.type.defaultProps!==void 0?Ir(Ir({},N.type.defaultProps),N.props):N.props,T=S[l],A=iht("number");if(!b[T]){w++;var I;return v?I=Mhe(0,y):o&&o[T]&&o[T].hasStack?(I=Udt(o[T].stackGroups,c,d),I=ike(m,I,T,i)):(I=jNe(A,Rdt(x,n.filter(function(D){var R,$,F=l in D.props?D.props[l]:(R=D.type.defaultProps)===null||R===void 0?void 0:R[l],z="hide"in D.props?D.props.hide:($=D.type.defaultProps)===null||$===void 0?void 0:$.hide;return F===T&&!z}),"number",h),a.defaultProps.allowDataOverflow),I=ike(m,I,T,i)),Ir(Ir({},b),{},mi({},T,Ir(Ir({axisType:i},a.defaultProps),{},{hide:!0,orientation:Zp(fCs,"".concat(i,".").concat(w%2),null),domain:I,originalDomain:A,isCategorical:v,layout:h})))}return b},{})},bCs=function(t,r){var n=r.axisType,a=n===void 0?"xAxis":n,i=r.AxisComp,l=r.graphicalItems,o=r.stackGroups,c=r.dataStartIndex,d=r.dataEndIndex,h=t.children,m="".concat(a,"Id"),x=Xp(h,i),y={};return x&&x.length?y=yCs(t,{axes:x,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(y=vCs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:m,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),y},_Cs=function(t){var r=vw(t),n=cb(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:V5e(n,function(a){return a.coordinate}),tooltipAxis:r,tooltipAxisBandSize:yhe(r,n)}},Q$e=function(t){var r=t.children,n=t.defaultShowTooltip,a=Mp(r,sI),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:!!n}},wCs=function(t){return!t||!t.length?!1:t.some(function(r){var n=_b(r&&r.type);return n&&n.indexOf("Bar")>=0})},J$e=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"}},jCs=function(t,r){var n=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=n.width,h=n.height,m=n.children,x=n.margin||{},y=Mp(m,sI),v=Mp(m,VA),w=Object.keys(c).reduce(function(I,D){var R=c[D],$=R.orientation;return!R.mirror&&!R.hide?Ir(Ir({},I),{},mi({},$,I[$]+R.width)):I},{left:x.left||0,right:x.right||0}),b=Object.keys(l).reduce(function(I,D){var R=l[D],$=R.orientation;return!R.mirror&&!R.hide?Ir(Ir({},I),{},mi({},$,Zp(I,"".concat($))+R.height)):I},{top:x.top||0,bottom:x.bottom||0}),N=Ir(Ir({},b),w),S=N.bottom;y&&(N.bottom+=y.props.height||sI.defaultProps.height),v&&r&&(N=Xvs(N,a,n,r));var T=d-N.left-N.right,A=h-N.top-N.bottom;return Ir(Ir({brushBottom:S},N),{},{width:Math.max(T,0),height:Math.max(A,0)})},NCs=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},CTe=function(t){var r=t.chartName,n=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,h=t.formatAxisMap,m=t.defaultProps,x=function(N,S){var T=S.graphicalItems,A=S.stackGroups,I=S.offset,D=S.updateId,R=S.dataStartIndex,$=S.dataEndIndex,F=N.barSize,z=N.layout,Q=N.barGap,K=N.barCategoryGap,X=N.maxBarSize,Z=J$e(z),re=Z.numericAxisName,le=Z.cateAxisName,oe=wCs(T),ne=[];return T.forEach(function(ie,ye){var ce=pxe(N.data,{graphicalItems:[ie],dataStartIndex:R,dataEndIndex:$}),ve=ie.type.defaultProps!==void 0?Ir(Ir({},ie.type.defaultProps),ie.props):ie.props,be=ve.dataKey,Ue=ve.maxBarSize,Be=ve["".concat(re,"Id")],De=ve["".concat(le,"Id")],Ae={},He=c.reduce(function(tt,Ke){var Ze=S["".concat(Ke.axisType,"Map")],lt=ve["".concat(Ke.axisType,"Id")];Ze&&Ze[lt]||Ke.axisType==="zAxis"||G3();var xt=Ze[lt];return Ir(Ir({},tt),{},mi(mi({},Ke.axisType,xt),"".concat(Ke.axisType,"Ticks"),cb(xt)))},Ae),Le=He[le],Ie=He["".concat(le,"Ticks")],Te=A&&A[Be]&&A[Be].hasStack&&l1s(ie,A[Be].stackGroups),xe=_b(ie.type).indexOf("Bar")>=0,et=yhe(Le,Ie),fe=[],it=oe&&Yvs({barSize:F,stackGroups:A,totalSize:NCs(He,le)});if(xe){var Oe,Ye,We=Pi(Ue)?X:Ue,_e=(Oe=(Ye=yhe(Le,Ie,!0))!==null&&Ye!==void 0?Ye:We)!==null&&Oe!==void 0?Oe:0;fe=Zvs({barGap:Q,barCategoryGap:K,bandSize:_e!==et?_e:et,sizeList:it[De],maxBarSize:We}),_e!==et&&(fe=fe.map(function(tt){return Ir(Ir({},tt),{},{position:Ir(Ir({},tt.position),{},{offset:tt.position.offset-_e/2})})}))}var Re=ie&&ie.type&&ie.type.getComposedData;Re&&ne.push({props:Ir(Ir({},Re(Ir(Ir({},He),{},{displayedData:ce,props:N,dataKey:be,item:ie,bandSize:et,barPosition:fe,offset:I,stackedData:Te,layout:z,dataStartIndex:R,dataEndIndex:$}))),{},mi(mi(mi({key:ie.key||"item-".concat(ye)},re,He[re]),le,He[le]),"animationId",D)),childIndex:Zas(ie,N.children),item:ie})}),ne},y=function(N,S){var T=N.props,A=N.dataStartIndex,I=N.dataEndIndex,D=N.updateId;if(!hze({props:T}))return null;var R=T.children,$=T.layout,F=T.stackOffset,z=T.data,Q=T.reverseStackOrder,K=J$e($),X=K.numericAxisName,Z=K.cateAxisName,re=Xp(R,n),le=i1s(z,re,"".concat(X,"Id"),"".concat(Z,"Id"),F,Q),oe=c.reduce(function(ve,be){var Ue="".concat(be.axisType,"Map");return Ir(Ir({},ve),{},mi({},Ue,bCs(T,Ir(Ir({},be),{},{graphicalItems:re,stackGroups:be.axisType===X&&le,dataStartIndex:A,dataEndIndex:I}))))},{}),ne=jCs(Ir(Ir({},oe),{},{props:T,graphicalItems:re}),S==null?void 0:S.legendBBox);Object.keys(oe).forEach(function(ve){oe[ve]=h(T,oe[ve],ne,ve.replace("Map",""),r)});var ie=oe["".concat(Z,"Map")],ye=_Cs(ie),ce=x(T,Ir(Ir({},oe),{},{dataStartIndex:A,dataEndIndex:I,updateId:D,graphicalItems:re,stackGroups:le,offset:ne}));return Ir(Ir({formattedGraphicalItems:ce,graphicalItems:re,offset:ne,stackGroups:le},ye),oe)},v=function(b){function N(S){var T,A,I;return rCs(this,N),I=iCs(this,N,[S]),mi(I,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),mi(I,"accessibilityManager",new qSs),mi(I,"handleLegendBBoxUpdate",function(D){if(D){var R=I.state,$=R.dataStartIndex,F=R.dataEndIndex,z=R.updateId;I.setState(Ir({legendBBox:D},y({props:I.props,dataStartIndex:$,dataEndIndex:F,updateId:z},Ir(Ir({},I.state),{},{legendBBox:D}))))}}),mi(I,"handleReceiveSyncEvent",function(D,R,$){if(I.props.syncId===D){if($===I.eventEmitterSymbol&&typeof I.props.syncMethod!="function")return;I.applySyncEvent(R)}}),mi(I,"handleBrushChange",function(D){var R=D.startIndex,$=D.endIndex;if(R!==I.state.dataStartIndex||$!==I.state.dataEndIndex){var F=I.state.updateId;I.setState(function(){return Ir({dataStartIndex:R,dataEndIndex:$},y({props:I.props,dataStartIndex:R,dataEndIndex:$,updateId:F},I.state))}),I.triggerSyncEvent({dataStartIndex:R,dataEndIndex:$})}}),mi(I,"handleMouseEnter",function(D){var R=I.getMouseInfo(D);if(R){var $=Ir(Ir({},R),{},{isTooltipActive:!0});I.setState($),I.triggerSyncEvent($);var F=I.props.onMouseEnter;ki(F)&&F($,D)}}),mi(I,"triggeredAfterMouseMove",function(D){var R=I.getMouseInfo(D),$=R?Ir(Ir({},R),{},{isTooltipActive:!0}):{isTooltipActive:!1};I.setState($),I.triggerSyncEvent($);var F=I.props.onMouseMove;ki(F)&&F($,D)}),mi(I,"handleItemMouseEnter",function(D){I.setState(function(){return{isTooltipActive:!0,activeItem:D,activePayload:D.tooltipPayload,activeCoordinate:D.tooltipPosition||{x:D.cx,y:D.cy}}})}),mi(I,"handleItemMouseLeave",function(){I.setState(function(){return{isTooltipActive:!1}})}),mi(I,"handleMouseMove",function(D){D.persist(),I.throttleTriggeredAfterMouseMove(D)}),mi(I,"handleMouseLeave",function(D){I.throttleTriggeredAfterMouseMove.cancel();var R={isTooltipActive:!1};I.setState(R),I.triggerSyncEvent(R);var $=I.props.onMouseLeave;ki($)&&$(R,D)}),mi(I,"handleOuterEvent",function(D){var R=Yas(D),$=Zp(I.props,"".concat(R));if(R&&ki($)){var F,z;/.*touch.*/i.test(R)?z=I.getMouseInfo(D.changedTouches[0]):z=I.getMouseInfo(D),$((F=z)!==null&&F!==void 0?F:{},D)}}),mi(I,"handleClick",function(D){var R=I.getMouseInfo(D);if(R){var $=Ir(Ir({},R),{},{isTooltipActive:!0});I.setState($),I.triggerSyncEvent($);var F=I.props.onClick;ki(F)&&F($,D)}}),mi(I,"handleMouseDown",function(D){var R=I.props.onMouseDown;if(ki(R)){var $=I.getMouseInfo(D);R($,D)}}),mi(I,"handleMouseUp",function(D){var R=I.props.onMouseUp;if(ki(R)){var $=I.getMouseInfo(D);R($,D)}}),mi(I,"handleTouchMove",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&I.throttleTriggeredAfterMouseMove(D.changedTouches[0])}),mi(I,"handleTouchStart",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&I.handleMouseDown(D.changedTouches[0])}),mi(I,"handleTouchEnd",function(D){D.changedTouches!=null&&D.changedTouches.length>0&&I.handleMouseUp(D.changedTouches[0])}),mi(I,"handleDoubleClick",function(D){var R=I.props.onDoubleClick;if(ki(R)){var $=I.getMouseInfo(D);R($,D)}}),mi(I,"handleContextMenu",function(D){var R=I.props.onContextMenu;if(ki(R)){var $=I.getMouseInfo(D);R($,D)}}),mi(I,"triggerSyncEvent",function(D){I.props.syncId!==void 0&&ibe.emit(obe,I.props.syncId,D,I.eventEmitterSymbol)}),mi(I,"applySyncEvent",function(D){var R=I.props,$=R.layout,F=R.syncMethod,z=I.state.updateId,Q=D.dataStartIndex,K=D.dataEndIndex;if(D.dataStartIndex!==void 0||D.dataEndIndex!==void 0)I.setState(Ir({dataStartIndex:Q,dataEndIndex:K},y({props:I.props,dataStartIndex:Q,dataEndIndex:K,updateId:z},I.state)));else if(D.activeTooltipIndex!==void 0){var X=D.chartX,Z=D.chartY,re=D.activeTooltipIndex,le=I.state,oe=le.offset,ne=le.tooltipTicks;if(!oe)return;if(typeof F=="function")re=F(ne,D);else if(F==="value"){re=-1;for(var ie=0;ie=0){var Te,xe;if(X.dataKey&&!X.allowDuplicatedCategory){var et=typeof X.dataKey=="function"?Ie:"payload.".concat(X.dataKey.toString());Te=Vue(ie,et,re),xe=ye&&ce&&Vue(ce,et,re)}else Te=ie==null?void 0:ie[Z],xe=ye&&ce&&ce[Z];if(De||Be){var fe=D.props.activeIndex!==void 0?D.props.activeIndex:Z;return[k.cloneElement(D,Ir(Ir(Ir({},F.props),He),{},{activeIndex:fe})),null,null]}if(!Pi(Te))return[Le].concat(hI(I.renderActivePoints({item:F,activePoint:Te,basePoint:xe,childIndex:Z,isRange:ye})))}else{var it,Oe=(it=I.getItemByXY(I.state.activeCoordinate))!==null&&it!==void 0?it:{graphicalItem:Le},Ye=Oe.graphicalItem,We=Ye.item,_e=We===void 0?D:We,Re=Ye.childIndex,tt=Ir(Ir(Ir({},F.props),He),{},{activeIndex:Re});return[k.cloneElement(_e,tt),null,null]}return ye?[Le,null,null]:[Le,null]}),mi(I,"renderCustomized",function(D,R,$){return k.cloneElement(D,Ir(Ir({key:"recharts-customized-".concat($)},I.props),I.state))}),mi(I,"renderMap",{CartesianGrid:{handler:I$,once:!0},ReferenceArea:{handler:I.renderReferenceElement},ReferenceLine:{handler:I$},ReferenceDot:{handler:I.renderReferenceElement},XAxis:{handler:I$},YAxis:{handler:I$},Brush:{handler:I.renderBrush,once:!0},Bar:{handler:I.renderGraphicChild},Line:{handler:I.renderGraphicChild},Area:{handler:I.renderGraphicChild},Radar:{handler:I.renderGraphicChild},RadialBar:{handler:I.renderGraphicChild},Scatter:{handler:I.renderGraphicChild},Pie:{handler:I.renderGraphicChild},Funnel:{handler:I.renderGraphicChild},Tooltip:{handler:I.renderCursor,once:!0},PolarGrid:{handler:I.renderPolarGrid,once:!0},PolarAngleAxis:{handler:I.renderPolarAxis},PolarRadiusAxis:{handler:I.renderPolarAxis},Customized:{handler:I.renderCustomized}}),I.clipPathId="".concat((T=S.id)!==null&&T!==void 0?T:oL("recharts"),"-clip"),I.throttleTriggeredAfterMouseMove=Lct(I.triggeredAfterMouseMove,(A=S.throttleDelay)!==null&&A!==void 0?A:1e3/60),I.state={},I}return cCs(N,b),aCs(N,[{key:"componentDidMount",value:function(){var T,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T: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 T=this.props,A=T.children,I=T.data,D=T.height,R=T.layout,$=Mp(A,Bf);if($){var F=$.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,Q=cke(this.state,I,F,z),K=this.state.tooltipTicks[F].coordinate,X=(this.state.offset.top+D)/2,Z=R==="horizontal",re=Z?{x:K,y:X}:{y:K,x:X},le=this.state.formattedGraphicalItems.find(function(ne){var ie=ne.item;return ie.type.name==="Scatter"});le&&(re=Ir(Ir({},re),le.props.points[F].tooltipPosition),Q=le.props.points[F].tooltipPayload);var oe={activeTooltipIndex:F,isTooltipActive:!0,activeLabel:z,activePayload:Q,activeCoordinate:re};this.setState(oe),this.renderCursor($),this.accessibilityManager.setIndex(F)}}}},{key:"getSnapshotBeforeUpdate",value:function(T,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==T.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==T.margin){var I,D;this.accessibilityManager.setDetails({offset:{left:(I=this.props.margin.left)!==null&&I!==void 0?I:0,top:(D=this.props.margin.top)!==null&&D!==void 0?D:0}})}return null}},{key:"componentDidUpdate",value:function(T){F2e([Mp(T.children,Bf)],[Mp(this.props.children,Bf)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var T=Mp(this.props.children,Bf);if(T&&typeof T.props.shared=="boolean"){var A=T.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(T){if(!this.container)return null;var A=this.container,I=A.getBoundingClientRect(),D=wxs(I),R={chartX:Math.round(T.pageX-D.left),chartY:Math.round(T.pageY-D.top)},$=I.width/A.offsetWidth||1,F=this.inRange(R.chartX,R.chartY,$);if(!F)return null;var z=this.state,Q=z.xAxisMap,K=z.yAxisMap,X=this.getTooltipEventType(),Z=X$e(this.state,this.props.data,this.props.layout,F);if(X!=="axis"&&Q&&K){var re=vw(Q).scale,le=vw(K).scale,oe=re&&re.invert?re.invert(R.chartX):null,ne=le&&le.invert?le.invert(R.chartY):null;return Ir(Ir({},R),{},{xValue:oe,yValue:ne},Z)}return Z?Ir(Ir({},R),Z):null}},{key:"inRange",value:function(T,A){var I=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,D=this.props.layout,R=T/I,$=A/I;if(D==="horizontal"||D==="vertical"){var F=this.state.offset,z=R>=F.left&&R<=F.left+F.width&&$>=F.top&&$<=F.top+F.height;return z?{x:R,y:$}:null}var Q=this.state,K=Q.angleAxisMap,X=Q.radiusAxisMap;if(K&&X){var Z=vw(K);return w9e({x:R,y:$},Z)}return null}},{key:"parseEventsOfWrapper",value:function(){var T=this.props.children,A=this.getTooltipEventType(),I=Mp(T,Bf),D={};I&&A==="axis"&&(I.props.trigger==="click"?D={onClick:this.handleClick}:D={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 R=Hue(this.props,this.handleOuterEvent);return Ir(Ir({},R),D)}},{key:"addListener",value:function(){ibe.on(obe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){ibe.removeListener(obe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(T,A,I){for(var D=this.state.formattedGraphicalItems,R=0,$=D.length;R<$;R++){var F=D[R];if(F.item===T||F.props.key===T.key||A===_b(F.item.type)&&I===F.childIndex)return F}return null}},{key:"renderClipPath",value:function(){var T=this.clipPathId,A=this.state.offset,I=A.left,D=A.top,R=A.height,$=A.width;return wt.createElement("defs",null,wt.createElement("clipPath",{id:T},wt.createElement("rect",{x:I,y:D,height:R,width:$})))}},{key:"getXScales",value:function(){var T=this.state.xAxisMap;return T?Object.entries(T).reduce(function(A,I){var D=K$e(I,2),R=D[0],$=D[1];return Ir(Ir({},A),{},mi({},R,$.scale))},{}):null}},{key:"getYScales",value:function(){var T=this.state.yAxisMap;return T?Object.entries(T).reduce(function(A,I){var D=K$e(I,2),R=D[0],$=D[1];return Ir(Ir({},A),{},mi({},R,$.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(T){var A;return(A=this.state.xAxisMap)===null||A===void 0||(A=A[T])===null||A===void 0?void 0:A.scale}},{key:"getYScaleByAxisId",value:function(T){var A;return(A=this.state.yAxisMap)===null||A===void 0||(A=A[T])===null||A===void 0?void 0:A.scale}},{key:"getItemByXY",value:function(T){var A=this.state,I=A.formattedGraphicalItems,D=A.activeItem;if(I&&I.length)for(var R=0,$=I.length;R<$;R++){var F=I[R],z=F.props,Q=F.item,K=Q.type.defaultProps!==void 0?Ir(Ir({},Q.type.defaultProps),Q.props):Q.props,X=_b(Q.type);if(X==="Bar"){var Z=(z.data||[]).find(function(ne){return K_s(T,ne)});if(Z)return{graphicalItem:F,payload:Z}}else if(X==="RadialBar"){var re=(z.data||[]).find(function(ne){return w9e(T,ne)});if(re)return{graphicalItem:F,payload:re}}else if(lxe(F,D)||cxe(F,D)||hF(F,D)){var le=Rjs({graphicalItem:F,activeTooltipItem:D,itemData:K.data}),oe=K.activeIndex===void 0?le:K.activeIndex;return{graphicalItem:Ir(Ir({},F),{},{childIndex:oe}),payload:hF(F,D)?K.data[le]:F.props.data[le]}}}return null}},{key:"render",value:function(){var T=this;if(!hze(this))return null;var A=this.props,I=A.children,D=A.className,R=A.width,$=A.height,F=A.style,z=A.compact,Q=A.title,K=A.desc,X=Y$e(A,QSs),Z=ai(X,!1);if(z)return wt.createElement(A$e,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},wt.createElement(z2e,XE({},Z,{width:R,height:$,title:Q,desc:K}),this.renderClipPath(),fze(I,this.renderMap)));if(this.props.accessibilityLayer){var re,le;Z.tabIndex=(re=this.props.tabIndex)!==null&&re!==void 0?re:0,Z.role=(le=this.props.role)!==null&&le!==void 0?le:"application",Z.onKeyDown=function(ne){T.accessibilityManager.keyboardEvent(ne)},Z.onFocus=function(){T.accessibilityManager.focus()}}var oe=this.parseEventsOfWrapper();return wt.createElement(A$e,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},wt.createElement("div",XE({className:Fi("recharts-wrapper",D),style:Ir({position:"relative",cursor:"default",width:R,height:$},F)},oe,{ref:function(ie){T.container=ie}}),wt.createElement(z2e,XE({},Z,{width:R,height:$,title:Q,desc:K,style:pCs}),this.renderClipPath(),fze(I,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(k.Component);mi(v,"displayName",r),mi(v,"defaultProps",Ir({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},m)),mi(v,"getDerivedStateFromProps",function(b,N){var S=b.dataKey,T=b.data,A=b.children,I=b.width,D=b.height,R=b.layout,$=b.stackOffset,F=b.margin,z=N.dataStartIndex,Q=N.dataEndIndex;if(N.updateId===void 0){var K=Q$e(b);return Ir(Ir(Ir({},K),{},{updateId:0},y(Ir(Ir({props:b},K),{},{updateId:0}),N)),{},{prevDataKey:S,prevData:T,prevWidth:I,prevHeight:D,prevLayout:R,prevStackOffset:$,prevMargin:F,prevChildren:A})}if(S!==N.prevDataKey||T!==N.prevData||I!==N.prevWidth||D!==N.prevHeight||R!==N.prevLayout||$!==N.prevStackOffset||!qA(F,N.prevMargin)){var X=Q$e(b),Z={chartX:N.chartX,chartY:N.chartY,isTooltipActive:N.isTooltipActive},re=Ir(Ir({},X$e(N,T,R)),{},{updateId:N.updateId+1}),le=Ir(Ir(Ir({},X),Z),re);return Ir(Ir(Ir({},le),y(Ir({props:b},le),N)),{},{prevDataKey:S,prevData:T,prevWidth:I,prevHeight:D,prevLayout:R,prevStackOffset:$,prevMargin:F,prevChildren:A})}if(!F2e(A,N.prevChildren)){var oe,ne,ie,ye,ce=Mp(A,sI),ve=ce&&(oe=(ne=ce.props)===null||ne===void 0?void 0:ne.startIndex)!==null&&oe!==void 0?oe:z,be=ce&&(ie=(ye=ce.props)===null||ye===void 0?void 0:ye.endIndex)!==null&&ie!==void 0?ie:Q,Ue=ve!==z||be!==Q,Be=!Pi(T),De=Be&&!Ue?N.updateId:N.updateId+1;return Ir(Ir({updateId:De},y(Ir(Ir({props:b},N),{},{updateId:De,dataStartIndex:ve,dataEndIndex:be}),N)),{},{prevChildren:A,dataStartIndex:ve,dataEndIndex:be})}return null}),mi(v,"renderActiveDot",function(b,N,S){var T;return k.isValidElement(b)?T=k.cloneElement(b,N):ki(b)?T=b(N):T=wt.createElement(rxe,N),wt.createElement(Jo,{className:"recharts-active-dot",key:S},T)});var w=k.forwardRef(function(N,S){return wt.createElement(v,XE({},N,{ref:S}))});return w.displayName=v.displayName,w},kCs=CTe({chartName:"LineChart",GraphicalChild:RB,axisComponents:[{axisType:"xAxis",AxisComp:K3},{axisType:"yAxis",AxisComp:Y3}],formatAxisMap:Nut}),oht=CTe({chartName:"BarChart",GraphicalChild:Rb,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:K3},{axisType:"yAxis",AxisComp:Y3}],formatAxisMap:Nut}),lht=CTe({chartName:"PieChart",GraphicalChild:zv,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:oxe},{axisType:"radiusAxis",AxisComp:axe}],formatAxisMap:y1s,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}});const eUe=["hsl(220, 70%, 50%)","hsl(142, 71%, 45%)","hsl(270, 70%, 50%)","hsl(30, 90%, 55%)","hsl(350, 70%, 55%)","hsl(180, 60%, 45%)"];function SCs(){const s=br(),{data:t,isLoading:r}=mt({queryKey:["email-campaign-analytics"],queryFn:async()=>{const{data:S,error:T}=await V.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(T)throw T;return S}}),{data:n}=mt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:S,error:T}=await V.from("profiles").select("id, name, email");if(T)throw T;return S}});if(r)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((n||[]).map(S=>[S.id,S])),l=a.reduce((S,T)=>S+(T.sent_count||0),0),o=a.reduce((S,T)=>S+(T.open_count||0),0),c=a.reduce((S,T)=>S+(T.click_count||0),0),d=a.reduce((S,T)=>S+(T.bounce_count||0),0),h=a.reduce((S,T)=>S+(T.complaint_count||0),0),m=l>0?(o/l*100).toFixed(1):"0.0",x=l>0?(c/l*100).toFixed(1):"0.0",y=[{label:"Campaigns Sent",value:a.length,icon:en,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:pr,color:"text-green-600"},{label:"Avg Open Rate",value:`${m}%`,icon:bn,color:"text-blue-600"},{label:"Avg Click Rate",value:`${x}%`,icon:Bu,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:id,color:"text-orange-600"},{label:"Complaints",value:h,icon:bo,color:"text-destructive"}],v=new Map;a.forEach(S=>{var I,D;const T=S.user_id,A=v.get(T)||{name:((I=i.get(T))==null?void 0:I.name)||((D=i.get(T))==null?void 0:D.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=S.sent_count||0,A.opens+=S.open_count||0,A.clicks+=S.click_count||0,v.set(T,A)});const w=[...v.entries()].map(([S,T])=>({id:S,...T,openRate:T.sent>0?+(T.opens/T.sent*100).toFixed(1):0})).sort((S,T)=>T.sent-S.sent),b=w.slice(0,6).map(S=>({name:S.name,value:S.sent})),N=a.map(S=>{var T;return{name:S.name.length>20?S.name.slice(0,20)+"…":S.name,agent:((T=i.get(S.user_id))==null?void 0:T.name)||"Unknown",openRate:S.sent_count>0?+(S.open_count/S.sent_count*100).toFixed(1):0,clickRate:S.sent_count>0?+(S.click_count/S.sent_count*100).toFixed(1):0,sent:S.sent_count,date:S.sent_at?_s(new Date(S.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(en,{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:y.map(S=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 text-center",children:[e.jsx(S.icon,{className:`h-5 w-5 mx-auto mb-1 ${S.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:S.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S.label})]})},S.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Pe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(HA,{width:"100%",height:"100%",children:e.jsxs(oht,{data:N,children:[e.jsx(K3,{dataKey:"date",fontSize:11}),e.jsx(Y3,{fontSize:11,unit:"%"}),e.jsx(Bf,{formatter:S=>`${S}%`}),e.jsx(Rb,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(Rb,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Pe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(HA,{width:"100%",height:"100%",children:e.jsxs(lht,{children:[e.jsx(zv,{data:b,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:S,percent:T})=>`${S} (${(T*100).toFixed(0)}%)`,fontSize:11,children:b.map((S,T)=>e.jsx(EB,{fill:eUe[T%eUe.length]},T))}),e.jsx(Bf,{})]})})})})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Pe,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(HA,{width:"100%",height:"100%",children:e.jsxs(kCs,{data:N,children:[e.jsx(K3,{dataKey:"date",fontSize:11}),e.jsx(Y3,{fontSize:11}),e.jsx(Bf,{}),e.jsx(RB,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Agent Performance"})}),e.jsx(Pe,{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:w.map(S=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:S.name}),e.jsx("td",{className:"py-2.5 text-center",children:S.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:S.sent}),e.jsx("td",{className:"py-2.5 text-center",children:S.opens}),e.jsx("td",{className:"py-2.5 text-center",children:S.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Ge,{variant:"outline",children:[S.openRate,"%"]})})]},S.id))})]})})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((S,T)=>{const A=S.sent_count>0?S.open_count/S.sent_count:0;return(T.sent_count>0?T.open_count/T.sent_count:0)-A}).slice(0,10).map((S,T)=>{const A=S.sent_count>0?(S.open_count/S.sent_count*100).toFixed(1):"0.0",I=S.sent_count>0?(S.click_count/S.sent_count*100).toFixed(1):"0.0",D=i.get(S.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/${S.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",T+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:S.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(D==null?void 0:D.name)||"Unknown"," · ",S.sent_at?_s(new Date(S.sent_at),"MMM d, yyyy"):""," · ",S.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(bn,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Bu,{className:"h-3 w-3"})," ",I,"%"]})]})]},S.id)})})})]})]})})}const CCs=()=>{const{toast:s}=Ma(),[t,r]=k.useState(!0),[n,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});k.useEffect(()=>{d()},[]);const d=async()=>{try{r(!0);const h=new Date;h.setDate(h.getDate()-30);const m=h.toISOString(),{data:x}=await V.from("website_apps").select("slug, name").order("sort_order"),y=[];let v=0;for(;;){const{data:I,error:D}=await V.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(v,v+999);if(D)throw D;if(y.push(...I||[]),!I||I.length<1e3)break;v+=1e3}const w=[];for(v=0;;){const{data:I,error:D}=await V.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",m).order("created_at",{ascending:!1}).range(v,v+999);if(D)throw D;if(w.push(...I||[]),!I||I.length<1e3||(v+=1e3,v>2e4))break}const b=new Map;for(const I of x||[])b.set(I.slug,{app_slug:I.slug,app_name:I.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const I of y){const D=b.get(I.app_slug);D&&(D.installs+=1,I.enabled&&(D.enabled+=1))}for(const I of w){const D=b.get(I.app_slug);D&&(I.event_type==="impression"?D.impressions+=1:I.event_type==="expand"?D.expands+=1:I.event_type==="cta_click"?D.cta_clicks+=1:I.event_type==="lead_capture"&&(D.lead_captures+=1))}const N=new Map;for(const I of y){if(!I.enabled)continue;const D=N.get(I.user_id)||{user_id:I.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};D.apps_enabled.includes(I.app_slug)||D.apps_enabled.push(I.app_slug),N.set(I.user_id,D)}for(const I of w){const D=N.get(I.user_id);D&&(D.events_30d+=1,I.event_type==="lead_capture"&&(D.leads_30d+=1))}const S=Array.from(N.keys());if(S.length>0){const{data:I}=await V.from("profiles").select("id, name, email").in("id",S);for(const D of I||[]){const R=N.get(D.id);R&&(R.name=D.name,R.email=D.email)}}const T=Array.from(b.values()),A=Array.from(N.values()).sort((I,D)=>D.events_30d-I.events_30d);a(T),l(A),c({installs:T.reduce((I,D)=>I+D.enabled,0),activeAgents:A.length,impressions30d:T.reduce((I,D)=>I+D.impressions,0),leads30d:T.reduce((I,D)=>I+D.lead_captures,0)})}catch(h){console.error(h),s({title:"Error",description:h.message||"Failed to load website app analytics",variant:"destructive"})}finally{r(!1)}};return t?e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(fc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(Vs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"App Performance (last 30 days)"})}),e.jsx(Pe,{children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"App"}),e.jsx(Nt,{className:"text-right",children:"Installs"}),e.jsx(Nt,{className:"text-right",children:"Enabled"}),e.jsx(Nt,{className:"text-right",children:"Impressions"}),e.jsx(Nt,{className:"text-right",children:"Expands"}),e.jsx(Nt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Nt,{className:"text-right",children:"Leads"}),e.jsx(Nt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs($n,{children:[n.map(h=>{const m=h.impressions>0?(h.lead_captures/h.impressions*100).toFixed(1):"—";return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:h.app_name}),e.jsx(dt,{className:"text-right",children:h.installs}),e.jsx(dt,{className:"text-right",children:h.enabled}),e.jsx(dt,{className:"text-right",children:h.impressions}),e.jsx(dt,{className:"text-right",children:h.expands}),e.jsx(dt,{className:"text-right",children:h.cta_clicks}),e.jsx(dt,{className:"text-right font-semibold",children:h.lead_captures}),e.jsx(dt,{className:"text-right text-muted-foreground",children:m==="—"?"—":`${m}%`})]},h.app_slug)}),n.length===0&&e.jsx(Ds,{children:e.jsx(dt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Pe,{children:[e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Apps Enabled"}),e.jsx(Nt,{className:"text-right",children:"Events (30d)"}),e.jsx(Nt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs($n,{children:[i.slice(0,100).map(h=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:h.name||"—"}),e.jsx(dt,{className:"text-muted-foreground",children:h.email||"—"}),e.jsx(dt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:h.apps_enabled.map(m=>e.jsx(Ge,{variant:"secondary",className:"text-xs",children:m},m))})}),e.jsx(dt,{className:"text-right",children:h.events_30d}),e.jsx(dt,{className:"text-right font-semibold",children:h.leads_30d})]},h.user_id)),i.length===0&&e.jsx(Ds,{children:e.jsx(dt,{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."]})]})]})]})},TCs=()=>{const[s,t]=k.useState([]),[r,n]=k.useState([]),[a,i]=k.useState({}),[l,o]=k.useState(!0);k.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:m},{data:x}]=await Promise.all([V.rpc("get_extension_usage_summary"),V.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),y=m||[],v=x||[];t(y),n(v);const w=Array.from(new Set(v.map(b=>b.user_id)));if(w.length){const{data:b}=await V.from("profiles").select("id, name, email").in("id",w),N={};(b||[]).forEach(S=>{N[S.id]={name:S.name,email:S.email}}),i(N)}}finally{o(!1)}},d=s.reduce((m,x)=>({users:m.users+1,contacts:m.contacts+Number(x.contacts_saved||0),listings:m.listings+Number(x.listings_imported||0),activities:m.activities+Number(x.activities_logged||0),events:m.events+Number(x.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(ke,{children:e.jsx(Pe,{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 h=m=>{switch(m){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 m}};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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(L4,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(En,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Users by Extension Activity"})}),e.jsx(Pe,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"User"}),e.jsx(Nt,{className:"text-right",children:"Total"}),e.jsx(Nt,{className:"text-right",children:"Contacts"}),e.jsx(Nt,{className:"text-right",children:"Listings"}),e.jsx(Nt,{className:"text-right",children:"Activities"}),e.jsx(Nt,{children:"First Used"}),e.jsx(Nt,{children:"Last Used"})]})}),e.jsx($n,{children:s.map(m=>e.jsxs(Ds,{children:[e.jsxs(dt,{children:[e.jsx("div",{className:"font-medium",children:m.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.email})]}),e.jsx(dt,{className:"text-right font-medium",children:m.total_events}),e.jsx(dt,{className:"text-right",children:m.contacts_saved}),e.jsx(dt,{className:"text-right",children:m.listings_imported}),e.jsx(dt,{className:"text-right",children:m.activities_logged}),e.jsx(dt,{className:"text-xs text-muted-foreground",children:m.first_event_at?_s(new Date(m.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(dt,{className:"text-xs text-muted-foreground",children:m.last_event_at?_s(new Date(m.last_event_at),"MMM d, h:mm a"):"—"})]},m.user_id))})]})})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Recent Activity"})}),e.jsx(Pe,{children:r.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:r.map(m=>{const x=a[m.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(Ge,{variant:"secondary",children:h(m.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(x==null?void 0:x.name)||(x==null?void 0:x.email)||m.user_id.slice(0,8)}),m.metadata&&Object.keys(m.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(m.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_s(new Date(m.created_at),"MMM d, h:mm a")})]},m.id)})})})]})]})},ECs=()=>e.jsx(ws,{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(On,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Rn,{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(ts,{value:"analytics",className:"space-y-4",children:e.jsx(ess,{})}),e.jsx(ts,{value:"website-apps",className:"space-y-4",children:e.jsx(CCs,{})}),e.jsx(ts,{value:"extension",className:"space-y-4",children:e.jsx(TCs,{})}),e.jsx(ts,{value:"content",className:"space-y-4",children:e.jsx(sss,{})}),e.jsx(ts,{value:"email-campaigns",className:"space-y-4",children:e.jsx(SCs,{})}),e.jsx(ts,{value:"activity",className:"space-y-4",children:e.jsx(Jts,{})}),e.jsx(ts,{value:"shares",className:"space-y-4",children:e.jsx(ylt,{})})]})]})});function ACs(){const s=Xt(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=k.useState(null),[d,h]=k.useState(""),[m,x]=k.useState([]),[y,v]=k.useState([]),[w,b]=k.useState([]),[N,S]=k.useState(!1),[T,A]=k.useState(null),[I,D]=k.useState(""),{data:R,isLoading:$}=mt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(et)throw et;return xe}}),{data:F}=mt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(et)throw et;return xe}}),{data:z}=mt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(et)throw et;return xe}}),{data:Q}=mt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(et)throw et;return xe}}),{data:K,isLoading:X}=mt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(et)throw et;return xe}}),Z=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),h(""),x([]),v([]),b([]),a(null),D("")},re=xe=>{a(xe),l({title:xe.title,description:xe.description||"",publish_date:xe.publish_date.split("T")[0],is_published:xe.is_published,category_id:xe.category_id||""}),h(xe.preview_image_url||""),D("");const et=(F==null?void 0:F.filter(Oe=>Oe.resource_id===xe.id))||[];x(et.map(Oe=>({id:Oe.id,name:Oe.name,file_url:Oe.file_url,file_size:Oe.file_size,sort_order:Oe.sort_order})));const fe=(z==null?void 0:z.filter(Oe=>Oe.resource_id===xe.id))||[];v(fe.map(Oe=>({id:Oe.id,title:Oe.title,video_url:Oe.video_url,sort_order:Oe.sort_order})));const it=(Q==null?void 0:Q.filter(Oe=>Oe.resource_id===xe.id))||[];b(it.map(Oe=>({id:Oe.id,title:Oe.title,canva_share_link:Oe.canva_share_link,sort_order:Oe.sort_order}))),r(!0)},le=xe=>{var fe;const et=(fe=xe.target.files)==null?void 0:fe[0];et&&(c(et),h(URL.createObjectURL(et)))},oe=()=>{x([...m,{name:"",file_url:"",sort_order:m.length}])},ne=xe=>{x(m.filter((et,fe)=>fe!==xe))},ie=(xe,et,fe)=>{const it=[...m];if(et==="file"&&fe instanceof File){const Oe=fe.name.replace(/\.[^/.]+$/,"");it[xe]={...it[xe],file:fe,file_size:fe.size,name:it[xe].name||Oe}}else it[xe]={...it[xe],[et]:fe};x(it)},ye=()=>{v([...y,{title:"",video_url:"",sort_order:y.length}])},ce=xe=>{v(y.filter((et,fe)=>fe!==xe))},ve=(xe,et,fe)=>{const it=[...y];et==="file"&&fe instanceof File?it[xe]={...it[xe],file:fe}:it[xe]={...it[xe],[et]:fe},v(it)},be=()=>{b([...w,{title:"",canva_share_link:"",sort_order:w.length}])},Ue=xe=>{b(w.filter((et,fe)=>fe!==xe))},Be=(xe,et,fe)=>{const it=[...w];it[xe]={...it[xe],[et]:fe},b(it)},De=async(xe,et)=>{try{const fe=await V.functions.invoke("bunny-upload",{body:{action:"create",title:xe.name}});if(fe.error)throw fe.error;const{videoId:it,uploadUrl:Oe,libraryId:Ye}=fe.data,We=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:it,libraryId:Ye}});if(We.error)throw We.error;const{uploadUrl:_e,apiKey:Re}=We.data,tt=new XMLHttpRequest;return tt.open("PUT",_e,!0),tt.setRequestHeader("AccessKey",Re),tt.upload.onprogress=Ke=>{if(Ke.lengthComputable){const Ze=Math.round(Ke.loaded/Ke.total*100),lt=[...y];lt[et]={...lt[et],uploadProgress:Ze},v(lt)}},await new Promise((Ke,Ze)=>{tt.onload=()=>tt.status>=200&&tt.status<300?Ke():Ze(new Error("Upload failed")),tt.onerror=()=>Ze(new Error("Upload failed")),tt.send(xe)}),`https://iframe.mediadelivery.net/embed/${Ye}/${it}`}catch(fe){throw console.error("Bunny upload error:",fe),fe}},Ae=Ct({mutationFn:async xe=>{const{data:et,error:fe}=await V.from("brokerage_resource_categories").insert({name:xe,sort_order:(K==null?void 0:K.length)||0}).select().single();if(fe)throw fe;return et},onSuccess:xe=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:xe.id}),D(""),ue.success("Category created")},onError:xe=>{ue.error("Failed to create category: "+xe.message)}}),He=Ct({mutationFn:async()=>{S(!0);let xe=(n==null?void 0:n.preview_image_url)||null;if(o){const it=o.name.split(".").pop(),Oe=`${Date.now()}.${it}`,{error:Ye}=await V.storage.from("brokerage-resources").upload(`previews/${Oe}`,o);if(Ye)throw Ye;const{data:We}=V.storage.from("brokerage-resources").getPublicUrl(`previews/${Oe}`);xe=We.publicUrl}const et={title:i.title,description:i.description||null,preview_image_url:xe,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let fe;if(n){const{error:it}=await V.from("brokerage_resources").update(et).eq("id",n.id);if(it)throw it;fe=n.id;const Oe=(F==null?void 0:F.filter(xt=>xt.resource_id===n.id).map(xt=>xt.id))||[],Ye=m.filter(xt=>xt.id).map(xt=>xt.id),We=Oe.filter(xt=>!Ye.includes(xt));We.length>0&&await V.from("brokerage_resource_pdfs").delete().in("id",We);const _e=(z==null?void 0:z.filter(xt=>xt.resource_id===n.id).map(xt=>xt.id))||[],Re=y.filter(xt=>xt.id).map(xt=>xt.id),tt=_e.filter(xt=>!Re.includes(xt));tt.length>0&&await V.from("brokerage_resource_videos").delete().in("id",tt);const Ke=(Q==null?void 0:Q.filter(xt=>xt.resource_id===n.id).map(xt=>xt.id))||[],Ze=w.filter(xt=>xt.id).map(xt=>xt.id),lt=Ke.filter(xt=>!Ze.includes(xt));lt.length>0&&await V.from("brokerage_resource_links").delete().in("id",lt)}else{const{data:it,error:Oe}=await V.from("brokerage_resources").insert(et).select().single();if(Oe)throw Oe;fe=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"]}),ue.success(n?"Resource updated":"Resource created"),r(!1),Z(),S(!1)},onError:xe=>{ue.error("Failed to save resource: "+xe.message),S(!1)}}),Le=Ct({mutationFn:async xe=>{const{error:et}=await V.from("brokerage_resources").delete().eq("id",xe);if(et)throw et},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ue.success("Resource deleted")},onError:xe=>{ue.error("Failed to delete: "+xe.message)}}),Ie=xe=>{if(xe.preventDefault(),!i.title){ue.error("Please enter a title");return}He.mutate()},Te=xe=>{const et=(F==null?void 0:F.filter(Oe=>Oe.resource_id===xe).length)||0,fe=(z==null?void 0:z.filter(Oe=>Oe.resource_id===xe).length)||0,it=(Q==null?void 0:Q.filter(Oe=>Oe.resource_id===xe).length)||0;return{pdfCount:et,videoCount:fe,linkCount:it}};return e.jsx(ws,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(R==null?void 0:R.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(R==null?void 0:R.filter(xe=>xe.is_published).length)||0})})]})]}),e.jsxs(G,{onClick:()=>{Z(),r(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Category"}),e.jsx(Nt,{children:"Content"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:$?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(R==null?void 0:R.length)===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):R==null?void 0:R.map(xe=>{const{pdfCount:et,videoCount:fe,linkCount:it}=Te(xe.id),Oe=K==null?void 0:K.find(Ye=>Ye.id===xe.category_id);return e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[xe.preview_image_url?e.jsx("img",{src:xe.preview_image_url,alt:xe.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(Gu,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:xe.title}),xe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:xe.description})]})]})}),e.jsx(dt,{children:Oe?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Oe.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(dt,{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(ln,{className:"h-3.5 w-3.5"}),et]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),fe]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(po,{className:"h-3.5 w-3.5"}),it]})]})}),e.jsx(dt,{children:_s(new Date(xe.publish_date),"MMM d, yyyy")}),e.jsx(dt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${xe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:xe.is_published?"Published":"Draft"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{const Ye=(F==null?void 0:F.filter(Re=>Re.resource_id===xe.id))||[],We=(z==null?void 0:z.filter(Re=>Re.resource_id===xe.id))||[],_e=(Q==null?void 0:Q.filter(Re=>Re.resource_id===xe.id))||[];A({...xe,pdfs:Ye,videos:We,links:_e})},children:e.jsx(bn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>re(xe),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Le.mutate(xe.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},xe.id)})})]})})}),e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:n?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Ie,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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(Gu,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:le})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:i.title,onChange:xe=>l({...i,title:xe.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(wh,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{value:i.category_id,onValueChange:xe=>l({...i,category_id:xe}),children:[e.jsx(As,{className:"flex-1",children:e.jsx(Ls,{placeholder:"Select a category"})}),e.jsx(Ms,{children:K==null?void 0:K.map(xe=>e.jsx(ct,{value:xe.id,children:xe.name},xe.id))})]}),i.category_id&&e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(vr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Or create new category...",value:I,onChange:xe=>D(xe.target.value),className:"flex-1"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",disabled:!I.trim()||Ae.isPending,onClick:()=>Ae.mutate(I.trim()),children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:i.description,onChange:xe=>l({...i,description:xe}),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(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:i.publish_date,onChange:xe=>l({...i,publish_date:xe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(_r,{checked:i.is_published,onCheckedChange:xe=>l({...i,is_published:xe})}),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(he,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"PDF Documents (",m.length,")"]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:oe,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),m.map((xe,et)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(Ne,{placeholder:"PDF Name",value:xe.name,onChange:fe=>ie(et,"name",fe.target.value),className:"flex-1"}),e.jsx(Ne,{type:"file",accept:".pdf",onChange:fe=>{var Oe;const it=(Oe=fe.target.files)==null?void 0:Oe[0];it&&ie(et,"file",it)},className:"flex-1"}),xe.file_url&&!xe.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>ne(et),children:e.jsx(vr,{className:"h-4 w-4"})})]},et))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Videos (",y.length,")"]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:ye,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),y.map((xe,et)=>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(Ne,{placeholder:"Video Title",value:xe.title,onChange:fe=>ve(et,"title",fe.target.value),className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>ce(et),children:e.jsx(vr,{className:"h-4 w-4"})})]}),e.jsx(Ne,{type:"file",accept:"video/*",onChange:fe=>{var Oe;const it=(Oe=fe.target.files)==null?void 0:Oe[0];it&&ve(et,"file",it)}}),xe.uploadProgress!==void 0&&xe.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:`${xe.uploadProgress}%`}})}),xe.video_url&&!xe.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},et))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(po,{className:"h-4 w-4"}),"Canva Links (",w.length,")"]}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),w.map((xe,et)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(Ne,{placeholder:"Link Title",value:xe.title,onChange:fe=>Be(et,"title",fe.target.value),className:"flex-1"}),e.jsx(Ne,{placeholder:"Canva Share Link",value:xe.canva_share_link,onChange:fe=>Be(et,"canva_share_link",fe.target.value),className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>Ue(et),children:e.jsx(vr,{className:"h-4 w-4"})})]},et))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:He.isPending||N,children:He.isPending||N?"Saving...":n?"Update":"Create"})]})]})]})}),e.jsx(fs,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:T==null?void 0:T.title})}),T&&e.jsxs("div",{className:"space-y-4",children:[T.preview_image_url&&e.jsx("img",{src:T.preview_image_url,alt:T.title,className:"w-full h-48 object-cover rounded-lg"}),T.description&&e.jsx("p",{className:"text-muted-foreground",children:T.description}),T.pdfs&&T.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"PDF Documents (",T.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:T.pdfs.map(xe=>e.jsx("a",{href:xe.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:xe.name},xe.id))})]}),T.videos&&T.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Videos (",T.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:T.videos.map(xe=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:xe.title})},xe.id))})]}),T.links&&T.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(po,{className:"h-4 w-4"}),"Canva Links (",T.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:T.links.map(xe=>e.jsx("a",{href:xe.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:xe.title},xe.id))})]})]})]})})]})})}const cht=[{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 MCs(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,y]=k.useState(!1),[v,w]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,I]=k.useState(""),[D,R]=k.useState("Learn More"),[$,F]=k.useState("top"),[z,Q]=k.useState(""),[K,X]=k.useState(!0),[Z,re]=k.useState(""),[le,oe]=k.useState("");k.useEffect(()=>{ne()},[]);const ne=async()=>{try{const{data:Ae,error:He}=await V.from("dashboard_banners").select("*").order("placement").order("sort_order");if(He)throw He;t(Ae||[])}catch(Ae){ue.error("Failed to load banners: "+Ae.message)}finally{n(!1)}},ie=()=>{w(""),N(""),T(""),I(""),R("Learn More"),F("top"),Q(""),X(!0),re(""),oe(""),d(null)},ye=Ae=>{d(Ae),w(Ae.title),N(Ae.description||""),T(Ae.image_url),I(Ae.link_url||""),R(Ae.link_text||"Learn More"),F(Ae.placement),Q(Ae.section_after||""),X(Ae.is_active),re(Ae.start_date?_s(new Date(Ae.start_date),"yyyy-MM-dd'T'HH:mm"):""),oe(Ae.end_date?_s(new Date(Ae.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},ce=async Ae=>{var Le;const He=(Le=Ae.target.files)==null?void 0:Le[0];if(He){m(!0);try{const Ie=He.name.split(".").pop(),Te=`${Date.now()}.${Ie}`,{error:xe}=await V.storage.from("banner-images").upload(Te,He);if(xe)throw xe;const{data:{publicUrl:et}}=V.storage.from("banner-images").getPublicUrl(Te);T(et),ue.success("Image uploaded successfully")}catch(Ie){ue.error("Failed to upload image: "+Ie.message)}finally{m(!1)}}},ve=async()=>{if(!v.trim()||!S){ue.error("Please fill in required fields (title and image)");return}y(!0);try{const Ae={title:v.trim(),description:b.trim()||null,image_url:S,link_url:A.trim()||null,link_text:D.trim()||"Learn More",placement:$,section_after:$==="between"?z:null,is_active:K,start_date:Z?new Date(Z).toISOString():null,end_date:le?new Date(le).toISOString():null};if(c){const{error:He}=await V.from("dashboard_banners").update(Ae).eq("id",c.id);if(He)throw He;ue.success("Banner updated successfully")}else{const He=s.filter(Ie=>Ie.placement===$).length,{error:Le}=await V.from("dashboard_banners").insert({...Ae,sort_order:He});if(Le)throw Le;ue.success("Banner created successfully")}i(!1),ie(),ne()}catch(Ae){ue.error("Failed to save banner: "+Ae.message)}finally{y(!1)}},be=async()=>{if(c)try{const{error:Ae}=await V.from("dashboard_banners").delete().eq("id",c.id);if(Ae)throw Ae;ue.success("Banner deleted successfully"),o(!1),d(null),ne()}catch(Ae){ue.error("Failed to delete banner: "+Ae.message)}},Ue=async Ae=>{try{const{error:He}=await V.from("dashboard_banners").update({is_active:!Ae.is_active}).eq("id",Ae.id);if(He)throw He;ue.success(Ae.is_active?"Banner deactivated":"Banner activated"),ne()}catch(He){ue.error("Failed to update banner: "+He.message)}},Be=s.filter(Ae=>Ae.placement==="top"),De=s.filter(Ae=>Ae.placement==="between");return r?e.jsx(ws,{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(ws,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Nr,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(fs,{open:a&&$==="top",onOpenChange:Ae=>{Ae||ie(),i(Ae),Ae&&F("top")},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{onClick:()=>{ie(),F("top")},children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Hr,{children:"Configure the banner's content and display settings"})]}),e.jsx(tUe,{title:v,setTitle:w,description:b,setDescription:N,imageUrl:S,linkUrl:A,setLinkUrl:I,linkText:D,setLinkText:R,placement:$,setPlacement:F,sectionAfter:z,setSectionAfter:Q,isActive:K,setIsActive:X,startDate:Z,setStartDate:re,endDate:le,setEndDate:oe,handleImageUpload:ce,uploading:h,showPlacementOptions:!1}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>{i(!1),ie()},children:"Cancel"}),e.jsx(G,{onClick:ve,disabled:x,children:x?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Pe,{children:Be.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:Be.map(Ae=>e.jsx(sUe,{banner:Ae,onEdit:()=>ye(Ae),onDelete:()=>{d(Ae),o(!0)},onToggleActive:()=>Ue(Ae)},Ae.id))})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Nr,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(fs,{open:a&&$==="between",onOpenChange:Ae=>{Ae||ie(),i(Ae),Ae&&F("between")},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{onClick:()=>{ie(),F("between")},children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Hr,{children:"Configure where this banner appears between sections"})]}),e.jsx(tUe,{title:v,setTitle:w,description:b,setDescription:N,imageUrl:S,linkUrl:A,setLinkUrl:I,linkText:D,setLinkText:R,placement:$,setPlacement:F,sectionAfter:z,setSectionAfter:Q,isActive:K,setIsActive:X,startDate:Z,setStartDate:re,endDate:le,setEndDate:oe,handleImageUpload:ce,uploading:h,showPlacementOptions:!0}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>{i(!1),ie()},children:"Cancel"}),e.jsx(G,{onClick:ve,disabled:x,children:x?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Pe,{children:De.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:De.map(Ae=>e.jsx(sUe,{banner:Ae,onEdit:()=>ye(Ae),onDelete:()=>{d(Ae),o(!0)},onToggleActive:()=>Ue(Ae),showSection:!0},Ae.id))})})]})]}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Delete Banner"}),e.jsxs(Hr,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}function tUe({title:s,setTitle:t,description:r,setDescription:n,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:h,sectionAfter:m,setSectionAfter:x,isActive:y,setIsActive:v,startDate:w,setStartDate:b,endDate:N,setEndDate:S,handleImageUpload:T,uploading:A,showPlacementOptions:I}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",placeholder:"Banner headline...",value:s,onChange:D=>t(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",placeholder:"Optional banner description...",value:r,onChange:D=>n(D.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:T,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(he,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(Ne,{id:"linkUrl",placeholder:"https://...",value:i,onChange:D=>l(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"linkText",children:"Button Text"}),e.jsx(Ne,{id:"linkText",placeholder:"Learn More",value:o,onChange:D=>c(D.target.value)})]})]}),I&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Placement"}),e.jsxs(Is,{value:m,onValueChange:x,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select section placement..."})}),e.jsx(Ms,{children:cht.map(D=>e.jsx(ct,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(Ne,{id:"startDate",type:"datetime-local",value:w,onChange:D=>b(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(Ne,{id:"endDate",type:"datetime-local",value:N,onChange:D=>S(D.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(_r,{id:"isActive",checked:y,onCheckedChange:v}),e.jsx(he,{htmlFor:"isActive",children:"Active"})]})})]})}function sUe({banner:s,onEdit:t,onDelete:r,onToggleActive:n,showSection:a=!1}){var c;const i=(c=cht.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=k.useState(null);return k.useEffect(()=>{(async()=>{const{count:h}=await V.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(h??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(vu,{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(Ge,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Ge,{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(qc,{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(G,{variant:"ghost",size:"icon",children:e.jsx(Qr,{className:"h-4 w-4"})})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:n,children:s.is_active?e.jsx(bn,{className:"h-4 w-4"}):e.jsx(Xh,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})]})}const L$={open:{label:"Open",icon:fn,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Jl,color:"bg-blue-500"},resolved:{label:"Resolved",icon:di,color:"bg-green-500"},closed:{label:"Closed",icon:Sc,color:"bg-muted-foreground"}},rUe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function ICs(){var $,F;const{user:s}=js(),t=Xt(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),[c,d]=k.useState("all"),[h,m]=k.useState("all"),[x,y]=k.useState(!1),{data:v=[],isLoading:w}=mt({queryKey:["admin-support-tickets",c,h],queryFn:async()=>{let z=V.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(z=z.eq("status",c)),h!=="all"&&(z=z.eq("category",h));const{data:Q,error:K}=await z;if(K)throw K;return Q}}),{data:b=[]}=mt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:z,error:Q}=await V.from("user_roles").select("user_id").eq("role","admin");if(Q)throw Q;const K=z.map(ne=>ne.user_id),{data:X,error:Z}=await V.from("profiles").select("id, name, email").in("id",K);if(Z)throw Z;const{data:re,error:le}=await V.from("support_notification_settings").select("user_id, receive_notifications");if(le)throw le;const oe=new Map((re==null?void 0:re.map(ne=>[ne.user_id,ne.receive_notifications]))||[]);return X.map(ne=>({...ne,receives_notifications:oe.get(ne.id)||!1}))}}),{data:N=[]}=mt({queryKey:["admin-ticket-replies",r==null?void 0:r.id],queryFn:async()=>{if(!r)return[];const{data:z,error:Q}=await V.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",r.id).order("created_at",{ascending:!0});if(Q)throw Q;return z},enabled:!!r}),S=Ct({mutationFn:async({userId:z,enabled:Q})=>{const{data:K}=await V.from("support_notification_settings").select("id").eq("user_id",z).maybeSingle();if(K){const{error:X}=await V.from("support_notification_settings").update({receive_notifications:Q}).eq("user_id",z);if(X)throw X}else{const{error:X}=await V.from("support_notification_settings").insert({user_id:z,receive_notifications:Q});if(X)throw X}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ue.success("Notification settings updated")},onError:()=>{ue.error("Failed to update settings")}}),T=Ct({mutationFn:async({ticketId:z,status:Q})=>{const{error:K}=await V.from("support_tickets").update({status:Q}).eq("id",z);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),r&&n({...r,status:r.status}),ue.success("Status updated")},onError:()=>{ue.error("Failed to update status")}}),A=Ct({mutationFn:async({ticketId:z,assignedTo:Q})=>{const{error:K}=await V.from("support_tickets").update({assigned_to:Q}).eq("id",z);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ue.success("Ticket assigned")},onError:()=>{ue.error("Failed to assign ticket")}}),I=Ct({mutationFn:async({content:z,attachments:Q})=>{var X,Z;if(!r||!s)throw new Error("Missing data");const{error:K}=await V.from("support_ticket_replies").insert({ticket_id:r.id,user_id:s.id,content:z,is_admin_reply:!0,attachments:Q});if(K)throw K;try{await V.functions.invoke("support-reply-notify",{body:{ticketId:r.id,ticketSubject:r.subject,replyContent:z,userEmail:(X=r.profiles)==null?void 0:X.email,userName:(Z=r.profiles)==null?void 0:Z.name}})}catch(re){console.error("Failed to send reply notification:",re)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",r==null?void 0:r.id]}),i(""),o([]),ue.success("Reply sent!")},onError:()=>{ue.error("Failed to send reply")}}),D=()=>{!a.trim()&&l.length===0||I.mutate({content:a,attachments:l})};k.useEffect(()=>{const z=V.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{V.removeChannel(z)}},[t]);const R=v.filter(z=>z.status==="open").length;return r?(L$[r.status].icon,e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>n(null),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:r.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"secondary",children:rUe[r.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",(($=r.profiles)==null?void 0:$.name)||"Unknown"," (",(F=r.profiles)==null?void 0:F.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm",children:"Status"})}),e.jsx(Pe,{children:e.jsxs(Is,{value:r.status,onValueChange:z=>{T.mutate({ticketId:r.id,status:z}),n({...r,status:z})},children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"open",children:"Open"}),e.jsx(ct,{value:"in_progress",children:"In Progress"}),e.jsx(ct,{value:"resolved",children:"Resolved"}),e.jsx(ct,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm",children:"Assigned To"})}),e.jsx(Pe,{children:e.jsxs(Is,{value:r.assigned_to||"unassigned",onValueChange:z=>{const Q=z==="unassigned"?null:z;A.mutate({ticketId:r.id,assignedTo:Q}),n({...r,assigned_to:Q})},children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Unassigned"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"unassigned",children:"Unassigned"}),b.map(z=>e.jsx(ct,{value:z.id,children:z.name},z.id))]})]})})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Nr,{children:["Created on ",_s(new Date(r.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Pe,{children:[e.jsx(Qa,{className:"h-[300px] pr-4",children:N.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:N.map(z=>{var Q,K;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?`${((Q=z.profiles)==null?void 0:Q.name)||"Admin"} (Support)`:((K=z.profiles)==null?void 0:K.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_s(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(zot,{attachments:z.attachments})]},z.id)})})}),e.jsx(fo,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(or,{placeholder:"Type your reply...",value:a,onChange:z=>i(z.target.value),className:"min-h-[80px]"}),e.jsx(G,{onClick:D,disabled:!a.trim()&&l.length===0||I.isPending,className:"self-end",children:e.jsx(en,{className:"h-4 w-4"})})]}),e.jsx(Bot,{value:l,onChange:o,disabled:I.isPending})]})]})]})]})})):e.jsx(ws,{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",R>0&&e.jsxs(Ge,{variant:"destructive",className:"ml-2",children:[R," open"]})]})]}),e.jsxs(fs,{open:x,onOpenChange:y,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",children:[e.jsx(oo,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Email Notification Settings"}),e.jsx(Hr,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:b.map(z=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Di,{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(_m,{className:"h-4 w-4 text-primary"}):e.jsx(ev,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(_r,{checked:z.receives_notifications,onCheckedChange:Q=>S.mutate({userId:z.id,enabled:Q})})]})]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(On,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Rn,{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(Is,{value:h,onValueChange:m,children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"All Categories"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Categories"}),e.jsx(ct,{value:"general",children:"General Support"}),e.jsx(ct,{value:"technology",children:"Technology Support"}),e.jsx(ct,{value:"crm",children:"CRM Support"}),e.jsx(ct,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:w?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):v.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"text-center py-12",children:[e.jsx(Jl,{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:v.map(z=>{var K,X;const Q=L$[z.status].icon;return e.jsx(ke,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>n(z),children:e.jsx(Pe,{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(Ge,{variant:"outline",className:"text-xs",children:rUe[z.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(K=z.profiles)==null?void 0:K.name," • ",_s(new Date(z.created_at),"MMM d, yyyy")]}),z.assigned_to&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Di,{className:"h-3 w-3"}),((X=b.find(Z=>Z.id===z.assigned_to))==null?void 0:X.name)||"Assigned"]})]})]}),e.jsxs(Ge,{className:L$[z.status].color,children:[e.jsx(Q,{className:"h-3 w-3 mr-1"}),L$[z.status].label]})]})})},z.id)})})})]})]})})}const dht=nm.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 LCs({content:s,onChange:t,variables:r}){const n=O3e({extensions:[B3e,Y3e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Z3e.configure({types:["heading","paragraph"]}),X3e,dht],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});k.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const a=l=>{n&&n.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!n)return;const l=n.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return n?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(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBold().run(),className:n.isActive("bold")?"bg-muted":"",children:e.jsx(Yw,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleItalic().run(),className:n.isActive("italic")?"bg-muted":"",children:e.jsx(tj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleBulletList().run(),className:n.isActive("bulletList")?"bg-muted":"",children:e.jsx(em,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleOrderedList().run(),className:n.isActive("orderedList")?"bg-muted":"",children:e.jsx(Cy,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("left").run(),className:n.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(E4,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("center").run(),className:n.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(T4,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().setTextAlign("right").run(),className:n.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(A4,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:i,className:n.isActive("link")?"bg-muted":"",children:e.jsx(po,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().toggleCodeBlock().run(),className:n.isActive("codeBlock")?"bg-muted":"",children:e.jsx(P4,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),children:e.jsx(cj,{className:"h-4 w-4"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),children:e.jsx(oj,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),r.length>0&&e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(TA,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(xd,{align:"end",className:"w-64",children:r.map(l=>e.jsxs(Pa,{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(D3e,{editor:n,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),r.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:r.map(l=>e.jsx(Ge,{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 PCs(){const s=Xt(),[t,r]=k.useState(null),[n,a]=k.useState(null),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(!0),[y,v]=k.useState("visual"),{data:w,isLoading:b}=mt({queryKey:["email-templates"],queryFn:async()=>{const{data:I,error:D}=await V.from("email_templates").select("*").order("name");if(D)throw D;return I.map(R=>({...R,available_variables:R.available_variables||[]}))}}),N=Ct({mutationFn:async I=>{const{error:D}=await V.from("email_templates").update({subject:I.subject,body_html:I.body_html,description:I.description,is_active:I.is_active}).eq("id",I.id);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ue.success("Email template updated successfully"),r(null)},onError:I=>{ue.error("Failed to update template: "+I.message)}}),S=I=>{r(I),l(I.subject),c(I.body_html),h(I.description||""),x(I.is_active),v("visual")},T=()=>{t&&N.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:m})},A=(I,D)=>{let R=I;return D.forEach($=>{const F=`{{${$.key}}}`,z=`[${$.label}]`;R=R.replace(new RegExp(F.replace(/[{}]/g,"\\$&"),"g"),z)}),R};return t?e.jsxs(ws,{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(G,{variant:"ghost",onClick:()=>r(null),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(G,{variant:"outline",onClick:()=>a(t),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(G,{onClick:T,disabled:N.isPending,children:[e.jsx(Bl,{className:"h-4 w-4 mr-2"}),N.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),t.name]}),e.jsxs(Nr,{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(he,{htmlFor:"active-toggle",children:"Active"}),e.jsx(_r,{id:"active-toggle",checked:m,onCheckedChange:x})]})]})}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",value:d,onChange:I=>h(I.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"subject",children:"Email Subject"}),e.jsx(Ne,{id:"subject",value:i,onChange:I=>l(I.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(he,{children:"Email Body"}),e.jsx(On,{value:y,onValueChange:I=>v(I),children:e.jsxs(Rn,{className:"h-8",children:[e.jsxs(Kt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(rj,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Kt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(P4,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),y==="visual"?e.jsx(LCs,{content:o,onChange:c,variables:t.available_variables}):e.jsx(or,{value:o,onChange:I=>c(I.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(fs,{open:!!n,onOpenChange:()=>a(null),children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Email Preview"}),e.jsxs(Hr,{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(ws,{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"})]}),b?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((I,D)=>e.jsx(ke,{children:e.jsxs(Mt,{children:[e.jsx(Fs,{className:"h-5 w-48"}),e.jsx(Fs,{className:"h-4 w-96"})]})},D))}):e.jsx("div",{className:"grid gap-4",children:w==null?void 0:w.map(I=>e.jsxs(ke,{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(Dt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Vs,{className:"h-5 w-5 text-muted-foreground"}),I.name,!I.is_active&&e.jsx(Ge,{variant:"secondary",children:"Inactive"})]}),e.jsx(Nr,{children:I.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>a(I),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(G,{size:"sm",onClick:()=>S(I),children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Pe,{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:I.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:I.available_variables.map(D=>e.jsx(Ge,{variant:"outline",className:"font-mono text-xs",children:`{{${D.key}}}`},D.key))})]})]})})]},I.id))}),e.jsx(fs,{open:!!n&&!t,onOpenChange:()=>a(null),children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:["Email Preview: ",n==null?void 0:n.name]}),e.jsxs(Hr,{children:["Subject: ",n==null?void 0:n.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),n&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(n.body_html,n.available_variables)}})})]})})]})})}function DCs(){const s=Xt(),[t,r]=k.useState("templates"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[y,v]=k.useState({name:"",description:"",icon:"📧"}),{data:w=[]}=mt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:z,error:Q}=await V.from("email_template_categories").select("*").order("sort_order");if(Q)throw Q;return z}}),{data:b=[],isLoading:N}=mt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:z,error:Q}=await V.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(Q)throw Q;return z}}),S=Ct({mutationFn:async z=>{const Q={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:K}=await V.from("agent_email_templates").update(Q).eq("id",z.id);if(K)throw K}else{const{error:K}=await V.from("agent_email_templates").insert(Q);if(K)throw K}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ue.success(n?"Template updated":"Template created")},onError:()=>ue.error("Failed to save template")}),T=Ct({mutationFn:async z=>{const{error:Q}=await V.from("agent_email_templates").delete().eq("id",z);if(Q)throw Q},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ue.success("Template deleted")}}),A=Ct({mutationFn:async z=>{const Q={name:z.name,description:z.description||null,icon:z.icon};if(z.id){const{error:K}=await V.from("email_template_categories").update(Q).eq("id",z.id);if(K)throw K}else{const K=w.length>0?Math.max(...w.map(Z=>Z.sort_order))+1:0,{error:X}=await V.from("email_template_categories").insert({...Q,sort_order:K});if(X)throw X}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),h(!1),ue.success(i?"Category updated":"Category created")},onError:()=>ue.error("Failed to save category")}),I=Ct({mutationFn:async z=>{const{error:Q}=await V.from("email_template_categories").delete().eq("id",z);if(Q)throw Q},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ue.success("Category deleted")}}),D=()=>{a(null),x({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},R=z=>{a(z),x({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)},$=()=>{l(null),v({name:"",description:"",icon:"📧"}),h(!0)},F=z=>{l(z),v({name:z.name,description:z.description||"",icon:z.icon}),h(!0)};return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(eh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(On,{value:t,onValueChange:r,children:[e.jsxs(Rn,{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(Qh,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(ts,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(G,{onClick:D,className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Template"}),e.jsx(Nt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Nt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:N?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8",children:e.jsx(es,{className:"h-6 w-6 animate-spin mx-auto"})})}):b.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):b.map(z=>e.jsxs(Ds,{children:[e.jsx(dt,{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(dt,{className:"hidden md:table-cell",children:z.category?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[z.category.icon," ",z.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(dt,{className:"hidden md:table-cell",children:z.tone?e.jsx(Ge,{variant:"secondary",children:z.tone}):"—"}),e.jsx(dt,{children:e.jsx(Ge,{variant:z.is_active?"default":"secondary",children:z.is_active?"Active":"Inactive"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>R(z),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&T.mutate(z.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},z.id))})]})})})]}),e.jsxs(ts,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(G,{onClick:$,className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:w.map(z=>e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{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(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>F(z),children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&I.mutate(z.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Pe,{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:[b.filter(Q=>Q.category_id===z.id).length," templates"]})]})]},z.id))})]})]}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:n?"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(he,{children:"Title"}),e.jsx(Ne,{value:m.title,onChange:z=>x(Q=>({...Q,title:z.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Category"}),e.jsxs(Is,{value:m.category_id,onValueChange:z=>x(Q=>({...Q,category_id:z})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select category"})}),e.jsx(Ms,{children:w.map(z=>e.jsxs(ct,{value:z.id,children:[z.icon," ",z.name]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Subject Line"}),e.jsx(Ne,{value:m.subject,onChange:z=>x(Q=>({...Q,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(he,{children:"Email Body"}),e.jsx(or,{value:m.body,onChange:z=>x(Q=>({...Q,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(he,{children:"Description (internal)"}),e.jsx(Ne,{value:m.description,onChange:z=>x(Q=>({...Q,description:z.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Tone"}),e.jsx(Ne,{value:m.tone,onChange:z=>x(Q=>({...Q,tone:z.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{checked:m.is_active,onCheckedChange:z=>x(Q=>({...Q,is_active:z}))}),e.jsx(he,{children:"Active"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>S.mutate({...m,id:n==null?void 0:n.id}),disabled:S.isPending||!m.title||!m.subject||!m.body,children:[S.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Save Changes":"Create Template"]})]})]})}),e.jsx(fs,{open:d,onOpenChange:h,children:e.jsxs(ms,{className:"sm:max-w-[450px]",children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{children:"Icon"}),e.jsx(Ne,{value:y.icon,onChange:z=>v(Q=>({...Q,icon:z.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Name"}),e.jsx(Ne,{value:y.name,onChange:z=>v(Q=>({...Q,name:z.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Description"}),e.jsx(Ne,{value:y.description,onChange:z=>v(Q=>({...Q,description:z.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>A.mutate({...y,id:i==null?void 0:i.id}),disabled:A.isPending||!y.name,children:[A.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const RCs=({brokerageId:s})=>{var gr,zt;const{toast:t}=Ma(),r=br(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,h]=k.useState("all"),[m,x]=k.useState(new Set),[y,v]=k.useState(!1),[w,b]=k.useState({}),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[I,D]=k.useState({email:"",name:"",password:"",phone:""}),[R,$]=k.useState(!1),[F,z]=k.useState(null),[Q,K]=k.useState(!1),[X,Z]=k.useState(!1),[re,le]=k.useState(!1),[oe,ne]=k.useState(""),[ie,ye]=k.useState(!1),[ce,ve]=k.useState([]),[be,Ue]=k.useState(!1),[Be,De]=k.useState(!1),[Ae,He]=k.useState(null),[Le,Ie]=k.useState({name:"",phone:"",email:""}),[Te,xe]=k.useState(!1),[et,fe]=k.useState(!1),[it,Oe]=k.useState(null),[Ye,We]=k.useState("asc"),[_e,Re]=k.useState(!1),[tt,Ke]=k.useState(null),[Ze,lt]=k.useState(!1),[xt,Xe]=k.useState(null),[Je,jt]=k.useState(""),[ns,Ns]=k.useState(!1),[Ys,rs]=k.useState(null);k.useEffect(()=>{cs(),bt()},[s]);const bt=async()=>{try{const{data:Se,error:ze}=await V.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(ze)throw ze;ve((Se==null?void 0:Se.map(st=>st.user_id))||[])}catch(Se){console.error("Error loading brokerage managers:",Se)}},cs=async()=>{try{l(!0);const{data:Se,error:ze}=await V.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(ze)throw ze;const st=Se.agents||[];if(a(st),st.length>0){const gt=st.map(Ft=>Ft.id),{data:At}=await V.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",gt);if(At&&At.length>0){const Ft=At.map(Jt=>Jt.assistant_id),{data:Wt}=await V.from("profiles").select("id, name, email").in("id",Ft),Vt={};for(const Jt of At){const qs=Wt==null?void 0:Wt.find(Cs=>Cs.id===Jt.assistant_id);qs&&(Vt[Jt.agent_id]={name:qs.name||"",email:qs.email||""})}b(Vt)}else b({})}}catch(Se){console.error("Error loading agents:",Se),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},yt=async()=>{if(!I.email||!I.name||!I.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:Se}}=await V.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se==null?void 0:Se.access_token}`},body:JSON.stringify({...I,brokerageId:s})}),st=await ze.json();if(!ze.ok)throw new Error(st.error||"Failed to create agent");t({title:"Success",description:`Agent ${I.email} created successfully`}),D({email:"",name:"",password:"",phone:""}),S(!1),cs()}catch(Se){console.error("Error creating agent:",Se),t({title:"Error",description:Se.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},is=async Se=>{try{const{data:{session:ze}}=await V.auth.getSession(),st=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ze==null?void 0:ze.access_token}`},body:JSON.stringify({userId:Se})}),gt=await st.json();if(!st.ok)throw new Error(gt.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(ze){console.error("Error resending welcome email:",ze),t({title:"Error",description:ze.message||"Failed to resend welcome email",variant:"destructive"})}},Bs=async(Se,ze)=>{try{const{error:st}=await V.functions.invoke("send-password-reset",{body:{email:Se,redirectTo:window.location.origin}});if(st)throw st;t({title:"Password Reset Sent",description:`Password reset email sent to ${ze}`})}catch(st){console.error("Error sending password reset:",st),t({title:"Error",description:st.message||"Failed to send password reset email",variant:"destructive"})}},ps=Se=>{z(Se),$(!0)},lr=Se=>{He(Se),Ie({name:Se.name,phone:Se.phone||"",email:Se.email}),De(!0)},kr=async()=>{if(!Ae)return;if(!Le.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Se=Le.email.trim().toLowerCase()!==Ae.email.toLowerCase();xe(!0);try{if(Se){if(!Le.email.trim())throw new Error("Email is required");fe(!0);const{data:{session:st}}=await V.auth.getSession(),gt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${st==null?void 0:st.access_token}`},body:JSON.stringify({agentId:Ae.id,newEmail:Le.email.trim(),brokerageId:s})}),At=await gt.json();if(fe(!1),!gt.ok)throw new Error(At.error||"Failed to update email")}const{error:ze}=await V.from("profiles").update({name:Le.name.trim(),phone:Le.phone.trim()||null}).eq("id",Ae.id);if(ze)throw ze;t({title:"Success",description:"Agent profile updated successfully"}),De(!1),He(null),cs()}catch(ze){console.error("Error updating agent:",ze),t({title:"Error",description:ze.message||"Failed to update agent",variant:"destructive"})}finally{xe(!1),fe(!1)}},Lr=async()=>{if(!oe){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}ye(!0);try{const{data:{session:Se}}=await V.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se==null?void 0:Se.access_token}`},body:JSON.stringify({userId:oe,role:"brokerage_manager",action:"add",brokerageId:s})}),st=await ze.json();if(!ze.ok)throw new Error(st.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),le(!1),ne(""),bt()}catch(Se){console.error("Error adding brokerage manager:",Se),t({title:"Error",description:Se.message||"Failed to add brokerage manager",variant:"destructive"})}finally{ye(!1)}},qr=async Se=>{try{const{data:{session:ze}}=await V.auth.getSession(),st=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ze==null?void 0:ze.access_token}`},body:JSON.stringify({userId:Se,role:"brokerage_manager",action:"remove",brokerageId:s})}),gt=await st.json();if(!st.ok)throw new Error(gt.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),bt()}catch(ze){console.error("Error removing brokerage manager:",ze),t({title:"Error",description:ze.message||"Failed to remove brokerage manager",variant:"destructive"})}},Ur=Se=>ce.includes(Se),Mr=Se=>{Xe(Se),jt(""),lt(!0)},Cr=async()=>{if(!(!xt||!Je)){if(Je.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Ns(!0);try{const{data:{session:Se}}=await V.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se==null?void 0:Se.access_token}`},body:JSON.stringify({agentId:xt.id,brokerageId:s,action:"set_password",newPassword:Je})}),st=await ze.json();if(!ze.ok)throw new Error(st.error||"Failed to set password");t({title:"Success",description:`Password set for ${xt.name}`}),lt(!1),Xe(null),jt("")}catch(Se){console.error("Error setting password:",Se),t({title:"Error",description:Se.message||"Failed to set password",variant:"destructive"})}finally{Ns(!1)}}},Xr=async Se=>{rs(Se.id);try{const{data:{session:ze}}=await V.auth.getSession(),st=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ze==null?void 0:ze.access_token}`},body:JSON.stringify({agentId:Se.id,brokerageId:s,action:"claim_account"})}),gt=await st.json();if(!st.ok)throw new Error(gt.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Se.name}`}),cs()}catch(ze){console.error("Error claiming account:",ze),t({title:"Error",description:ze.message||"Failed to claim account",variant:"destructive"})}finally{rs(null)}},Ln=async()=>{if(F){K(!0);try{const{data:{session:Se}}=await V.auth.getSession(),ze=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Se==null?void 0:Se.access_token}`},body:JSON.stringify({userId:F.id,brokerageId:s})}),st=await ze.json();if(!ze.ok)throw new Error(st.error||"Failed to remove agent");t({title:"Success",description:`${F.name} has been removed from your brokerage`}),$(!1),z(null),cs()}catch(Se){console.error("Error removing agent:",Se),t({title:"Error",description:Se.message||"Failed to remove agent",variant:"destructive"})}finally{K(!1)}}},Zs=Se=>{const ze=Se.trim().split(" ");return ze.length>1?ze[ze.length-1].toLowerCase():Se.toLowerCase()},Yr=Se=>{it===Se?We(Ye==="asc"?"desc":"asc"):(Oe(Se),We("asc"))},ss=Se=>it!==Se?e.jsx(Ad,{className:"ml-1 h-4 w-4"}):Ye==="asc"?e.jsx(Id,{className:"ml-1 h-4 w-4"}):e.jsx(Hu,{className:"ml-1 h-4 w-4"}),ta=n.filter(Se=>{if(d==="active"&&!Se.claimed||d==="pending"&&Se.claimed)return!1;if(!o)return!0;const ze=o.toLowerCase();return Se.name.toLowerCase().includes(ze)||Se.email.toLowerCase().includes(ze)}),nn=[...ta].sort((Se,ze)=>{if(!it)return 0;let st=0;return it==="name"?st=Zs(Se.name).localeCompare(Zs(ze.name)):it==="status"&&(st=Se.claimed===ze.claimed?0:Se.claimed?-1:1),Ye==="asc"?st:-st});ta.filter(Se=>Se.claimed&&!Ur(Se.id));const hr=Se=>{x(ze=>{const st=new Set(ze);return st.has(Se)?st.delete(Se):st.add(Se),st})},Pr=()=>{m.size===nn.length?x(new Set):x(new Set(nn.map(Se=>Se.id)))},Qn=()=>{x(new Set)},Gt=async()=>{const Se=Array.from(m);if(Se.length===0)return;v(!0);let ze=0,st=0;try{const{data:{session:gt}}=await V.auth.getSession();for(const At of Se)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${gt==null?void 0:gt.access_token}`},body:JSON.stringify({userId:At})})).ok?ze++:st++}catch{st++}ze>0?t({title:"Success",description:`Welcome emails sent to ${ze} agent${ze>1?"s":""}${st>0?` (${st} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Qn()}catch(gt){console.error("Error bulk sending welcome emails:",gt),t({title:"Error",description:gt.message||"Failed to send welcome emails",variant:"destructive"})}finally{v(!1)}};return i?e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Agents"}),e.jsx(Nr,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>le(!0),children:[e.jsx(Wu,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(G,{variant:"outline",onClick:()=>Z(!0),children:[e.jsx(mb,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(G,{onClick:()=>S(!0),children:[e.jsx(sl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Pe,{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(yn,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:o,onChange:Se=>c(Se.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:d,onValueChange:Se=>h(Se),children:[e.jsx(As,{className:"w-[160px]",children:e.jsx(Ls,{placeholder:"Filter by status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Agents"}),e.jsx(ct,{value:"active",children:"Active"}),e.jsx(ct,{value:"pending",children:"Pending"})]})]})]}),m.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:[m.size," agent",m.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{const ze=n.filter(st=>m.has(st.id)&&st.email).map(st=>({email:st.email,name:st.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(ze)),r("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:ze}})},disabled:y,children:[e.jsx(bu,{className:"mr-2 h-4 w-4"}),"Email Agents (",m.size,")"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:Gt,disabled:y,children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),y?"Sending...":"Resend Welcome Email"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:Qn,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[40px]",children:e.jsx(Si,{checked:nn.length>0&&m.size===nn.length,onCheckedChange:Pr,"aria-label":"Select all"})}),e.jsx(Nt,{children:e.jsxs(G,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Yr("name"),children:["Name (Last)",ss("name")]})}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:e.jsxs(G,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Yr("status"),children:["Status",ss("status")]})}),e.jsx(Nt,{children:"Actions"})]})}),e.jsx($n,{children:nn.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):nn.map(Se=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx(Si,{checked:m.has(Se.id),onCheckedChange:()=>hr(Se.id),"aria-label":`Select ${Se.name}`})}),e.jsx(dt,{className:"font-medium",children:Se.name}),e.jsx(dt,{children:Se.email}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Se.claimed?e.jsx(Ge,{variant:"default",children:"Active"}):e.jsx(Ge,{variant:"secondary",children:"Pending"}),Ur(Se.id)&&e.jsxs(Ge,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(Ey,{className:"mr-1 h-3 w-3"}),"Manager"]}),w[Se.id]&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:[e.jsx(pr,{className:"mr-1 h-3 w-3"}),"Asst: ",w[Se.id].name||w[Se.id].email]})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{Ke(Se),Re(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(eu,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>lr(Se),title:"Edit agent",children:e.jsx(Ea,{className:"h-4 w-4"})}),!Se.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>is(Se.id),title:"Resend welcome email",children:e.jsx(Vs,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>Xr(Se),title:"Claim account for agent",disabled:Ys===Se.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(uv,{className:"h-4 w-4"})})]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>Mr(Se),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Hc,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>Bs(Se.email,Se.name),title:"Send password reset email",children:e.jsx(z4,{className:"h-4 w-4"})}),Ur(Se.id)&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>qr(Se.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Wu,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>ps(Se),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Se.id))})]})})]})]}),e.jsx(fs,{open:N,onOpenChange:S,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add New Agent"}),e.jsx(Hr,{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(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",value:I.name,onChange:Se=>D({...I,name:Se.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:I.email,onChange:Se=>D({...I,email:Se.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(Ne,{id:"phone",type:"tel",value:I.phone,onChange:Se=>D({...I,phone:Se.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"password",children:"Temporary Password"}),e.jsx(Ne,{id:"password",type:"password",value:I.password,onChange:Se=>D({...I,password:Se.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(G,{onClick:yt,disabled:T,children:T?"Creating...":"Create Agent"})]})]})}),e.jsx(fs,{open:R,onOpenChange:$,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Remove Agent"}),e.jsxs(Hr,{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(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>$(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:Ln,disabled:Q,children:Q?"Removing...":"Remove Agent"})]})]})}),e.jsx($ot,{open:X,onOpenChange:Z,fixedBrokerageId:s,onSuccess:cs}),e.jsx(fs,{open:re,onOpenChange:le,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add Brokerage Manager"}),e.jsx(Hr,{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(he,{children:"Select Agent"}),e.jsxs(To,{open:be,onOpenChange:Ue,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":be,className:"w-full justify-between",children:[oe?((gr=n.find(Se=>Se.id===oe))==null?void 0:gr.name)+" ("+((zt=n.find(Se=>Se.id===oe))==null?void 0:zt.email)+")":"Select an agent to promote...",e.jsx(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-full p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search by name or email..."}),e.jsxs(ax,{className:"max-h-[200px]",children:[e.jsx(ix,{children:"No eligible agents found."}),e.jsx(ox,{children:n.filter(Se=>!Ur(Se.id)).map(Se=>e.jsxs(cf,{value:`${Se.name} ${Se.email}`,onSelect:()=>{ne(Se.id),Ue(!1)},children:[e.jsx(Kn,{className:`mr-2 h-4 w-4 ${oe===Se.id?"opacity-100":"opacity-0"}`}),Se.name," (",Se.email,")"]},Se.id))})]})]})})]}),n.filter(Se=>!Ur(Se.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsx(G,{onClick:Lr,disabled:ie||!oe,children:ie?"Adding...":"Add as Manager"})]})]})}),e.jsx(fs,{open:Be,onOpenChange:De,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Edit Agent"}),e.jsxs(Hr,{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(he,{htmlFor:"edit-name",children:"Name"}),e.jsx(Ne,{id:"edit-name",value:Le.name,onChange:Se=>Ie({...Le,name:Se.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"edit-email",children:"Email"}),e.jsx(Ne,{id:"edit-email",type:"email",value:Le.email,onChange:Se=>Ie({...Le,email:Se.target.value}),placeholder:"agent@example.com"}),Le.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(he,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(Ne,{id:"edit-phone",type:"tel",value:Le.phone,onChange:Se=>Ie({...Le,phone:Se.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>De(!1),children:"Cancel"}),e.jsx(G,{onClick:kr,disabled:Te||et,children:et?"Updating email...":Te?"Saving...":"Save Changes"})]})]})}),tt&&e.jsx(Uot,{open:_e,onOpenChange:Se=>{Re(Se),Se||Ke(null)},userId:tt.id,userName:tt.name}),e.jsx(fs,{open:Ze,onOpenChange:lt,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Set Password"}),e.jsxs(Hr,{children:["Set a new password for ",xt==null?void 0:xt.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(he,{htmlFor:"new-password",children:"New Password"}),e.jsx(Ne,{id:"new-password",type:"password",value:Je,onChange:Se=>jt(Se.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(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>lt(!1),children:"Cancel"}),e.jsx(G,{onClick:Cr,disabled:ns||!Je||Je.length<6,children:ns?"Setting...":"Set Password"})]})]})})]})},OCs={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},FCs={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},BCs=s=>{switch(s){case"academy_video":return e.jsx(Jr,{className:"h-4 w-4"});case"template":return e.jsx(ln,{className:"h-4 w-4"});case"toolbox":return e.jsx(ln,{className:"h-4 w-4"});case"newsletter":return e.jsx(iv,{className:"h-4 w-4"});case"social_swag":return e.jsx(jr,{className:"h-4 w-4"});case"event":return e.jsx(on,{className:"h-4 w-4"});default:return e.jsx(Qr,{className:"h-4 w-4"})}},zCs=({brokerageId:s})=>{const{toast:t}=Ma(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState([]),[c,d]=k.useState(!0),[h,m]=k.useState(null);k.useEffect(()=>{x()},[s]);const x=async()=>{try{d(!0);const{data:w,error:b}=await V.from("profiles").select("id, name, email").eq("brokerage_id",s);if(b)throw b;const N=w.map(Q=>Q.id),S=new Map(w.map(Q=>[Q.id,Q]));if(N.length===0){n([]),i([]),o([]);return}const{data:T,error:A}=await V.from("activity_logs").select("*").in("user_id",N).order("launched_at",{ascending:!1});if(A)throw A;const I=T.map(Q=>{var K,X;return{id:Q.id,user_id:Q.user_id,app_name:Q.app_name,launched_at:Q.launched_at,user_name:((K=S.get(Q.user_id))==null?void 0:K.name)||"Unknown",user_email:((X=S.get(Q.user_id))==null?void 0:X.email)||"Unknown"}});n(I);const{data:D,error:R}=await V.from("content_engagement_logs").select("*").in("user_id",N).order("created_at",{ascending:!1});if(R)throw R;const $=(D||[]).map(Q=>{var K,X;return{id:Q.id,user_id:Q.user_id,resource_type:Q.resource_type,resource_id:Q.resource_id,resource_title:Q.resource_title,action_type:Q.action_type,created_at:Q.created_at,user_name:((K=S.get(Q.user_id))==null?void 0:K.name)||"Unknown",user_email:((X=S.get(Q.user_id))==null?void 0:X.email)||"Unknown"}});i($);const F=new Map;w.forEach(Q=>{F.set(Q.id,{user_id:Q.id,user_name:Q.name,user_email:Q.email,app_launches:0,content_views:0,last_activity:""})}),I.forEach(Q=>{const K=F.get(Q.user_id);K&&(K.app_launches++,(!K.last_activity||new Date(Q.launched_at)>new Date(K.last_activity))&&(K.last_activity=Q.launched_at))}),$.forEach(Q=>{const K=F.get(Q.user_id);K&&(K.content_views++,(!K.last_activity||new Date(Q.created_at)>new Date(K.last_activity))&&(K.last_activity=Q.created_at))});const z=Array.from(F.values()).filter(Q=>Q.app_launches>0||Q.content_views>0).sort((Q,K)=>new Date(K.last_activity).getTime()-new Date(Q.last_activity).getTime());o(z)}catch(w){console.error("Error loading activity:",w),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},y=w=>r.filter(b=>b.user_id===w),v=w=>a.filter(b=>b.user_id===w);return c?e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Agent Activity"}),e.jsx(Nr,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{className:"text-center",children:"App Launches"}),e.jsx(Nt,{className:"text-center",children:"Content Views"}),e.jsx(Nt,{children:"Last Active"})]})}),e.jsx($n,{children:l.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(w=>e.jsxs(Ds,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>m({id:w.user_id,name:w.user_name,email:w.user_email}),children:[e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:w.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:w.user_email})]})}),e.jsx(dt,{className:"text-center",children:e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Uo,{className:"h-3 w-3"}),w.app_launches]})}),e.jsx(dt,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(ln,{className:"h-3 w-3"}),w.content_views]})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:w.last_activity&&rl(new Date(w.last_activity),{addSuffix:!0})})]},w.user_id))})]})})})]}),e.jsx(fs,{open:!!h,onOpenChange:w=>!w&&m(null),children:e.jsxs(ms,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Hr,{children:h==null?void 0:h.email})]}),e.jsxs(On,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rn,{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(ts,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Resource"}),e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Action"}),e.jsx(Nt,{children:"Time"})]})}),e.jsx($n,{children:h&&v(h.id).length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):h&&v(h.id).map(w=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"max-w-[200px] truncate font-medium",children:w.resource_title}),e.jsx(dt,{children:e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[BCs(w.resource_type),OCs[w.resource_type]||w.resource_type]})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:FCs[w.action_type]||w.action_type})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:rl(new Date(w.created_at),{addSuffix:!0})})]},w.id))})]})})}),e.jsx(ts,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"App"}),e.jsx(Nt,{children:"Time"})]})}),e.jsx($n,{children:h&&y(h.id).length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):h&&y(h.id).map(w=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",children:w.app_name})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:rl(new Date(w.launched_at),{addSuffix:!0})})]},w.id))})]})})})]})]})})]})},$Cs=({brokerageId:s})=>{const{toast:t}=Ma(),[r,n]=k.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=k.useState(!0);k.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await V.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(I=>I.id),h=d.length;if(d.length===0){i(!1);return}const{data:m,error:x}=await V.from("profiles").select("id, email").in("id",d);if(x)throw x;const{count:y}=await V.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),v=y||0,w=h-v,{count:b}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),N=new Date;N.setDate(N.getDate()-7);const{count:S}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",N.toISOString()),T=new Date;T.setMonth(T.getMonth()-1);const{count:A}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",T.toISOString());n({totalAgents:h,activeAgents:v,pendingAgents:w,totalLaunches:b||0,launchesThisWeek:S||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(ke,{children:e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.activeAgents," active, ",r.pendingAgents," pending"]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.totalAgents>0?`${Math.round(r.activeAgents/r.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(fn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(vh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(vh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(vh,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Pe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:r.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},UCs=({brokerageId:s})=>{const[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState({description:"",maxUses:""});k.useEffect(()=>{m()},[s]);const m=async()=>{try{const{data:N,error:S}=await V.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(S)throw S;r(N||[])}catch(N){console.error("Error loading invite codes:",N),ue.error("Failed to load invite links")}finally{a(!1)}},x=()=>Math.random().toString(36).substring(2,8).toUpperCase(),y=async()=>{l(!0);try{const N=x(),{error:S}=await V.from("invite_codes").insert({code:N,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(S)throw S;ue.success("Invite link created!"),c(!1),h({description:"",maxUses:""}),m()}catch(N){console.error("Error creating invite code:",N),ue.error("Failed to create invite link")}finally{l(!1)}},v=async N=>{try{const{error:S}=await V.from("invite_codes").delete().eq("id",N);if(S)throw S;ue.success("Invite link deleted"),r(t.filter(T=>T.id!==N))}catch(S){console.error("Error deleting invite code:",S),ue.error("Failed to delete invite link")}},w=async(N,S)=>{try{const{error:T}=await V.from("invite_codes").update({is_active:!S}).eq("id",N);if(T)throw T;r(t.map(A=>A.id===N?{...A,is_active:!S}:A)),ue.success(`Invite link ${S?"deactivated":"activated"}`)}catch(T){console.error("Error toggling invite code:",T),ue.error("Failed to update invite link")}},b=N=>{const S=`${window.location.origin}/join?code=${N}`;navigator.clipboard.writeText(S),ue.success("Link copied to clipboard!")};return n?e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-8",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(po,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Nr,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(fs,{open:o,onOpenChange:c,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create Invite Link"}),e.jsx(Hr,{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(he,{htmlFor:"description",children:"Description (optional)"}),e.jsx(Ne,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:N=>h({...d,description:N.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(Ne,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:N=>h({...d,maxUses:N.target.value})})]}),e.jsx(G,{onClick:y,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Pe,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(po,{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(N=>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:N.code}),e.jsx(Ge,{variant:N.is_active?"default":"secondary",children:N.is_active?"Active":"Inactive"})]}),N.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:N.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[N.uses_count," uses",N.max_uses&&` / ${N.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>b(N.code),title:"Copy link",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>w(N.id,N.is_active),title:N.is_active?"Deactivate":"Activate",children:N.is_active?"Disable":"Enable"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>v(N.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},N.id))})})]})},qCs=({open:s,onOpenChange:t,referralCode:r,brokerageId:n,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=k.useState(""),[d,h]=k.useState([]),[m,x]=k.useState(""),[y,v]=k.useState(!1),w=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),b=()=>{const A=o.trim().toLowerCase();if(A&&w(A)&&!d.includes(A)){if(d.length>=10){ue.error("Maximum 10 emails per invite");return}h([...d,A]),c("")}else A&&!w(A)?ue.error("Please enter a valid email address"):d.includes(A)&&ue.error("Email already added")},N=A=>{h(d.filter(I=>I!==A))},S=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),b())},T=async()=>{if(d.length===0){ue.error("Please add at least one email address");return}v(!0);try{const{data:A,error:I}=await V.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:m.trim()||void 0,referralCode:r,brokerageId:n,senderName:a,brokerageName:i}});if(I)throw I;A.successCount===A.totalCount?ue.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):ue.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),h([]),x(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),ue.error("Failed to send invites. Please try again.")}finally{v(!1)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[550px]",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Hr,{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(ii,{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(he,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:A=>c(A.target.value),onKeyDown:S,onBlur:b}),e.jsx(G,{type:"button",variant:"secondary",onClick:b,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(Ge,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[A,e.jsx("button",{type:"button",onClick:()=>N(A),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(vr,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(or,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:m,onChange:A=>x(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[m.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(jr,{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(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:T,disabled:d.length===0||y,children:y?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(en,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},VCs=({brokerageId:s,refreshTrigger:t})=>{const[r,n]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await V.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;n(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Ge,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(di,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Ge,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Sc,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(fn,{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"})}):r.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"}),r.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 ",_s(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},HCs=()=>{const{brokerageId:s,user:t}=js(),[r,n]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState([]),[h,m]=k.useState(!0),[x,y]=k.useState(!1),[v,w]=k.useState(0);k.useEffect(()=>{s&&b()},[s]);const b=async()=>{try{const[D,R]=await Promise.all([V.from("brokerages").select("name").eq("id",s).single(),t?V.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);D.data&&i(D.data.name),R.data&&o(R.data.name||"A LevelUp Member");const{data:$}=await V.from("referral_codes").select("code").eq("brokerage_id",s).single();if($)n($.code);else{const z=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await V.from("referral_codes").insert({brokerage_id:s,code:z}),n(z)}const{data:F}=await V.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(D){console.error("Error fetching referral data:",D)}finally{m(!1)}},N=()=>{const D=`https://dashboard.relevelup.com/?ref=${r}`;navigator.clipboard.writeText(D),ue.success("Referral link copied to clipboard!")},S=c.filter(D=>D.status==="qualified").length,T=c.filter(D=>D.status==="pending").length,A=S*25,I=Math.max(0,Math.ceil((299-A)/25));return h?null:e.jsxs(e.Fragment,{children:[e.jsxs(ke,{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(ii,{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(di,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),I>0&&A<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",I," 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(jr,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Pe,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(G,{onClick:()=>y(!0),className:"w-full",size:"lg",children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(G,{onClick:N,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Ra,{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=",r]})]}),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(wl,{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(pr,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:S}),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(fn,{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:T}),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(VCs,{brokerageId:s,refreshTrigger:v}),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(D=>{var R,$;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:((R=D.referred_brokerage)==null?void 0:R.name)||(($=D.referred_user)==null?void 0:$.email)||"Pending setup"}),e.jsxs(Ge,{variant:D.status==="qualified"?"default":D.status==="pending"?"secondary":"destructive",className:D.status==="qualified"?"bg-green-600":"",children:[D.status==="qualified"&&e.jsx(di,{className:"h-3 w-3 mr-1"}),D.status]})]},D.id)})]})]})]}),e.jsx(qCs,{open:x,onOpenChange:y,referralCode:r||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>w(D=>D+1)})]})},GCs=({brokerageId:s})=>{const t=br(),{teams:r,isLoading:n}=l5(s),{data:a,isLoading:i}=mt({queryKey:["team-aggregate-stats",s,r.map(h=>h.id)],queryFn:async()=>{if(r.length===0)return[];const h=r.map(D=>D.id),{data:m}=await V.from("team_members").select("team_id, user_id, role").in("team_id",h);if(!m||m.length===0)return r.map(D=>({team_id:D.id,team_name:D.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const x=m.map(D=>D.user_id),y=m.filter(D=>D.role==="team_leader").map(D=>D.user_id),{data:v}=await V.from("profiles").select("id, name, avatar_url").in("id",y),w=new Map((v||[]).map(D=>[D.id,D])),{data:b}=await V.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",x),{data:N}=await V.from("deal_pipeline").select("owner_user_id").in("owner_user_id",x),{data:S}=await V.from("agent_videos").select("owner_user_id").in("owner_user_id",x).eq("is_deleted",!1),T=new Map;(b||[]).forEach(D=>{T.set(D.owner_user_id,(T.get(D.owner_user_id)||0)+1)});const A=new Map;(N||[]).forEach(D=>{A.set(D.owner_user_id,(A.get(D.owner_user_id)||0)+1)});const I=new Map;return(S||[]).forEach(D=>{I.set(D.owner_user_id,(I.get(D.owner_user_id)||0)+1)}),r.map(D=>{const R=m.filter(Z=>Z.team_id===D.id),$=R.find(Z=>Z.role==="team_leader"),F=$?w.get($.user_id):null,z=R.map(Z=>Z.user_id),Q=z.reduce((Z,re)=>Z+(T.get(re)||0),0),K=z.reduce((Z,re)=>Z+(A.get(re)||0),0),X=z.reduce((Z,re)=>Z+(I.get(re)||0),0);return{team_id:D.id,team_name:D.name,member_count:R.length,leader_name:(F==null?void 0:F.name)||null,leader_avatar:(F==null?void 0:F.avatar_url)||null,total_contacts:Q,total_deals:K,total_videos:X}})},enabled:r.length>0});if(n||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(h=>e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Fs,{className:"h-5 w-32"})}),e.jsx(Pe,{children:e.jsx(Fs,{className:"h-24 w-full"})})]},h))});if(r.length===0)return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pr,{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(G,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((h,m)=>h+m.member_count,0),c=(a||[]).reduce((h,m)=>h+m.total_contacts,0),d=(a||[]).reduce((h,m)=>h+m.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(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(pr,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:r.length})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(pr,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(R4,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Gu,{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(h=>e.jsxs(ke,{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(Dt,{className:"text-lg",children:h.team_name}),e.jsxs(Ge,{variant:"secondary",children:[h.member_count," members"]})]}),h.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Nn,{className:"h-6 w-6",children:[e.jsx(ya,{src:h.leader_avatar||""}),e.jsx(kn,{className:"text-xs",children:h.leader_name.charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Zh,{className:"h-3 w-3 text-amber-500"}),h.leader_name]})]})]}),e.jsx(Pe,{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:h.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:h.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:h.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},h.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx(G,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},WCs=()=>{const{user:s,isBrokerageManager:t,brokerageId:r,isAdmin:n,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=js(),o=br(),{toast:c}=Ma(),[d,h]=k.useState(""),[m,x]=k.useState(!0),y=i||(a.length>0?a[0].id:r);k.useEffect(()=>{if(!s||!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),y?v():a.length===0&&!r&&x(!1)},[s,t,n,y,o,a,i]);const v=async()=>{if(!y){x(!1);return}try{const{data:w,error:b}=await V.from("brokerages").select("name").eq("id",y).single();if(b)throw b;h(w.name)}catch(w){console.error("Error loading brokerage info:",w),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{x(!1)}};return m?e.jsx(ws,{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"})})}):y?e.jsx(ws,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(Is,{value:i||"",onValueChange:l,children:[e.jsxs(As,{className:"w-[280px]",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),e.jsx(Ls,{placeholder:"Select brokerage"})]}),e.jsx(Ms,{children:a.map(w=>e.jsx(ct,{value:w.id,children:w.name},w.id))})]})]}),e.jsxs(On,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Rn,{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(ts,{value:"agents",className:"space-y-4",children:e.jsx(RCs,{brokerageId:y})}),e.jsx(ts,{value:"teams",className:"space-y-4",children:e.jsx(GCs,{brokerageId:y})}),e.jsx(ts,{value:"invite",className:"space-y-4",children:e.jsx(UCs,{brokerageId:y})}),e.jsx(ts,{value:"referrals",className:"space-y-4",children:e.jsx(HCs,{})}),e.jsx(ts,{value:"leaderboard",className:"space-y-4",children:e.jsx(not,{brokerageId:y,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(ts,{value:"activity",className:"space-y-4",children:e.jsx(zCs,{brokerageId:y})}),e.jsx(ts,{value:"analytics",className:"space-y-4",children:e.jsx($Cs,{brokerageId:y})}),e.jsx(ts,{value:"shares",className:"space-y-4",children:e.jsx(ylt,{brokerageOnly:!0,brokerageId:y})})]})]})}):e.jsx(ws,{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(Sa,{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 KCs({brokerageId:s,canManage:t}){const{user:r}=js(),[n,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),[y,v]=k.useState(!1),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(!1),I=async()=>{try{const{data:z,error:Q}=await V.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(Q)throw Q;const K=z;if(K&&K.length>0){const X=[...new Set(K.map(oe=>oe.created_by))],{data:Z}=await V.from("profiles").select("id, name, avatar_url").in("id",X),re=new Map((Z==null?void 0:Z.map(oe=>[oe.id,oe]))||[]),le=K.map(oe=>({...oe,author:re.get(oe.created_by)||{name:"Unknown",avatar_url:null}}));a(le)}else a([])}catch(z){console.error("Error fetching announcements:",z)}finally{l(!1)}};k.useEffect(()=>{I()},[s]);const D=()=>{b(""),S(""),A(!1),h(null)},R=z=>{z?(h(z),b(z.title),S(z.content),A(z.is_pinned)):D(),c(!0)},$=async()=>{if(!w.trim()||!N.trim()){ue.error("Please fill in all fields");return}v(!0);try{if(d){const{error:z}=await V.from("brokerage_announcements").update({title:w.trim(),content:N.trim(),is_pinned:T,pinned_at:T?new Date().toISOString():null}).eq("id",d.id);if(z)throw z;ue.success("Announcement updated")}else{const{error:z}=await V.from("brokerage_announcements").insert({brokerage_id:s,created_by:r==null?void 0:r.id,title:w.trim(),content:N.trim(),is_pinned:T,pinned_at:T?new Date().toISOString():null});if(z)throw z;ue.success("Announcement created")}c(!1),D(),I()}catch(z){console.error("Error saving announcement:",z),ue.error("Failed to save announcement")}finally{v(!1)}},F=async()=>{if(m)try{const{error:z}=await V.from("brokerage_announcements").delete().eq("id",m);if(z)throw z;ue.success("Announcement deleted"),I()}catch(z){console.error("Error deleting announcement:",z),ue.error("Failed to delete announcement")}finally{x(null)}};return i?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(bu,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(bu,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(G,{size:"sm",onClick:()=>R(),className:"gap-1",children:[e.jsx($s,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Pe,{children:n.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:n.map(z=>{var Q,K,X,Z;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(ij,{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(Nn,{className:"h-5 w-5",children:[e.jsx(ya,{src:((Q=z.author)==null?void 0:Q.avatar_url)||void 0}),e.jsx(kn,{className:"text-[10px]",children:((X=(K=z.author)==null?void 0:K.name)==null?void 0:X.charAt(0))||"?"})]}),e.jsx("span",{children:(Z=z.author)==null?void 0:Z.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:_s(new Date(z.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>R(z),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>x(z.id),children:e.jsx(yr,{className:"h-4 w-4"})})]})]})},z.id)})})})]}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",value:w,onChange:z=>b(z.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"content",children:"Content"}),e.jsx(or,{id:"content",value:N,onChange:z=>S(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(_r,{id:"pinned",checked:T,onCheckedChange:A}),e.jsxs(he,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(ij,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{onClick:$,disabled:y,children:y?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Ko,{open:!!m,onOpenChange:()=>x(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Announcement"}),e.jsx(Bo,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:F,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function YCs({brokerageId:s,canManage:t=!1}){const{startImpersonation:r,isLoading:n}=Yme(),{user:a}=js(),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,h]=k.useState(""),[m,x]=k.useState(new Set);k.useEffect(()=>{(async()=>{try{const{data:w,error:b}=await V.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(b)throw b;if(l(w||[]),w&&w.length>0){const N=w.map(T=>T.id),{data:S}=await V.from("agent_assistant_assignments").select("agent_id").in("agent_id",N);S&&x(new Set(S.map(T=>T.agent_id)))}}catch(w){console.error("Error fetching agents:",w)}finally{c(!1)}})()},[s]);const y=i.filter(v=>{var w,b;return v.name.toLowerCase().includes(d.toLowerCase())||v.email.toLowerCase().includes(d.toLowerCase())||((w=v.title)==null?void 0:w.toLowerCase().includes(d.toLowerCase()))||((b=v.areas_served)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Pe,{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(v=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},v))})})]}):e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(pr,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:d,onChange:v=>h(v.target.value),className:"pl-9"})]})]}),e.jsx(Pe,{children:y.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:y.map(v=>e.jsx(ZCs,{agent:v,hasAssistant:m.has(v.id),canImpersonate:t&&v.id!==(a==null?void 0:a.id),onImpersonate:()=>r(v.id,"/my-brokerage"),impersonationLoading:n},v.id))})})]})}function ZCs({agent:s,hasAssistant:t,canImpersonate:r,onImpersonate:n,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(Nn,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(ya,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(kn,{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(Ge,{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(Ca,{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:[r&&e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:n,disabled:a,children:e.jsx(V4,{className:"h-4 w-4"})})}),e.jsxs(Gl,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(G,{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(Cn,{className:"h-4 w-4"})})}),e.jsx(G,{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(G,{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(Jh,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(G,{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(Jd,{className:"h-4 w-4"})})})]})]})}function XCs({brokerageId:s}){const[t,r]=k.useState([]),[n,a]=k.useState(!0);if(k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),a(!1);return}const h=c.map(w=>w.id),{data:m,error:x}=await V.from("agent_attendance_stats").select("user_id, total_points").in("user_id",h).order("total_points",{ascending:!1});if(x)throw x;const y=new Map(c.map(w=>[w.id,w])),v=(m||[]).filter(w=>w.total_points>0).map(w=>{const b=y.get(w.user_id);return{user_id:w.user_id,total_points:w.total_points,name:(b==null?void 0:b.name)||"Unknown",avatar_url:(b==null?void 0:b.avatar_url)||null}});r(v)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),n)return e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Pe,{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(xb,{className:It("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Pe,{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(m=>m[0]).join("").toUpperCase().slice(0,2),h=c+1;return e.jsxs("div",{className:It("flex items-center gap-3 p-2 rounded-lg",h<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(h)}),e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:o.avatar_url||void 0}),e.jsx(kn,{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 QCs({brokerageId:s}){const t=br(),[r,n]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),i(!1);return}const h=c.map(w=>w.id),m=new Map(c.map(w=>[w.id,w])),{data:x,error:y}=await V.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",h).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(y)throw y;const v=(x||[]).map(w=>({id:w.id,slug:w.slug,property_address:w.property_address,city:w.city,price:w.price,property_type:w.property_type,agent_id:w.agent_id,agent:m.get(w.agent_id)||null,photos:w.listing_photos||[]}));n(v)}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(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Pe,{children:[r.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(En,{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(G,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:r.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(En,{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))}),r.length>0&&e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(Qr,{className:"h-3 w-3 ml-1"})]})]})]})}function JCs(){const{user:s,isAdmin:t,isBrokerageManager:r}=js(),n=br(),[a,i]=k.useState(!0),[l,o]=k.useState(null),[c,d]=k.useState(""),[h,m]=k.useState(0),[x,y]=k.useState(!1),[v,w]=k.useState(!1);return k.useEffect(()=>{(async()=>{if(s)try{const{data:N}=await V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(N!=null&&N.brokerage_id)){i(!1);return}o(N.brokerage_id);const{data:S}=await V.from("brokerages").select("name").eq("id",N.brokerage_id).maybeSingle();S&&d(S.name);const{count:T}=await V.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",N.brokerage_id);if(m(T||0),t)y(!0),w(!0);else if(r){const{data:A}=await V.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",N.brokerage_id).maybeSingle();y(!!A),w(!!A)}}catch(N){console.error("Error fetching brokerage info:",N)}finally{i(!1)}})()},[s,t,r]),a?e.jsx(ws,{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(ws,{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(pr,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[h," ",h===1?"Agent":"Agents"]})]}),v&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>n("/brokerage-content"),children:[e.jsx(bh,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(G,{onClick:()=>n(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(KCs,{brokerageId:l,canManage:x}),e.jsx(YCs,{brokerageId:l,canManage:x}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(XCs,{brokerageId:l}),e.jsx(QCs,{brokerageId:l})]})]})}):e.jsx(ws,{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(Sa,{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 e4s(s){if(!s)return null;try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}function t4s(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 nUe={video:{icon:Uo,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:ln,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:tl,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:on,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 s4s({item:s,canManage:t}){const[r,n]=k.useState(!1),[a,i]=k.useState(null),l=u$t(),o=br(),c=nUe[s.content_type]||nUe.link,d=c.icon,h=k.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?e4s(s.url):null,[s]);k.useEffect(()=>{h||!s.url||s.content_type!=="video"||!t4s(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(v=>v.ok?v.json():null).then(v=>{v!=null&&v.thumbnail_url&&i(v.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,h]);const m=h||a,x=()=>{o(`/brokerage-content/${s.id}`)},y=async()=>{try{await l.mutateAsync(s.id),ue.success("Content deleted")}catch{ue.error("Failed to delete")}n(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:x,children:[m?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:m,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(Pe,{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(Ge,{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(Ge,{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:["📅 ",_s(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",_s(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,onClick:v=>v.stopPropagation(),children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Yx,{className:"h-4 w-4"})})}),e.jsx(xd,{align:"end",children:e.jsxs(Pa,{onClick:v=>{v.stopPropagation(),n(!0)},className:"text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Ko,{open:r,onOpenChange:n,children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Content"}),e.jsxs(Bo,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:y,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function r4s(s){try{const t=new URL(s),r=t.hostname.replace("www.","");let n=null;if(r==="youtube.com"||r==="m.youtube.com"?n=t.searchParams.get("v"):r==="youtu.be"&&(n=t.pathname.slice(1)),n)return`https://img.youtube.com/vi/${n}/hqdefault.jpg`}catch{}return null}const aUe=[{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 n4s({brokerageId:s,categories:t}){var ve;const{user:r}=js(),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,h]=k.useState("📁"),[m,x]=k.useState(!1);k.useRef(null);const[y,v]=k.useState("video"),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[I,D]=k.useState(""),[R,$]=k.useState(""),[F,z]=k.useState(""),[Q,K]=k.useState(""),X=d$t(),Z=h$t(s),re=m$t(),le=f$t(s),oe=()=>{v("video"),b(""),S(""),A(""),D(""),$(""),z(""),K("")},ne=async(be,Ue)=>{var De;const Be=(De=be.target.files)==null?void 0:De[0];if(Be){x(!0);try{const Ae=Be.name.split(".").pop(),He=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Ae}`,{error:Le}=await V.storage.from("brokerage-content").upload(He,Be);if(Le)throw Le;const{data:{publicUrl:Ie}}=V.storage.from("brokerage-content").getPublicUrl(He);Ue==="file"?(D(Ie),y==="graphic"&&!R&&$(Ie)):$(Ie),ue.success("File uploaded")}catch(Ae){ue.error(Ae.message||"Upload failed")}finally{x(!1)}}},ie=async()=>{if(!w.trim()){ue.error("Title is required");return}if(r)try{await X.mutateAsync({brokerage_id:s,category_id:Q||null,content_type:y,title:w.trim(),description:N.trim()||null,url:T.trim()||null,file_url:I.trim()||null,thumbnail_url:R.trim()||null,event_date:F?new Date(F).toISOString():null,created_by:r.id}),ue.success("Content added!"),oe(),a(!1)}catch(be){ue.error(be.message||"Failed to add content")}},ye=async()=>{if(o.trim())try{await Z.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),h("📁"),ue.success("Category created")}catch(be){ue.error(be.message||"Failed to create category")}},ce=async()=>{try{await le.mutateAsync(),ue.success("Default categories created")}catch{ue.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(fs,{open:n,onOpenChange:a,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(ms,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{children:"Content Type"}),e.jsxs(Is,{value:y,onValueChange:v,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:aUe.map(be=>e.jsx(ct,{value:be.value,children:be.label},be.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ve=aUe.find(be=>be.value===y))==null?void 0:ve.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Category"}),e.jsxs(Is,{value:Q,onValueChange:K,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select category (optional)"})}),e.jsx(Ms,{children:t.map(be=>e.jsxs(ct,{value:be.id,children:[be.icon," ",be.name]},be.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Title *"}),e.jsx(Ne,{value:w,onChange:be=>b(be.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:N,onChange:be=>S(be.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(y)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:y==="video"?"Video URL":y==="graphic"?"Canva / Image URL":y==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(Ne,{value:T,onChange:be=>{const Ue=be.target.value;if(A(Ue),y==="video"&&!R){const Be=r4s(Ue);Be&&$(Be)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(y)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:y==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"file",accept:y==="pdf"?".pdf,.doc,.docx":"image/*",onChange:be=>ne(be,"file"),disabled:m}),m&&e.jsx(es,{className:"h-4 w-4 animate-spin"})]}),I&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Thumbnail Image (optional)"}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:be=>ne(be,"thumbnail"),disabled:m}),R&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:R,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>$(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(vr,{className:"h-3 w-3"})})]})]}),y==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Event Date & Time"}),e.jsx(Ne,{type:"datetime-local",value:F,onChange:be=>z(be.target.value)})]}),e.jsxs(G,{onClick:ie,disabled:X.isPending||!w.trim(),className:"w-full",children:[X.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(fs,{open:i,onOpenChange:l,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",children:[e.jsx(oo,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{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(G,{variant:"outline",size:"sm",onClick:ce,disabled:le.isPending,children:[le.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(be=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[be.icon," ",be.name]}),!be.is_default&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await re.mutateAsync(be.id),ue.success("Category deleted")},children:e.jsx(vr,{className:"h-4 w-4"})})]},be.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(Ne,{value:d,onChange:be=>h(be.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(Ne,{value:o,onChange:be=>c(be.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:be=>be.key==="Enter"&&ye()}),e.jsx(G,{size:"sm",onClick:ye,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function a4s(){const{user:s,isAdmin:t,isBrokerageManager:r}=js(),[n,a]=k.useState(!0),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState(null),[y,v]=k.useState("");k.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await V.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:I}=await V.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(I&&c(I.name),t)h(!0);else if(r){const{data:D}=await V.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();h(!!D)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,r]);const{data:w=[]}=o$t(i),{data:b=[],isLoading:N}=l$t(i,m),S=k.useMemo(()=>{if(!y.trim())return b;const T=y.toLowerCase();return b.filter(A=>{var I;return A.title.toLowerCase().includes(T)||((I=A.description)==null?void 0:I.toLowerCase().includes(T))||A.content_type.toLowerCase().includes(T)})},[b,y]);return n?e.jsx(ws,{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(ws,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(n4s,{brokerageId:i,categories:w}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search content...",value:y,onChange:T=>v(T.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(G,{variant:m===null?"default":"outline",size:"sm",onClick:()=>x(null),children:"All"}),w.map(T=>e.jsxs(G,{variant:m===T.id?"default":"outline",size:"sm",onClick:()=>x(T.id),children:[e.jsx("span",{className:"mr-1",children:T.icon}),T.name]},T.id))]})]}),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"})}):S.length===0?e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Qh,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:y.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:y.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:S.map(T=>e.jsx(s4s,{item:T,canManage:d},T.id))})]})}):e.jsx(ws,{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(Sa,{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 iUe={video:{icon:Uo,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:ln,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:tl,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:on,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 i4s(s){try{const t=new URL(s),r=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const n=t.searchParams.get("list");if(n)return`https://www.youtube.com/embed/videoseries?list=${n}`}if(r==="youtube.com"||r==="m.youtube.com"){const n=t.searchParams.get("v");if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtu.be"){const n=t.pathname.slice(1);if(n){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${n}`;return a&&(i+=`?list=${a}`),i}}if(r==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function o4s(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function l4s(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function c4s(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function d4s(){const{contentId:s}=Ki(),{data:t,isLoading:r}=mt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:h}=await V.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(h)throw h;return d},enabled:!!s});if(r)return e.jsx(ws,{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(ws,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sa,{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(G,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/brokerage-content",children:"Back to Content"})})]})});const n=iUe[t.content_type]||iUe.link,a=n.icon,i=t.url||t.file_url,l=i&&o4s(i)?i4s(i):null,o=i&&l4s(i)?c4s(i):null,c=l||o;return e.jsx(ws,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/brokerage-content",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ge,{variant:"secondary",className:`text-xs px-2 py-0.5 ${n.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),n.label]}),t.category&&e.jsxs(Ge,{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 ",_s(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(ke,{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(ke,{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(ke,{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(ke,{children:e.jsx(Pe,{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(ke,{children:e.jsxs(Pe,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(on,{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:_s(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(G,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(G,{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(Qr,{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 Hhe={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 u4s(s="open"){const{user:t}=js();return mt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let r=V.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")r=r.eq("status","open");else if(s==="mine")r=r.eq("requester_user_id",t.id);else if(s==="filled")r=r.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await V.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[];r=r.in("id",l)}const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})}function h4s(s){return mt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function m4s(s){return mt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})}function f4s(){const s=Xt(),{user:t,brokerageId:r}=js();return Ct({mutationFn:async n=>{if(!t||!r)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await V.from("brokerage_help_requests").insert({...n,brokerage_id:r,requester_user_id:t.id}).select().single();if(i)throw i;try{await V.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 p4s(){const s=Xt(),{user:t}=js();return Ct({mutationFn:async({request_id:r,note:n})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await V.from("brokerage_help_claims").insert({request_id:r,claimant_user_id:t.id,note:n}).select().single();if(i)throw i;return a},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function x4s(){const s=Xt();return Ct({mutationFn:async({claim_id:t,request_id:r,claimant_user_id:n})=>{const{error:a}=await V.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await V.from("brokerage_help_requests").update({status:"filled",assigned_user_id:n}).eq("id",r);if(i)throw i;try{await V.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function g4s(){const s=Xt();return Ct({mutationFn:async({claim_id:t})=>{const{error:r}=await V.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]})}})}function y4s(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",r]})}})}function v4s(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(r)throw r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",r]})}})}function b4s(){const{user:s,brokerageId:t}=js(),r=Xt(),n=mt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await V.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=Ct({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await V.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:()=>{r.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...n,setEmailEnabled:a.mutate,isSaving:a.isPending}}function _4s(s,t){if(!s)return null;const r=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),n=r(s,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});if(t){const a=r(t,{hour:"numeric",minute:"2-digit"});return`${n} – ${a} ET`}return`${n} ET`}function w4s(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 j4s({req:s,onClick:t}){var i;const r=Hhe[s.request_type],n=_4s(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Pe,{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(Ge,{variant:"secondary",className:"text-xs",children:[r.emoji," ",r.label]}),s.status!=="open"&&e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(va,{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:[n&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:n})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{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(wl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:w4s(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 N4s(){var c;const s=br(),{brokerageId:t}=js(),[r,n]=k.useState("open"),{data:a=[],isLoading:i}=u4s(r),l=b4s(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(ws,{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(On,{value:r,onValueChange:d=>n(d),children:e.jsxs(Rn,{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(G,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Pe,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(_m,{className:"h-4 w-4 text-primary"}):e.jsx(ev,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(he,{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(_r,{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(ke,{className:"bg-muted/30 border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(fy,{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:r==="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(j4s,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(ws,{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(fy,{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 k4s(){const s=br(),{toast:t}=Ma(),r=f4s(),[n,a]=k.useState("open_house"),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[I,D]=k.useState(""),[R,$]=k.useState(""),[F,z]=k.useState("goodwill"),[Q,K]=k.useState(""),[X,Z]=k.useState(""),re=n==="open_house"||n==="showing_coverage",le=n!=="general",oe=(ie,ye)=>!ie||!ye?null:`${ie}T${ye}:00`,ne=async ie=>{if(ie.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const ye=oe(d,m),ce=oe(d,y);await r.mutateAsync({request_type:n,title:i.trim(),description:o.trim()||null,event_start_at:ye,event_end_at:ce,address:re&&w.trim()||null,city:re&&N.trim()||null,state:re&&T.trim()||null,zip:re&&I.trim()||null,mls_number:R.trim()||null,compensation_type:F,compensation_amount:Q?Number(Q):null,compensation_notes:X.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(ye){t({title:"Could not post",description:(ye==null?void 0:ye.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(ws,{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(G,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ne,children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(Hhe).map(ie=>{const ye=Hhe[ie],ce=ie===n;return e.jsxs("button",{type:"button",onClick:()=>a(ie),className:`text-left p-3 rounded-lg border-2 transition ${ce?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:ye.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ye.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ye.description})]},ie)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:i,onChange:ie=>l(ie.target.value),placeholder:n==="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(he,{htmlFor:"description",children:"Details"}),e.jsx(or,{id:"description",value:o,onChange:ie=>c(ie.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),le&&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(he,{htmlFor:"date",children:"Date"}),e.jsx(Ne,{id:"date",type:"date",value:d,onChange:ie=>h(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"start",children:"Start"}),e.jsx(Ne,{id:"start",type:"time",value:m,onChange:ie=>x(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"end",children:"End"}),e.jsx(Ne,{id:"end",type:"time",value:y,onChange:ie=>v(ie.target.value)})]})]}),re&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"address",children:"Address"}),e.jsx(Ne,{id:"address",value:w,onChange:ie=>b(ie.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(he,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:N,onChange:ie=>S(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:T,onChange:ie=>A(ie.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(he,{htmlFor:"zip",children:"Zip"}),e.jsx(Ne,{id:"zip",value:I,onChange:ie=>D(ie.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(Ne,{id:"mls",value:R,onChange:ie=>$(ie.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(he,{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(ie=>{const ye=F===ie.val;return e.jsxs("button",{type:"button",onClick:()=>z(ie.val),className:`text-left p-3 rounded-lg border-2 transition ${ye?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ie.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ie.sub})]},ie.val)})}),F!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"amount",children:F==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(Ne,{id:"amount",type:"number",min:"0",step:F==="referral_percent"?"1":"5",value:Q,onChange:ie=>K(ie.target.value),placeholder:F==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(Ne,{id:"comp-notes",value:X,onChange:ie=>Z(ie.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(G,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:r.isPending,className:"gap-2",children:[r.isPending&&e.jsx(es,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function S4s(s,t){if(!s)return null;const r=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),n=r(s,{weekday:"long",month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});return t?`${n} – ${r(t,{hour:"numeric",minute:"2-digit"})} ET`:`${n} ET`}function cbe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function C4s(){var R,$,F,z,Q,K,X,Z;const{id:s}=Ki(),t=br(),{user:r}=js(),{toast:n}=Ma(),{data:a,isLoading:i}=h4s(s),{data:l=[]}=m4s(s),o=p4s(),c=x4s(),d=g4s(),h=y4s(),m=v4s(),[x,y]=k.useState("");if(i)return e.jsx(ws,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(ws,{title:"Not Found",description:"",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Request not found or you don't have access."})]});const v=Hhe[a.request_type],w=S4s(a.event_start_at,a.event_end_at),b=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),N=(r==null?void 0:r.id)===a.requester_user_id,S=l.find(re=>re.claimant_user_id===(r==null?void 0:r.id)),T=l.find(re=>re.status==="accepted"),A=a.status==="open",I=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)",D=async()=>{if(!x.trim()){n({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:x.trim()}),n({title:"You're in!",description:"The requester will review and pick someone."}),y("")}catch(re){n({title:"Could not submit",description:re==null?void 0:re.message,variant:"destructive"})}};return e.jsx(ws,{title:a.title,description:`${v.emoji} ${v.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx(ke,{children:e.jsxs(Pe,{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(Ge,{variant:"secondary",children:[v.emoji," ",v.label]}),e.jsx(Ge,{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(Nn,{className:"h-7 w-7",children:[e.jsx(ya,{src:((R=a.requester)==null?void 0:R.avatar_url)||void 0}),e.jsx(kn,{children:cbe(($=a.requester)==null?void 0:$.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:[w&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(fn,{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:w})]})]}),b&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Ca,{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:b})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(wl,{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:I})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Jw,{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]})]})}),!N&&A&&!S&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(or,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:x,onChange:re=>y(re.target.value),rows:3,maxLength:400}),e.jsxs(G,{onClick:D,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(es,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!N&&S&&e.jsx(ke,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(Kn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",S.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[S.status==="pending"&&"Waiting for the requester to pick.",S.status==="accepted"&&"You're confirmed — see contact info below.",S.status==="declined"&&"They went with someone else this time."]})]})]})}),T&&(N||T.claimant_user_id===(r==null?void 0:r.id))&&e.jsx(ke,{className:"border-primary/30",children:e.jsxs(Pe,{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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:((z=T.claimant)==null?void 0:z.avatar_url)||void 0}),e.jsx(kn,{children:cbe((Q=T.claimant)==null?void 0:Q.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(K=T.claimant)==null?void 0:K.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:[((X=T.claimant)==null?void 0:X.email)&&e.jsxs("a",{href:`mailto:${T.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Vs,{className:"h-4 w-4"})," ",T.claimant.email]}),((Z=T.claimant)==null?void 0:Z.phone)&&e.jsxs("a",{href:`tel:${T.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Cn,{className:"h-4 w-4"})," ",T.claimant.phone]})]})]})}),N&&e.jsx(ke,{children:e.jsxs(Pe,{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(re=>{var le,oe,ne,ie,ye;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:((le=re.claimant)==null?void 0:le.avatar_url)||void 0}),e.jsx(kn,{children:cbe((oe=re.claimant)==null?void 0:oe.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium",children:((ne=re.claimant)==null?void 0:ne.name)||"Teammate"}),e.jsx(Ge,{variant:"outline",className:"capitalize text-xs",children:re.status})]}),re.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',re.note,'"']}),re.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(G,{size:"sm",onClick:()=>c.mutate({claim_id:re.id,request_id:a.id,claimant_user_id:re.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Kn,{className:"h-3.5 w-3.5"})," Pick ",((ye=(ie=re.claimant)==null?void 0:ie.name)==null?void 0:ye.split(" ")[0])||"them"]}),e.jsxs(G,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:re.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(vr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},re.id)}),N&&A&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Cancel request"})}),N&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(G,{size:"sm",onClick:()=>m.mutate(a.id),disabled:m.isPending,children:"Mark complete"})})]})})]})})}var uht="Toggle",TTe=k.forwardRef((s,t)=>{const{pressed:r,defaultPressed:n,onPressedChange:a,...i}=s,[l,o]=Sh({prop:r,onChange:a,defaultProp:n??!1,caller:uht});return e.jsx(wn.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:Vr(s.onClick,()=>{s.disabled||o(!l)})})});TTe.displayName=uht;var hht=TTe,u2="ToggleGroup",[mht,WUs]=pd(u2,[Yj]),fht=Yj(),ETe=wt.forwardRef((s,t)=>{const{type:r,...n}=s;if(r==="single"){const a=n;return e.jsx(T4s,{...a,ref:t})}if(r==="multiple"){const a=n;return e.jsx(E4s,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${u2}\``)});ETe.displayName=u2;var[pht,xht]=mht(u2),T4s=wt.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=Sh({prop:r,defaultProp:n??"",onChange:a,caller:u2});return e.jsx(pht,{scope:s.__scopeToggleGroup,type:"single",value:wt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:wt.useCallback(()=>o(""),[o]),children:e.jsx(ght,{...i,ref:t})})}),E4s=wt.forwardRef((s,t)=>{const{value:r,defaultValue:n,onValueChange:a=()=>{},...i}=s,[l,o]=Sh({prop:r,defaultProp:n??[],onChange:a,caller:u2}),c=wt.useCallback(h=>o((m=[])=>[...m,h]),[o]),d=wt.useCallback(h=>o((m=[])=>m.filter(x=>x!==h)),[o]);return e.jsx(pht,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(ght,{...i,ref:t})})});ETe.displayName=u2;var[A4s,M4s]=mht(u2),ght=wt.forwardRef((s,t)=>{const{__scopeToggleGroup:r,disabled:n=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=fht(r),h=Kj(l),m={role:"group",dir:h,...c};return e.jsx(A4s,{scope:r,rovingFocus:a,disabled:n,children:a?e.jsx(Xme,{asChild:!0,...d,orientation:i,dir:h,loop:o,children:e.jsx(wn.div,{...m,ref:t})}):e.jsx(wn.div,{...m,ref:t})})}),Ghe="ToggleGroupItem",yht=wt.forwardRef((s,t)=>{const r=xht(Ghe,s.__scopeToggleGroup),n=M4s(Ghe,s.__scopeToggleGroup),a=fht(s.__scopeToggleGroup),i=r.value.includes(s.value),l=n.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=wt.useRef(null);return n.rovingFocus?e.jsx(Qme,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(oUe,{...o,ref:t})}):e.jsx(oUe,{...o,ref:t})});yht.displayName=Ghe;var oUe=wt.forwardRef((s,t)=>{const{__scopeToggleGroup:r,value:n,...a}=s,i=xht(Ghe,r),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(TTe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(n):i.onItemDeactivate(n)}})}),vht=ETe,bht=yht;const _ht=r5("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"}}),I4s=k.forwardRef(({className:s,variant:t,size:r,...n},a)=>e.jsx(hht,{ref:a,className:It(_ht({variant:t,size:r,className:s})),...n}));I4s.displayName=hht.displayName;const wht=k.createContext({size:"default",variant:"default"}),ATe=k.forwardRef(({className:s,variant:t,size:r,children:n,...a},i)=>e.jsx(vht,{ref:i,className:It("flex items-center justify-center gap-1",s),...a,children:e.jsx(wht.Provider,{value:{variant:t,size:r},children:n})}));ATe.displayName=vht.displayName;const Whe=k.forwardRef(({className:s,children:t,variant:r,size:n,...a},i)=>{const l=k.useContext(wht);return e.jsx(bht,{ref:i,className:It(_ht({variant:l.variant||r,size:l.size||n}),s),...a,children:t})});Whe.displayName=bht.displayName;const L4s=[{key:"search",label:"Search for Properties",icon:yn,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Cn,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:on,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:En,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:wl,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:Ca,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:Ec,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:qc,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function lUe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function P4s(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function jht({html:s,onChange:t}){const{user:r}=js(),n=k.useRef(null),a=k.useRef(""),i=k.useRef(t);i.current=t;const[l,o]=k.useState("desktop"),c=k.useRef(null),[d,h]=k.useState(!1),[m,x]=k.useState(""),[y,v]=k.useState(""),w=k.useRef(null),b=()=>{var yt;const bt=(yt=n.current)==null?void 0:yt.contentDocument,cs=bt==null?void 0:bt.getSelection();cs&&cs.rangeCount>0&&(bt!=null&&bt.body.contains(cs.anchorNode))&&(w.current=cs.getRangeAt(0).cloneRange())},N=()=>{var ps;const bt=c.current,cs=(ps=n.current)==null?void 0:ps.contentDocument;if(!bt||!cs)return;let yt=m.trim();yt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(yt)&&(yt="https://"+yt),bt.setAttribute("href",yt),bt.setAttribute("target","_blank");const is=y.trim();is&&is!==(bt.textContent||"").trim()&&(bt.textContent=is);const Bs=` `+cs.documentElement.outerHTML;a.current=Bs,i.current(Bs),h(!1)};k.useEffect(()=>{var yt,is;const bt=n.current;if(!bt||a.current===s)return;const cs=()=>{const Bs=bt.contentDocument;if(!Bs)return;Bs.open(),Bs.write(s||""),Bs.close(),a.current=s;const ps=Bs.body;if(!ps)return;ps.setAttribute("contenteditable","true"),ps.style.outline="none",ps.style.minHeight="400px",ps.style.cursor="text";const lr=()=>{const Lr=` `+Bs.documentElement.outerHTML;a.current=Lr,i.current(Lr)};ps.addEventListener("input",lr),ps.addEventListener("blur",lr),ps.addEventListener("mouseup",b),ps.addEventListener("keyup",b),Bs.addEventListener("selectionchange",b);const kr=Lr=>{var Ln;const qr=Lr.target,Ur=qr==null?void 0:qr.closest("a");if(Ur){if(Lr.metaKey||Lr.ctrlKey||Lr.shiftKey)return;Lr.preventDefault(),Lr.stopPropagation(),c.current=Ur,x(Ur.getAttribute("href")||""),v((Ur.textContent||"").trim()),h(!0);return}const Mr=Bs.getSelection();if(!Mr)return;const Cr=(Ln=Bs.caretRangeFromPoint)==null?void 0:Ln.call(Bs,Lr.clientX,Lr.clientY),Xr=Cr==null?void 0:Cr.startContainer;if(Xr&&Xr.nodeType===Node.TEXT_NODE){const Zs=Xr.textContent||"",Yr=Cr.startOffset,ss=Zs.lastIndexOf("[",Yr),ta=Zs.indexOf("]",Yr);if(ss!==-1&&ta!==-1&&ta>ss){const nn=Bs.createRange();nn.setStart(Xr,ss),nn.setEnd(Xr,ta+1),Mr.removeAllRanges(),Mr.addRange(nn),w.current=nn.cloneRange()}}};ps.addEventListener("click",kr,!0)};((yt=bt.contentDocument)==null?void 0:yt.readyState)==="complete"||(is=bt.contentDocument)!=null&&is.body?cs():bt.addEventListener("load",cs,{once:!0})},[s]);const S=(bt,cs)=>{var Bs;const yt=(Bs=n.current)==null?void 0:Bs.contentDocument;if(!yt)return;yt.body.focus(),yt.execCommand(bt,!1,cs);const is=` `+yt.documentElement.outerHTML;a.current=is,i.current(is)},T=()=>{const bt=window.prompt("Enter URL (https://...)");bt&&S("createLink",bt)},A=(bt,cs)=>{var Bs;const yt=(Bs=n.current)==null?void 0:Bs.contentDocument;if(!yt)return;if(yt.body.focus(),cs==="cursor"&&w.current&&yt.body.contains(w.current.startContainer)){const ps=yt.getSelection();if(ps){ps.removeAllRanges(),ps.addRange(w.current),yt.execCommand("insertHTML",!1,bt);const lr=` `+yt.documentElement.outerHTML;a.current=lr,i.current(lr);return}}cs==="top"?yt.body.insertAdjacentHTML("afterbegin",bt):yt.body.insertAdjacentHTML("beforeend",bt);const is=` `+yt.documentElement.outerHTML;a.current=is,i.current(is)},[I,D]=k.useState(!1),[R,$]=k.useState(null),[F,z]=k.useState(""),[Q,K]=k.useState(""),[X,Z]=k.useState("#406E71"),[re,le]=k.useState("cursor"),oe=bt=>{$(bt),z(bt.defaultText),K(""),D(!0)},ne=()=>{if(!R)return;const bt=Q.trim();if(!R.isForward&&!bt)return;let cs=bt;if(R.isForward){const ps=bt||"",lr=encodeURIComponent("You should see this newsletter"),kr=encodeURIComponent(ps?`I thought you'd like this — take a look: ${ps} `:`I thought you'd like this newsletter — take a look! `);cs=`mailto:?subject=${lr}&body=${kr}`}else R.hrefPrefix==="tel:"?cs="tel:"+bt.replace(/[^0-9+]/g,""):R.hrefPrefix==="mailto:"?cs="mailto:"+bt:/^https?:\/\//i.test(bt)||(cs="https://"+bt);const yt=(F||R.defaultText).replace(/[<>]/g,""),is=X||"#406E71",Bs=`
${yt}

 

`;A(Bs,re),D(!1)},[ie,ye]=k.useState(!1),[ce,ve]=k.useState(""),[be,Ue]=k.useState(""),[Be,De]=k.useState(""),[Ae,He]=k.useState("cursor"),Le=(()=>{if(be.trim())return be.trim();const bt=lUe(ce);return bt?`https://i.ytimg.com/vi/${bt}/hqdefault.jpg`:""})(),Ie=()=>{ve(""),Ue(""),De(""),ye(!0)},Te=()=>{const bt=ce.trim();if(!bt)return;let cs=bt;/^https?:\/\//i.test(cs)||(cs="https://"+cs);const yt=lUe(cs),is=yt?null:P4s(cs);let Bs=be.trim();!Bs&&yt&&(Bs=`https://i.ytimg.com/vi/${yt}/hqdefault.jpg`),!Bs&&is&&(Bs=`https://vumbnail.com/${is}.jpg`),Bs||(Bs="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const ps=(Be||"Watch the video").replace(/[<>]/g,""),lr=`
${ps}
▶ ${ps}

 

`.trim();A(lr,Ae),ye(!1)},[xe,et]=k.useState(!1),[fe,it]=k.useState(""),[Oe,Ye]=k.useState(""),[We,_e]=k.useState("full"),[Re,tt]=k.useState("cursor"),[Ke,Ze]=k.useState(!1),lt=k.useRef(null),xt=()=>{it(""),Ye(""),_e("full"),et(!0)},Xe=async bt=>{var cs;if(!r){ue.error("You must be signed in to upload images");return}if(bt.size>10*1024*1024){ue.error("Image must be under 10MB");return}Ze(!0);try{const yt=((cs=bt.name.split(".").pop())==null?void 0:cs.toLowerCase())||"png",is=`${r.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${yt}`,{error:Bs}=await V.storage.from("email-assets").upload(is,bt,{cacheControl:"3600",upsert:!1,contentType:bt.type});if(Bs)throw Bs;const{data:ps}=V.storage.from("email-assets").getPublicUrl(is);it(ps.publicUrl),ue.success("Image uploaded")}catch(yt){ue.error(yt.message||"Upload failed")}finally{Ze(!1)}},Je=()=>{if(!fe.trim())return;const bt=(Oe||"").replace(/[<>"]/g,""),cs=We==="half"?280:560,yt=`
${bt}

 

`.trim();A(yt,Re),et(!1)},{data:jt,isLoading:ns}=mt({queryKey:["newsletter-editor-videos",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&ie,queryFn:async()=>{const{data:bt,error:cs}=await V.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",r.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(cs)throw cs;return bt||[]}}),Ns=bt=>{bt.share_token&&(ve(`https://video.relevelup.com/share/video/${bt.share_token}`),Ue(`https://video.relevelup.com/thumb/${bt.share_token}`),De(bt.title||"Watch the video"))},Ys=l==="mobile"?390:"100%",rs=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(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("bold"),title:"Bold",children:e.jsx(Yw,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("italic"),title:"Italic",children:e.jsx(tj,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("underline"),title:"Underline",children:e.jsx(CA,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("insertUnorderedList"),title:"Bullet list",children:e.jsx(em,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("insertOrderedList"),title:"Numbered list",children:e.jsx(Cy,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:T,title:"Insert link",children:e.jsx(po,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("undo"),title:"Undo",children:e.jsx(cj,{className:"h-3.5 w-3.5"})}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>S("redo"),title:"Redo",children:e.jsx(oj,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(xd,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(m8,{children:"Insert a call-to-action"}),e.jsx(_v,{}),L4s.map(bt=>{const cs=bt.icon;return e.jsxs(Pa,{onClick:()=>oe(bt),children:[e.jsx(cs,{className:"h-4 w-4 mr-2"}),bt.label]},bt.key)})]})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:xt,children:[e.jsx(ml,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Ie,children:[e.jsx(Jr,{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(ATe,{type:"single",value:l,onValueChange:bt=>bt&&o(bt),size:"sm",className:"h-7",children:[e.jsx(Whe,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(rj,{className:"h-3.5 w-3.5"})}),e.jsx(Whe,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(ig,{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(qc,{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:n,title:"Newsletter visual editor",className:"bg-white",style:{width:Ys,maxWidth:rs,height:480,border:l==="mobile"?"1px solid hsl(var(--border))":"none",borderRadius:l==="mobile"?12:0,boxShadow:l==="mobile"?"0 4px 12px rgba(0,0,0,0.08)":"none"}})}),e.jsx(fs,{open:d,onOpenChange:h,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(Ne,{id:"link-edit-text",value:y,onChange:bt=>v(bt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(Ne,{id:"link-edit-href",value:m,onChange:bt=>x(bt.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(an,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:N,disabled:!m.trim(),children:"Save link"})]})]})}),e.jsx(fs,{open:I,onOpenChange:D,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Insert ",(R==null?void 0:R.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"cta-text",children:"Button text"}),e.jsx(Ne,{id:"cta-text",value:F,onChange:bt=>z(bt.target.value),placeholder:R==null?void 0:R.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"cta-value",children:R==null?void 0:R.helper}),e.jsx(Ne,{id:"cta-value",value:Q,onChange:bt=>K(bt.target.value),placeholder:R==null?void 0:R.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{id:"cta-color",type:"color",value:X,onChange:bt=>Z(bt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(Ne,{value:X,onChange:bt=>Z(bt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Position"}),e.jsxs(ab,{value:re,onValueChange:bt=>le(bt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"cursor",id:"cta-cursor"}),e.jsxs(he,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"top",id:"cta-top"}),e.jsxs(he,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Id,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"bottom",id:"cta-bottom"}),e.jsxs(he,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Hu,{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:X,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:F||(R==null?void 0:R.defaultText)})})]}),e.jsxs(an,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:ne,disabled:!(R!=null&&R.isForward)&&!Q.trim(),children:"Insert Button"})]})]})}),e.jsx(fs,{open:ie,onOpenChange:ye,children:e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Insert Video Block"})}),e.jsxs(On,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Rn,{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(ts,{value:"library",className:"space-y-3 mt-2",children:[ns?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(es,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!jt||jt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(Jr,{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:jt.map(bt=>{const cs=ce.includes(bt.share_token||"___"),yt=bt.share_token?`https://video.relevelup.com/thumb/${bt.share_token}`:bt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Ns(bt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${cs?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[yt?e.jsx("img",{src:yt,alt:bt.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(Jr,{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(Uo,{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:bt.title||"Untitled"})})]},bt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(Ne,{id:"vid-title-lib",value:Be,onChange:bt=>De(bt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(ts,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(Ne,{id:"vid-url",value:ce,onChange:bt=>ve(bt.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(he,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(Ne,{id:"vid-title",value:Be,onChange:bt=>De(bt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(Ne,{id:"vid-thumb",value:be,onChange:bt=>Ue(bt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(ts,{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(Jr,{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(G,{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(he,{children:"Position"}),e.jsxs(ab,{value:Ae,onValueChange:bt=>He(bt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"cursor",id:"vid-cursor"}),e.jsxs(he,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"top",id:"vid-top"}),e.jsxs(he,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Id,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"bottom",id:"vid-bottom"}),e.jsxs(he,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Hu,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Le&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Preview"}),e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Le,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:bt=>{bt.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(an,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>ye(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:Te,disabled:!ce.trim(),children:"Insert Video"})]})]})}),e.jsx(fs,{open:xe,onOpenChange:et,children:e.jsxs(ms,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Insert Image"})}),e.jsxs(On,{defaultValue:"upload",className:"space-y-3",children:[e.jsxs(Rn,{className:"grid w-full grid-cols-2",children:[e.jsx(Kt,{value:"upload",children:"Upload"}),e.jsx(Kt,{value:"url",children:"From URL"})]}),e.jsxs(ts,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:lt,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:bt=>{var yt;const cs=(yt=bt.target.files)==null?void 0:yt[0];cs&&Xe(cs),bt.target.value=""}}),fe?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:fe,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(G,{type:"button",variant:"ghost",size:"sm",onClick:()=>it(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var bt;return(bt=lt.current)==null?void 0:bt.click()},disabled:Ke,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:Ke?e.jsxs(e.Fragment,{children:[e.jsx(es,{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(da,{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(ts,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"img-url",children:"Image URL"}),e.jsx(Ne,{id:"img-url",value:fe,onChange:bt=>it(bt.target.value),placeholder:"https://..."})]}),fe&&/^https?:\/\//i.test(fe)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:fe,alt:"Preview",className:"w-full max-h-48 object-contain",onError:bt=>{bt.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(he,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(Ne,{id:"img-alt",value:Oe,onChange:bt=>Ye(bt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Size"}),e.jsxs(ab,{value:We,onValueChange:bt=>_e(bt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"full",id:"img-full"}),e.jsx(he,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"half",id:"img-half"}),e.jsx(he,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Position"}),e.jsxs(ab,{value:Re,onValueChange:bt=>tt(bt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"cursor",id:"img-cursor"}),e.jsxs(he,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(qc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"top",id:"img-top"}),e.jsxs(he,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Id,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Hd,{value:"bottom",id:"img-bottom"}),e.jsxs(he,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Hu,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>et(!1),children:"Cancel"}),e.jsx(G,{type:"button",onClick:Je,disabled:!fe.trim()||Ke,children:"Insert Image"})]})]})})]})}function D4s({open:s,onOpenChange:t,initial:r,onSaved:n}){const{user:a,isAdmin:i,isBrokerageManager:l,brokerageId:o}=js(),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(!1),[b,N]=k.useState("private"),[S,T]=k.useState(!1),{data:A}=mt({queryKey:["my-team-leader-info",a==null?void 0:a.id],enabled:!!(a!=null&&a.id)&&s,queryFn:async()=>{const{data:$}=await V.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return $}}),I=(A==null?void 0:A.role)==="team_leader",D=(A==null?void 0:A.team_id)??null;k.useEffect(()=>{s&&(d((r==null?void 0:r.title)??""),m((r==null?void 0:r.description)??""),y((r==null?void 0:r.html_content)??R4s()),w((r==null?void 0:r.is_template)??!1),N((r==null?void 0:r.share_scope)??"private"))},[s,r]);const R=async()=>{if(a){if(!c.trim()){ue.error("Please enter a title");return}if(!x.trim()){ue.error("Newsletter content is empty");return}T(!0);try{const $={user_id:a.id,title:c.trim(),description:h.trim()||null,html_content:x,is_template:v,share_scope:b,shared_team_id:b==="team"?D:null,shared_brokerage_id:b==="brokerage"?o:null};if(b==="team"&&!D){ue.error("You must be a team leader to share with a team"),T(!1);return}if(b==="brokerage"&&!l){ue.error("Only brokerage managers can share to a brokerage"),T(!1);return}if(b==="global"&&!i){ue.error("Only admins can publish global starter templates"),T(!1);return}let F;if(r!=null&&r.id?{error:F}=await V.from("agent_custom_newsletters").update($).eq("id",r.id):{error:F}=await V.from("agent_custom_newsletters").insert($),F)throw F;ue.success(r!=null&&r.id?"Saved":"Newsletter created"),n==null||n(),t(!1)}catch($){ue.error($.message||"Failed to save")}finally{T(!1)}}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(ys,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(gs,{children:r!=null&&r.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(he,{htmlFor:"acn-title",children:"Title *"}),e.jsx(Ne,{id:"acn-title",value:c,onChange:$=>d($.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(Ne,{id:"acn-desc",value:h,onChange:$=>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(_r,{id:"acn-template",checked:v,onCheckedChange:w}),e.jsx(he,{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"})]}),(I||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(he,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(ab,{value:b,onValueChange:$=>N($),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Hd,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(he,{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"})]})]}),I&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Hd,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(he,{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(Hd,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(he,{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(Hd,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(he,{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(he,{className:"mb-2 block",children:"Content"}),e.jsx(jht,{html:x,onChange:y})]})]}),e.jsxs(an,{className:"px-6 py-3 border-t",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs(G,{onClick:R,disabled:S,children:[S?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bl,{className:"h-4 w-4 mr-2"}),r!=null&&r.id?"Save Changes":"Create"]})]})]})})}function R4s(){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 Eh(){const{data:s,isLoading:t}=mt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:a,error:i}=await V.from("gmail_integrations").select("*").maybeSingle();if(i)throw i;return a}}),r=!!(s!=null&&s.is_active),n=(s==null?void 0:s.gmail_email)||null;return{isGmailConnected:r,gmailEmail:n,isLoading:t}}function OB(){var a;const{user:s}=js(),{data:t,isLoading:r}=mt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,h,m,x;const[i,l]=await Promise.all([V.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),V.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())||((h=c==null?void 0:c.email)==null?void 0:h.trim())||s.email||null,display_name:((m=o==null?void 0:o.display_name)==null?void 0:m.trim())||((x=c==null?void 0:c.name)==null?void 0:x.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:r,settings:t}}function xL(){const s=sa();return mt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(r)throw r;return t},enabled:!!s})}function O4s(s){return mt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(r)throw r;return t},enabled:!!s})}function MTe(){const s=Xt(),t=sa();return Ct({mutationFn:async({name:r,color:n})=>{const{data:a,error:i}=await V.from("contact_custom_tags").insert({owner_user_id:t,name:r.trim(),color:n||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function F4s(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("contact_custom_tags").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function B4s(){const s=Xt();return Ct({mutationFn:async({id:t,name:r,color:n})=>{const a={};r!==void 0&&(a.name=r.trim()),n!==void 0&&(a.color=n);const{error:i}=await V.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 Nht(){const s=Xt();return Ct({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await V.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:r});if(n)throw n},onSuccess:(t,{contactId:r})=>{s.invalidateQueries({queryKey:["contact-custom-tags",r]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function z4s(){const s=Xt();return Ct({mutationFn:async({contactId:t,tagId:r})=>{const{error:n}=await V.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",r);if(n)throw n},onSuccess:(t,{contactId:r})=>{s.invalidateQueries({queryKey:["contact-custom-tags",r]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function ITe(){const s=sa();return mt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(r)throw r;return t},enabled:!!s})}function kht(){const{user:s}=js();return mt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function $4s(){const s=Xt(),{user:t}=js();return Ct({mutationFn:async({name:r,filters:n,sort_by:a})=>{const{data:i,error:l}=await V.from("contact_smart_lists").insert({owner_user_id:t.id,name:r,filters:n,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),cn({title:"Smart filter saved"})},onError:r=>{cn({title:"Error saving smart filter",description:r.message,variant:"destructive"})}})}function U4s(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("contact_smart_lists").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),cn({title:"Smart filter deleted"})}})}const cUe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function dUe(s,t,r,n){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:(r==null?void 0:r.name)||"",agent_email:(r==null?void 0:r.email)||"",agent_phone:(r==null?void 0:r.phone)||"",agent_title:(r==null?void 0:r.title)||"",brokerage:n||"",current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(d,h)=>c[h]??`{{${h}}}`)}function q4s(s,t,r,n){const a=t.trim()?`
${cUe(t).replace(/\n/g,"
")}
`:"",i=r.trim()?`
${cUe(r).replace(/\n/g,"
")}
`:"",l=n?`
${n}
`:"";return`${a} ${s} ${i} ${l}`}function V4s(s,t,r){const n=(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 ${r} from your newsletter list.`)}`:"#";return`
${n}${i?" • "+i:""}
${l?`
${l}
`:""}
You're receiving this because ${n} thought you'd find it useful. Unsubscribe
`}const H4s=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function G4s(s,t){const r=[],n=s.trim();if(n.length>0){n.length<10&&r.push("Subject line is very short — most opened subjects are 30-60 characters."),n.length>90&&r.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=n.replace(/[^A-Za-z]/g,""),o=n.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&r.push("Subject is mostly uppercase — this often triggers spam filters."),(n.match(/!/g)||[]).length>=3&&r.push("Too many exclamation marks in the subject.");const d=n.toLowerCase(),h=H4s.filter(m=>d.includes(m));h.length>0&&r.push(`Subject contains spam-trigger words: ${h.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&r.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&r.push("Email is mostly images with little text — many spam filters block these."),r}function LTe({open:s,onOpenChange:t,newsletterId:r,newsletterTitle:n,htmlCode:a}){const{user:i}=js();Eh();const{isReady:l,settings:o}=OB(),c=sa(),{data:d}=mt({queryKey:["agent-profile-for-newsletter-send",i==null?void 0:i.id],enabled:!!i&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!i)return null;const{data:Zs}=await V.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature").eq("id",i.id).maybeSingle();return Zs}}),[h,m]=k.useState("visual"),[x,y]=k.useState("all"),[v,w]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,I]=k.useState(""),[D,R]=k.useState(!0),[$,F]=k.useState([]),[z,Q]=k.useState(null),[K,X]=k.useState(new Set),[Z,re]=k.useState(""),[le,oe]=k.useState(!1),[ne,ie]=k.useState(!1),[ye,ce]=k.useState(!1),[ve,be]=k.useState({sent:0,failed:0,total:0,currentName:""}),[Ue,Be]=k.useState(!0),[De,Ae]=k.useState(!1),[He,Le]=k.useState([]),[Ie,Te]=k.useState(!1),[xe,et]=k.useState(new Set),[fe,it]=k.useState("now"),[Oe,Ye]=k.useState(""),{data:We=[]}=xL(),{data:_e=[]}=ITe(),{data:Re=[]}=kht(),{data:tt=[],isLoading:Ke}=mt({queryKey:["newsletter-send-contacts",c],enabled:!!c&&s,queryFn:async()=>{const Zs=[];let Yr=0;const ss=1e3;for(;;){const{data:ta,error:nn}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",c).not("email","is",null).neq("email","").order("first_name").range(Yr,Yr+ss-1);if(nn)throw nn;if(!ta||ta.length===0||(Zs.push(...ta),ta.length{const{data:Zs}=await V.from("ses_suppressed_emails").select("email");return(Zs||[]).map(Yr=>Yr.email.toLowerCase())}}),{data:lt}=mt({queryKey:["newsletter-brokerage-info",i==null?void 0:i.id],enabled:!!i&&s,staleTime:10*60*1e3,queryFn:async()=>{if(!i)return null;const{data:Zs}=await V.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(Zs!=null&&Zs.brokerage_id))return null;const{data:Yr}=await V.from("brokerages").select("name, city, state").eq("id",Zs.brokerage_id).maybeSingle();return Yr}}),{data:xt}=mt({queryKey:["newsletter-active-lead-site",c],enabled:!!c&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!c)return null;const{data:Zs}=await V.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",c).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return Zs}}),Xe=!!(xt!=null&&xt.mls_provider_id),Je=(xt==null?void 0:xt.mls_agent_id)||(xt==null?void 0:xt.mls_agent_key)||null,{data:jt=[],isLoading:ns}=mt({queryKey:["newsletter-agent-listings",c,Je],enabled:!!c&&!!Je&&Ie,staleTime:60*1e3,queryFn:async()=>{if(!Je)return[];const{data:Zs}=await V.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",Je).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return Zs||[]}}),Ns=k.useMemo(()=>{const Zs=new Set(Ze);return tt.filter(Yr=>Yr.email&&Yr.email.includes("@")&&!Zs.has(Yr.email.toLowerCase()))},[tt,Ze]),Ys=k.useMemo(()=>{if($.length===0)return null;const Zs=new Set;for(const Yr of _e)$.includes(Yr.tag_id)&&Zs.add(Yr.contact_id);return Zs},[_e,$]),rs=k.useMemo(()=>Re.find(Zs=>Zs.id===z)||null,[Re,z]),bt=k.useMemo(()=>{var Zs;if(x==="all")return Ns;if(x==="tags")return Ys?Ns.filter(Yr=>Ys.has(Yr.id)):[];if(x==="smartlists"){if(!rs)return[];const Yr=(((Zs=rs.filters)==null?void 0:Zs.search)||"").toLowerCase().trim();return Yr?Ns.filter(ss=>`${ss.first_name||""} ${ss.last_name||""}`.toLowerCase().includes(Yr)||(ss.email||"").toLowerCase().includes(Yr)):Ns}return Ns.filter(Yr=>K.has(Yr.id))},[x,Ns,Ys,rs,K]),cs=k.useMemo(()=>{if(!Z.trim())return Ns;const Zs=Z.toLowerCase();return Ns.filter(Yr=>`${Yr.first_name||""} ${Yr.last_name||""}`.toLowerCase().includes(Zs))},[Ns,Z]);k.useEffect(()=>{s&&(w(""),N(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),T(`As always, reach out anytime if I can help. Talk soon!`),I(a||""),m("light"),y("all"),F([]),Q(null),X(new Set),re(""),oe(!1),R(!0),Be(!0),Le([]),it("now"),Ye(""),be({sent:0,failed:0,total:0,currentName:""}))},[s,n,a]);const yt=l,is=!!(v.trim()&&yt&&bt.length>0&&!ne),Bs=Zs=>{const Yr=h==="advanced"||h==="visual"?A:a,ss=D&&(d!=null&&d.email_signature)?d.email_signature:null;let ta;return h==="light"?ta=q4s(Yr,b,S,ss):ta=ss?`${Yr}
${ss}
`:Yr,Ue&&(ta+=V4s(d??null,lt??null,Zs.email)),dUe(ta,Zs,d??null,(lt==null?void 0:lt.name)??null)},ps=k.useMemo(()=>Bs({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[h,b,S,A,a,D,d,Ue,lt]),lr=k.useMemo(()=>G4s(v,h==="advanced"||h==="visual"?A:a),[v,h,A,a]),kr=async()=>{Ae(!0),Le([]);try{const Zs=h==="advanced"||h==="visual"?A:a,{data:Yr,error:ss}=await V.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:n,bodyHtml:Zs,currentSubject:v}});if(ss)throw ss;const ta=Yr==null?void 0:Yr.subjects;if(!Array.isArray(ta)||ta.length===0)throw new Error("No subjects returned");Le(ta)}catch(Zs){const Yr=(Zs==null?void 0:Zs.message)||"Failed to generate subjects";Yr.includes("credits exhausted")||Yr.includes("402")?ue.error("AI credits exhausted. Please add credits to your workspace."):Yr.includes("Rate limit")||Yr.includes("429")?ue.error("Rate limit hit — try again in a moment."):ue.error(Yr)}finally{Ae(!1)}},Lr=Zs=>Zs?"$"+Number(Zs).toLocaleString("en-US"):"",qr=()=>{if(xe.size===0){ue.error("Pick at least one listing first.");return}const Zs=jt.filter(hr=>xe.has(hr.listing_key)),Yr=(xt==null?void 0:xt.subdomain_slug)||"",ss=Yr?`https://${Yr}.relevelup.com`:"https://relevelup.com",nn=`

Featured Listings

${Zs.map(hr=>{var st,gt;const Pr=Array.isArray(hr.photos)&&hr.photos.length>0?typeof hr.photos[0]=="string"?hr.photos[0]:((st=hr.photos[0])==null?void 0:st.MediaURL)||((gt=hr.photos[0])==null?void 0:gt.url)||"":"",Qn=`${ss}/listings/${hr.listing_key}`,Gt=hr.bedrooms?`${hr.bedrooms} bd`:"",gr=hr.bathrooms_total?`${hr.bathrooms_total} ba`:"",zt=hr.living_area?`${Number(hr.living_area).toLocaleString()} sqft`:"",Se=[Gt,gr,zt].filter(Boolean).join(" • "),ze=`${hr.address||""}${hr.city?", "+hr.city:""}`;return`
${Pr?`${ze}`:""}
${Lr(hr.list_price)}
${ze}
${Se}
`.trim()}).join(` `)}
`.trim();I(hr=>(hr||a||"")+` `+nn),m("visual"),et(new Set),Te(!1),ue.success(`Added ${Zs.length} listing${Zs.length===1?"":"s"} to your newsletter.`)},Ur=()=>Bs({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}}"),Mr=()=>dUe(v,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},d??null,(lt==null?void 0:lt.name)??null).replace(/__FN__/g,"{{first_name}}").replace(/__LN__/g,"{{last_name}}").replace(/__EM__/g,"{{email}}").replace(/__NAME__/g,"{{name}}").replace(/__PHONE__/g,"{{phone}}").replace(/__ADDR__/g,"{{address}}").replace(/__CITY__/g,"{{city}}").replace(/__STATE__/g,"{{state}}").replace(/__ZIP__/g,"{{zip}}"),Cr=()=>{if(is){if(fe==="later"){if(!Oe){ue.error("Pick a date and time to schedule.");return}const Zs=new Date(Oe).getTime();if(Number.isNaN(Zs)||Zs{if(!(!is||!i)){ce(!1),ie(!0),be({sent:0,failed:0,total:bt.length,currentName:"Preparing campaign…"});try{const Yr=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ss=Ur(),ta=Mr(),nn=fe==="later",{data:hr,error:Pr}=await V.from("email_campaigns").insert({user_id:c||i.id,name:`Newsletter: ${n}`,subject:ta,body_html:ss,from_email:Yr,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:bt.length,status:nn?"scheduled":"draft",scheduled_at:nn?new Date(Oe).toISOString():null}).select("id").single();if(Pr)throw Pr;be(Gt=>({...Gt,currentName:"Adding recipients…"}));const Qn=bt.map(Gt=>({campaign_id:hr.id,contact_id:Gt.id,email:Gt.email,name:[Gt.first_name,Gt.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Gt=0;Gt({...Se,sent:Math.min(Gt+gr.length,Qn.length)}))}if(nn){const{error:Gt}=await V.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:hr.id}});if(Gt)throw Gt;ue.success(`Newsletter scheduled for ${new Date(Oe).toLocaleString()}.`)}else{const{error:Gt}=await V.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:hr.id}});if(Gt)throw Gt;ue.success(`Sending to ${bt.length} contact${bt.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(Zs){console.error("Newsletter send failed:",Zs),ue.error(`Failed to send: ${Zs.message||"Unknown error"}`)}finally{ie(!1)}}},Ln=Zs=>{X(Yr=>{const ss=new Set(Yr);return ss.has(Zs)?ss.delete(Zs):ss.add(Zs),ss})};return e.jsxs(fs,{open:s,onOpenChange:Zs=>!ne&&t(Zs),children:[e.jsxs(ms,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-5 w-5"})," Send Newsletter"]})}),!yt&&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(Oi,{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(G,{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(he,{children:"Subject"}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:kr,disabled:De,title:"Generate subject lines with AI",children:[De?e.jsx(es,{className:"h-3 w-3 animate-spin"}):e.jsx(jr,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(Ne,{value:v,onChange:Zs=>w(Zs.target.value),placeholder:"Newsletter subject"}),He.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:"}),He.map((Zs,Yr)=>e.jsxs("button",{type:"button",onClick:()=>{w(Zs),Le([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(jr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),Zs]},Yr))]}),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}}"})]})]}),lr.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(UR,{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:lr.map((Zs,Yr)=>e.jsx("li",{children:Zs},Yr))})]}),Xe&&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(En,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:"Pick from your live MLS listings and drop them into the email."})]}),e.jsx(G,{type:"button",size:"sm",variant:"outline",onClick:()=>Te(!0),children:"Choose listings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Editing"}),e.jsxs(On,{value:h,onValueChange:Zs=>m(Zs),children:[e.jsxs(Rn,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Kt,{value:"visual",children:[e.jsx(Zx,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Kt,{value:"light",children:[e.jsx(ln,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Kt,{value:"advanced",children:[e.jsx(W1,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(ts,{value:"visual",className:"mt-3",children:e.jsx(jht,{html:A,onChange:I})}),e.jsxs(ts,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(or,{value:b,onChange:Zs=>N(Zs.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(or,{value:S,onChange:Zs=>T(Zs.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(ts,{value:"advanced",className:"mt-3",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(or,{value:A,onChange:Zs=>I(Zs.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:d!=null&&d.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(_r,{checked:D&&!!(d!=null&&d.email_signature),disabled:!(d!=null&&d.email_signature),onCheckedChange:R})]}),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(_r,{checked:Ue,onCheckedChange:Be})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Recipients"}),e.jsxs(On,{value:x,onValueChange:Zs=>y(Zs),children:[e.jsxs(Rn,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Kt,{value:"all",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Kt,{value:"tags",children:[e.jsx(wh,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Kt,{value:"smartlists",children:[e.jsx(jR,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Kt,{value:"individual",children:[e.jsx(Di,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(ts,{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:Ns.length})," contact",Ns.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(ts,{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(Qa,{className:"h-40 rounded-lg border p-2",children:We.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."}):We.map(Zs=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Si,{checked:$.includes(Zs.id),onCheckedChange:Yr=>F(ss=>Yr?[...ss,Zs.id]:ss.filter(ta=>ta!==Zs.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:Zs.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:Zs.name})]},Zs.id))})]}),e.jsxs(ts,{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(Qa,{className:"h-40 rounded-lg border p-2",children:Re.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):Re.map(Zs=>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:z===Zs.id,onChange:()=>Q(Zs.id)}),e.jsx("span",{className:"text-sm",children:Zs.name})]},Zs.id))})]}),e.jsxs(ts,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(Ne,{placeholder:"Search contacts...",value:Z,onChange:Zs=>re(Zs.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[K.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>X(new Set),children:"Clear"})]}),e.jsxs(Qa,{className:"h-48 rounded-lg border p-2",children:[Ke&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!Ke&&cs.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),cs.slice(0,200).map(Zs=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Si,{checked:K.has(Zs.id),onCheckedChange:()=>Ln(Zs.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[Zs.first_name," ",Zs.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Zs.email})]})]},Zs.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(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(In,{className:"h-3 w-3"})," ",bt.length," recipient",bt.length===1?"":"s"]}),yt&&e.jsxs(Ge,{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(he,{children:"Preview"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>oe(Zs=>!Zs),children:le?e.jsxs(e.Fragment,{children:[e.jsx(Xh,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(bn,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),le?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:ps,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)."]})]})]}),ne&&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(es,{className:"h-4 w-4 animate-spin"}),"Sending to ",ve.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[ve.sent+ve.failed," / ",ve.total]})]}),e.jsx(ei,{value:ve.total?(ve.sent+ve.failed)/ve.total*100:0}),ve.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[ve.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(fn,{className:"h-4 w-4"})," When to send"]}),e.jsxs(ab,{value:fe,onValueChange:Zs=>it(Zs),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Hd,{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(Hd,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(tv,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),fe==="later"&&e.jsx(Ne,{type:"datetime-local",value:Oe,onChange:Zs=>Ye(Zs.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(G,{variant:"outline",onClick:()=>t(!1),disabled:ne,children:"Cancel"}),e.jsx(G,{onClick:Cr,disabled:!is,children:ne?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):fe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(tv,{className:"h-4 w-4 mr-1"}),"Schedule for ",bt.length]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4 mr-1"}),"Send to ",bt.length]})})]})]})]})]}),e.jsx(Ko,{open:ye,onOpenChange:ce,children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:fe==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Bo,{children:[fe==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[bt.length," contact",bt.length===1?"":"s"]}),fe==="later"&&Oe?` for ${new Date(Oe).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:Xr,children:fe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(tv,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4 mr-1"}),"Send to ",bt.length]})})]})]})}),e.jsx(fs,{open:Ie,onOpenChange:Te,children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 of your active listings. They'll be added as an email-safe grid linking to your lead site."}),ns&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(es,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!ns&&jt.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No active listings found in your MLS feed."}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:jt.map(Zs=>{var ta,nn;const Yr=xe.has(Zs.listing_key),ss=Array.isArray(Zs.photos)&&Zs.photos.length>0?typeof Zs.photos[0]=="string"?Zs.photos[0]:((ta=Zs.photos[0])==null?void 0:ta.MediaURL)||((nn=Zs.photos[0])==null?void 0:nn.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{et(hr=>{const Pr=new Set(hr);return Pr.has(Zs.listing_key)?Pr.delete(Zs.listing_key):Pr.size<6?Pr.add(Zs.listing_key):ue.error("Max 6 listings per newsletter"),Pr})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Yr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[ss&&e.jsx("img",{src:ss,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:Zs.list_price?`$${Number(Zs.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Zs.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Zs.city,Zs.state?`, ${Zs.state}`:""]})]}),Yr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(In,{className:"h-4 w-4"})})]},Zs.listing_key)})})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>Te(!1),children:"Cancel"}),e.jsxs(G,{onClick:qr,disabled:xe.size===0,children:["Insert ",xe.size>0?xe.size:""," listing",xe.size===1?"":"s"]})]})]})})]})}function W4s(){const{user:s}=js(),t=Xt(),[r,n]=k.useState("starters"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState(null),[h,m]=k.useState(null),{data:x,isLoading:y}=mt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:R,error:$}=await V.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if($)throw $;return R||[]}}),v=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),w=(x==null?void 0:x.filter(R=>R.user_id===(s==null?void 0:s.id)&&!R.is_template))??[],b=(x==null?void 0:x.filter(R=>R.user_id===(s==null?void 0:s.id)&&R.is_template))??[],N=(x==null?void 0:x.filter(R=>R.user_id!==(s==null?void 0:s.id)&&R.is_template&&(R.share_scope==="team"||R.share_scope==="brokerage"||R.share_scope==="global")))??[],S=(x==null?void 0:x.filter(R=>R.share_scope==="global"&&R.is_template))??[],T=r==="starters"?S:r==="mine"?w:r==="templates"?b:N.filter(R=>R.share_scope!=="global"),A=async R=>{if(!s)return;const{error:$}=await V.from("agent_custom_newsletters").insert({user_id:s.id,title:`${R.title} (Copy)`,description:R.description,html_content:R.html_content,is_template:!1,share_scope:"private"});if($){ue.error($.message);return}ue.success('Duplicated to "My Newsletters"'),v(),n("mine")},I=async R=>{const{error:$}=await V.from("agent_custom_newsletters").delete().eq("id",R);if($){ue.error($.message);return}ue.success("Deleted"),m(null),v()},D=R=>R.share_scope==="global"?e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(jr,{className:"h-3 w-3"}),"Starter"]}):R.share_scope==="brokerage"?e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Brokerage"]}):R.share_scope==="team"?e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Ge,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Hc,{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(G,{variant:r==="starters"?"default":"outline",size:"sm",onClick:()=>n("starters"),className:"gap-1.5",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"Starter Templates (",S.length,")"]}),e.jsxs(G,{variant:r==="mine"?"default":"outline",size:"sm",onClick:()=>n("mine"),children:["My Newsletters (",w.length,")"]}),e.jsxs(G,{variant:r==="templates"?"default":"outline",size:"sm",onClick:()=>n("templates"),children:["My Templates (",b.length,")"]}),e.jsxs(G,{variant:r==="shared"?"default":"outline",size:"sm",onClick:()=>n("shared"),children:["Shared with Me (",N.filter(R=>R.share_scope!=="global").length,")"]})]}),e.jsxs(G,{onClick:()=>{o(null),i(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),y&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((R,$)=>e.jsx(Fs,{className:"h-48 w-full"},$))}),r==="starters"&&!y&&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(jr,{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.']})]}),!y&&T.length===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ln,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),r==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),r==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),r==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),r==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!y&&T.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:T.map(R=>{const $=R.user_id===(s==null?void 0:s.id);return e.jsxs(ke,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[R.thumbnail_url?e.jsx("img",{src:R.thumbnail_url,alt:R.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:`
${R.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[R.is_template&&e.jsx(Ge,{className:"bg-primary/90",children:"Template"}),D(R)]})]}),e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:R.title}),R.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:R.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",_s(new Date(R.updated_at||R.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(G,{size:"sm",onClick:()=>d(R),className:"flex-1 min-w-[80px]",children:[e.jsx(en,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),$?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{o(R),i(!0)},children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>A(R),children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>m(R.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}):e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>A(R),children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},R.id)})}),e.jsx(D4s,{open:a,onOpenChange:i,initial:l,onSaved:v}),c&&e.jsx(LTe,{open:!!c,onOpenChange:R=>!R&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Ko,{open:!!h,onOpenChange:R=>!R&&m(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete this newsletter?"}),e.jsx(Bo,{children:"This cannot be undone."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>h&&I(h),children:"Delete"})]})]})})]})}function K4s(){const s=br(),[t,r]=k.useState(""),[n,a]=k.useState("grid"),[i,l]=k.useState(null),{data:o,isLoading:c}=mt({queryKey:["newsletters"],queryFn:async()=>{const{data:I,error:D}=await V.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(D)throw D;return I}}),{data:d}=mt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:I}=await V.from("newsletter_likes").select("newsletter_id");return I||[]}}),{data:h}=mt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:I}=await V.from("newsletter_comments").select("newsletter_id");return I||[]}}),{data:m}=mt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[I,D,R,$]=await Promise.all([V.from("newsletter_canva_links").select("newsletter_id"),V.from("newsletter_pdfs").select("newsletter_id"),V.from("newsletter_videos").select("newsletter_id"),V.from("newsletter_drive_links").select("newsletter_id")]);return{canva:I.data||[],pdfs:D.data||[],videos:R.data||[],drives:$.data||[]}}}),x=I=>(d==null?void 0:d.filter(D=>D.newsletter_id===I).length)||0,y=I=>(h==null?void 0:h.filter(D=>D.newsletter_id===I).length)||0,v=I=>{var D;return((D=m==null?void 0:m.canva)==null?void 0:D.filter(R=>R.newsletter_id===I).length)||0},w=I=>{var D;return((D=m==null?void 0:m.pdfs)==null?void 0:D.filter(R=>R.newsletter_id===I).length)||0},b=I=>{var D;return((D=m==null?void 0:m.videos)==null?void 0:D.filter(R=>R.newsletter_id===I).length)||0},N=I=>{var D;return((D=m==null?void 0:m.drives)==null?void 0:D.filter(R=>R.newsletter_id===I).length)||0},S=I=>v(I)+w(I)+b(I)+N(I),T=o==null?void 0:o.filter(I=>{var D;return I.title.toLowerCase().includes(t.toLowerCase())||((D=I.description)==null?void 0:D.toLowerCase().includes(t.toLowerCase()))}),A=I=>{s(`/newsletters/${I}`)};return e.jsx(ws,{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(On,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Rn,{children:[e.jsx(Kt,{value:"custom",children:"Build & Send"}),e.jsx(Kt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(ts,{value:"custom",className:"mt-2",children:e.jsx(W4s,{})}),e.jsxs(ts,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search newsletters...",value:t,onChange:I=>r(I.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>r(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(G,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(em,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(T==null?void 0:T.length)||0," item",(T==null?void 0:T.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((I,D)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-0",children:[e.jsx(Fs,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(Fs,{className:"h-5 w-3/4"}),e.jsx(Fs,{className:"h-4 w-full"})]})]})},D))}),!c&&(T==null?void 0:T.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ln,{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(G,{variant:"outline",onClick:()=>r(""),children:"Clear Search"})]}),!c&&T&&T.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-3",children:T.map(I=>{const D=S(I.id),R=v(I.id),$=w(I.id),F=b(I.id);return n==="grid"?e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(I.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:I.preview_image_url?e.jsx("img",{src:I.preview_image_url,alt:I.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(ln,{className:"h-16 w-16"})})}),e.jsxs(Pe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:I.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(on,{className:"h-3 w-3"}),_s(new Date(I.publish_date),"MMM d, yyyy")]})]}),I.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:I.description.replace(/<[^>]*>/g,"")}),D>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[R>0&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(fl,{className:"h-3 w-3"})," ",R," Template",R>1?"s":""]}),$>0&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Ya,{className:"h-3 w-3"})," ",$," PDF",$>1?"s":""]}),F>0&&e.jsxs(Ge,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Uo,{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(jh,{className:"h-3 w-3"})," ",x(I.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3 w-3"})," ",y(I.id)]})]}),I.html_code&&e.jsxs(G,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(I)},children:[e.jsx(en,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},I.id):e.jsx(ke,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(I.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:I.preview_image_url?e.jsx("img",{src:I.preview_image_url,alt:I.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(ln,{className:"h-10 w-10"})})}),e.jsxs(Pe,{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:I.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(on,{className:"h-3 w-3"}),_s(new Date(I.publish_date),"MMM d, yyyy")]})]}),I.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:I.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[D>0&&e.jsxs("span",{children:[D," resource",D>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jh,{className:"h-3 w-3"})," ",x(I.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3 w-3"})," ",y(I.id)]})]})]}),I.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(G,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(I)},children:[e.jsx(en,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},I.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(LTe,{open:!!i,onOpenChange:I=>!I&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function Y4s({rows:s}){if(!s||s.length===0)return null;const t=s.filter(r=>r.columns.some(n=>n.title||n.description||n.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((r,n)=>{const a=r.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(ke,{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(Pe,{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))},n)})})}function Z4s(){const{id:s}=Ki(),t=br(),{user:r}=js(),{toast:n}=Ma(),a=Xt(),{trackEngagement:i}=GI(),[l,o]=k.useState(""),[c,d]=k.useState(!1),{data:h,isLoading:m}=mt({queryKey:["newsletter",s],queryFn:async()=>{const{data:R,error:$}=await V.from("newsletter_content").select("*").eq("id",s).single();if($)throw $;return R},enabled:!!s});k.useEffect(()=>{h&&i("newsletter",h.id,h.title,"view")},[h==null?void 0:h.id]);const{data:x}=mt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:y}=mt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:v}=mt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:w}=mt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return R||[]},enabled:!!s}),{data:b}=mt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_likes").select("*").eq("newsletter_id",s);return R||[]},enabled:!!s}),{data:N}=mt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:R}=await V.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return R||[]},enabled:!!s}),S=b==null?void 0:b.some(R=>R.user_id===(r==null?void 0:r.id)),T=Ct({mutationFn:async()=>{S?await V.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",r==null?void 0:r.id):await V.from("newsletter_likes").insert({newsletter_id:s,user_id:r==null?void 0:r.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=Ct({mutationFn:async R=>{const{error:$}=await V.from("newsletter_comments").insert({newsletter_id:s,user_id:r==null?void 0:r.id,content:R});if($)throw $},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),n({title:"Comment added"})}}),I=Ct({mutationFn:async R=>{const{error:$}=await V.from("newsletter_comments").delete().eq("id",R);if($)throw $},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),n({title:"Comment deleted"})}}),D=R=>{if(R.includes("player.mediadelivery.net")||R.includes("iframe.mediadelivery.net")){const $=R.match(/embed\/(\d+)\/([a-f0-9-]+)/);if($)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${$[1]}/${$[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(R.includes("youtube.com")||R.includes("youtu.be")){const $=R.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if($)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${$[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:R,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Uo,{className:"h-4 w-4"})," Watch Video"]})};return m?e.jsx(ws,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{className:"h-8 w-32"}),e.jsx(Fs,{className:"h-64 w-full"}),e.jsx(Fs,{className:"h-32 w-full"})]})}):h?e.jsx(ws,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(ka,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),h.preview_image_url&&e.jsx("img",{src:h.preview_image_url,alt:h.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:h.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:_s(new Date(h.publish_date),"MMMM d, yyyy")})]}),h.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:h.description}}),e.jsx(Y4s,{rows:h.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(ZI,{resourceType:"newsletter",resourceId:h.id,resourceTitle:h.title}),e.jsxs(G,{variant:S?"default":"outline",size:"sm",onClick:()=>T.mutate(),children:[e.jsx(ci,{className:`h-4 w-4 mr-1 ${S?"fill-current":""}`}),(b==null?void 0:b.length)||0," ",(b==null?void 0:b.length)===1?"Like":"Likes"]}),h.html_code&&e.jsxs(G,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(en,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),h.html_code&&e.jsx(LTe,{open:c,onOpenChange:d,newsletterId:h.id,newsletterTitle:h.title,htmlCode:h.html_code}),w&&w.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Pe,{className:"space-y-2",children:w.map(R=>e.jsxs("a",{href:R.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.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:R.title}),e.jsx(Qr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},R.id))})]}),x&&x.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Pe,{className:"space-y-2",children:x.map(R=>e.jsxs("a",{href:R.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Qr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:R.title})]},R.id))})]}),y&&y.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Pe,{className:"space-y-2",children:y.map(R=>e.jsxs("a",{href:R.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",h.id,h.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(ln,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:R.name}),e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground"})]},R.id))})]}),v&&v.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Videos"})}),e.jsx(Pe,{className:"space-y-6",children:v.map(R=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:R.title}),D(R.video_url)]},R.id))})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-lg",children:["Comments (",(N==null?void 0:N.length)||0,")"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(or,{placeholder:"Write a comment...",value:l,onChange:R=>o(R.target.value),className:"flex-1"}),e.jsx(G,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(en,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:N==null?void 0:N.map(R=>{var $,F,z;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Nn,{className:"h-8 w-8",children:e.jsx(kn,{children:((F=($=R.profiles)==null?void 0:$.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=R.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:_s(new Date(R.created_at),"MMM d, yyyy")}),R.user_id===(r==null?void 0:r.id)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>I.mutate(R.id),children:e.jsx(yr,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:R.content})]})]},R.id)})})]})]})]})}):e.jsx(ws,{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(G,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function X4s({rows:s,onChange:t}){const[r,n]=k.useState(null),a=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},i=d=>{t(s.filter((h,m)=>m!==d))},l=(d,h,m,x)=>{const y=[...s];y[d]={...y[d],columns:y[d].columns.map((v,w)=>w===h?{...v,[m]:x}:v)},t(y)},o=async(d,h,m)=>{var v;const x=(v=m.target.files)==null?void 0:v[0];if(!x)return;const y=`${d}-${h}`;n(y);try{const w=`content-blocks/${Date.now()}-${x.name}`,{error:b}=await V.storage.from("newsletter-content").upload(w,x);if(!b){const{data:N}=V.storage.from("newsletter-content").getPublicUrl(w);l(d,h,"image_url",N.publicUrl)}}finally{n(null)}},c=(d,h)=>{l(d,h,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:a,children:[e.jsx($s,{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((d,h)=>e.jsxs(ke,{className:"relative",children:[e.jsx(G,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>i(h),children:e.jsx(vr,{className:"h-4 w-4"})}),e.jsxs(Pe,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(vu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",h+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:d.columns.map((m,x)=>{const y=`${h}-${x}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",x+1]}),m.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:m.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(G,{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:()=>c(h,x),children:e.jsx(vr,{className:"h-3 w-3"})})]}):e.jsxs("div",{children:[e.jsx(Ne,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${y}`,onChange:v=>o(h,x,v)}),e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"w-full text-xs h-8",disabled:r===y,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${y}`,className:"cursor-pointer",children:r===y?"Uploading...":e.jsxs(e.Fragment,{children:[e.jsx(ml,{className:"h-3 w-3 mr-1"})," Image"]})})})]}),e.jsx(Ne,{placeholder:"Title",value:m.title,onChange:v=>l(h,x,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(or,{placeholder:"Description",value:m.description,onChange:v=>l(h,x,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},x)})})]})]},h))]})}function Q4s(){const{toast:s}=Ma(),t=Xt(),[r,n]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState({title:"",description:"",publish_date:_s(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=k.useState(null),[h,m]=k.useState(null),[x,y]=k.useState([]),[v,w]=k.useState([]),[b,N]=k.useState([]),[S,T]=k.useState([]),[A,I]=k.useState([]),[D,R]=k.useState(""),[$,F]=k.useState([]),[z,Q]=k.useState(!1),{data:K,isLoading:X}=mt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Ae,error:He}=await V.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(He)throw He;return Ae}}),Z=Ct({mutationFn:async Ae=>{const{data:He,error:Le}=await V.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(Le)throw Le;return He},onSuccess:async Ae=>{await oe(Ae.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Ae.is_published&&nes(Ae.title,Ae.id),ye()},onError:Ae=>{s({title:"Error creating newsletter",description:Ae.message,variant:"destructive"})}}),re=Ct({mutationFn:async Ae=>{const{error:He}=await V.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(He)throw He;return Ae.id},onSuccess:async Ae=>{await oe(Ae),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ye()},onError:Ae=>{s({title:"Error updating newsletter",description:Ae.message,variant:"destructive"})}}),le=Ct({mutationFn:async Ae=>{const{error:He}=await V.from("newsletter_content").delete().eq("id",Ae);if(He)throw He},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Ae=>{s({title:"Error deleting newsletter",description:Ae.message,variant:"destructive"})}}),oe=async Ae=>{await V.from("newsletter_drive_links").delete().eq("newsletter_id",Ae),await V.from("newsletter_pdfs").delete().eq("newsletter_id",Ae),await V.from("newsletter_videos").delete().eq("newsletter_id",Ae),await V.from("newsletter_canva_links").delete().eq("newsletter_id",Ae);for(const He of $){const Le=`${Ae}/${Date.now()}-${He.file.name}`,{error:Ie}=await V.storage.from("newsletter-content").upload(Le,He.file);if(!Ie){const{data:Te}=V.storage.from("newsletter-content").getPublicUrl(Le);v.push({name:He.name,file_url:Te.publicUrl,file_size:He.file.size,sort_order:v.length})}}x.length>0&&await V.from("newsletter_drive_links").insert(x.map((He,Le)=>({newsletter_id:Ae,title:He.title,drive_url:He.drive_url,sort_order:Le}))),v.length>0&&await V.from("newsletter_pdfs").insert(v.map((He,Le)=>({newsletter_id:Ae,name:He.name,file_url:He.file_url,file_size:He.file_size||null,sort_order:Le}))),b.length>0&&await V.from("newsletter_videos").insert(b.map((He,Le)=>({newsletter_id:Ae,title:He.title,video_url:He.video_url,sort_order:Le}))),S.length>0&&await V.from("newsletter_canva_links").insert(S.map((He,Le)=>({newsletter_id:Ae,title:He.title,canva_share_link:He.canva_share_link,sort_order:Le})))},ne=async Ae=>{i(Ae),o({title:Ae.title,description:Ae.description||"",publish_date:_s(new Date(Ae.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Ae.is_published}),m(Ae.preview_image_url),I(Ae.content_blocks||[]),R(Ae.html_code||"");const[He,Le,Ie,Te]=await Promise.all([V.from("newsletter_drive_links").select("*").eq("newsletter_id",Ae.id).order("sort_order"),V.from("newsletter_pdfs").select("*").eq("newsletter_id",Ae.id).order("sort_order"),V.from("newsletter_videos").select("*").eq("newsletter_id",Ae.id).order("sort_order"),V.from("newsletter_canva_links").select("*").eq("newsletter_id",Ae.id).order("sort_order")]);y(He.data||[]),w(Le.data||[]),N(Ie.data||[]),T(Te.data||[]),F([]),n(!0)},ie=async Ae=>{const[He,Le,Ie,Te]=await Promise.all([V.from("newsletter_drive_links").select("*").eq("newsletter_id",Ae.id).order("sort_order"),V.from("newsletter_pdfs").select("*").eq("newsletter_id",Ae.id).order("sort_order"),V.from("newsletter_videos").select("*").eq("newsletter_id",Ae.id).order("sort_order"),V.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:_s(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),m(Ae.preview_image_url),I(Ae.content_blocks||[]),R(Ae.html_code||""),y((He.data||[]).map(({id:xe,...et})=>et)),w((Le.data||[]).map(({id:xe,...et})=>et)),N((Ie.data||[]).map(({id:xe,...et})=>et)),T((Te.data||[]).map(({id:xe,...et})=>et)),F([]),n(!0)},ye=()=>{n(!1),i(null),o({title:"",description:"",publish_date:_s(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),m(null),y([]),w([]),N([]),T([]),I([]),R(""),F([])},ce=async Ae=>{var Le;const He=(Le=Ae.target.files)==null?void 0:Le[0];He&&(d(He),m(URL.createObjectURL(He)))},ve=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}Q(!0);let Ae=h;if(c){const He=`previews/${Date.now()}-${c.name}`,{error:Le}=await V.storage.from("newsletter-content").upload(He,c);if(!Le){const{data:Ie}=V.storage.from("newsletter-content").getPublicUrl(He);Ae=Ie.publicUrl}}a?re.mutate({id:a.id,...l,preview_image_url:Ae,content_blocks:A,html_code:D||null}):Z.mutate({...l,preview_image_url:Ae,content_blocks:A,html_code:D||null}),Q(!1)},be=()=>y([...x,{title:"",drive_url:"",sort_order:x.length}]),Ue=()=>N([...b,{title:"",video_url:"",sort_order:b.length}]),Be=()=>T([...S,{title:"",canva_share_link:"",sort_order:S.length}]),De=Ae=>{const He=Ae.target.files;if(!He)return;const Le=Array.from(He).map(Ie=>({file:Ie,name:Ie.name.replace(/\.[^/.]+$/,"")}));F([...$,...Le])};return e.jsx(ws,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(K==null?void 0:K.length)||0})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(K==null?void 0:K.filter(Ae=>Ae.is_published).length)||0})})]})]}),e.jsxs(fs,{open:r,onOpenChange:Ae=>!Ae&&ye(),children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{onClick:()=>n(!0),children:[e.jsx($s,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(ms,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{children:"Title *"}),e.jsx(Ne,{value:l.title,onChange:Ae=>o({...l,title:Ae.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Publish Date"}),e.jsx(Ne,{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(he,{children:"Description"}),e.jsx(Uy,{content:l.description,onChange:Ae=>o({...l,description:Ae}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:h,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx(G,{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),m(null)},children:e.jsx(vr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(Ne,{type:"file",accept:"image/*",onChange:ce,className:"hidden",id:"preview-upload"}),e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(da,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{checked:l.is_published,onCheckedChange:Ae=>o({...l,is_published:Ae})}),e.jsx(he,{children:"Published"})]}),e.jsx(X4s,{rows:A,onChange:I}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{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:D,onChange:Ae=>R(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(he,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:Be,children:[e.jsx($s,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),S.map((Ae,He)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ne,{placeholder:"Link title",value:Ae.title,onChange:Le=>{const Ie=[...S];Ie[He].title=Le.target.value,T(Ie)},className:"w-1/3"}),e.jsx(Ne,{placeholder:"Canva share link",value:Ae.canva_share_link,onChange:Le=>{const Ie=[...S];Ie[He].canva_share_link=Le.target.value,T(Ie)},className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>T(S.filter((Le,Ie)=>Ie!==He)),children:e.jsx(vr,{className:"h-4 w-4"})})]},He))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:be,children:[e.jsx($s,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),x.map((Ae,He)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ne,{placeholder:"Link title",value:Ae.title,onChange:Le=>{const Ie=[...x];Ie[He].title=Le.target.value,y(Ie)},className:"w-1/3"}),e.jsx(Ne,{placeholder:"Google Drive URL",value:Ae.drive_url,onChange:Le=>{const Ie=[...x];Ie[He].drive_url=Le.target.value,y(Ie)},className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>y(x.filter((Le,Ie)=>Ie!==He)),children:e.jsx(vr,{className:"h-4 w-4"})})]},He))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(Ne,{type:"file",accept:".pdf",multiple:!0,onChange:De,className:"hidden",id:"pdf-upload"}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(da,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),v.map((Ae,He)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Ae.name}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>w(v.filter((Le,Ie)=>Ie!==He)),children:e.jsx(vr,{className:"h-4 w-4"})})]},`existing-${He}`)),$.map((Ae,He)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:Ae.name,onChange:Le=>{const Ie=[...$];Ie[He].name=Le.target.value,F(Ie)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>F($.filter((Le,Ie)=>Ie!==He)),children:e.jsx(vr,{className:"h-4 w-4"})})]},`pending-${He}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:Ue,children:[e.jsx($s,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),b.map((Ae,He)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(Ne,{placeholder:"Video title",value:Ae.title,onChange:Le=>{const Ie=[...b];Ie[He].title=Le.target.value,N(Ie)},className:"w-1/3"}),e.jsx(Ne,{placeholder:"Video URL",value:Ae.video_url,onChange:Le=>{const Ie=[...b];Ie[He].video_url=Le.target.value,N(Ie)},className:"flex-1"}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>N(b.filter((Le,Ie)=>Ie!==He)),children:e.jsx(vr,{className:"h-4 w-4"})})]},He))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(G,{variant:"outline",onClick:ye,children:"Cancel"}),e.jsx(G,{onClick:ve,disabled:z||Z.isPending||re.isPending,children:z?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:X?e.jsx(Ds,{children:e.jsx(dt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(K==null?void 0:K.length)===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):K==null?void 0:K.map(Ae=>e.jsxs(Ds,{children:[e.jsx(dt,{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(ln,{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(dt,{children:_s(new Date(Ae.publish_date),"MMM d, yyyy")}),e.jsx(dt,{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(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ne(Ae),title:"Edit",children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>ie(Ae),title:"Duplicate",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&le.mutate(Ae.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},Ae.id))})]})})})]})})}const uUe={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 J4s(){const{user:s}=js(),{toast:t}=Ma(),r=br(),n=Xt(),[a,i]=k.useState(""),[l,o]=k.useState("popular"),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(!1),{data:b=[],isLoading:N}=mt({queryKey:["wishlist-items",l,v],queryFn:async()=>{let D=V.from("wishlist_items").select("*");v&&s&&(D=D.eq("user_id",s.id)),l==="latest"?D=D.order("created_at",{ascending:!1}):l==="popular"?D=D.order("vote_count",{ascending:!1}):l==="trending"&&(D=D.order("vote_count",{ascending:!1}));const{data:R,error:$}=await D;if($)throw $;const F=[...new Set((R==null?void 0:R.map(le=>le.user_id))||[])],{data:z}=await V.from("profiles").select("id, name").in("id",F),Q=new Map((z==null?void 0:z.map(le=>[le.id,le]))||[]);let K=[];if(s){const{data:le}=await V.from("wishlist_votes").select("item_id").eq("user_id",s.id);K=(le==null?void 0:le.map(oe=>oe.item_id))||[]}const X=(R==null?void 0:R.map(le=>le.id))||[],{data:Z}=await V.from("wishlist_comments").select("item_id").in("item_id",X),re=new Map;return Z==null||Z.forEach(le=>{re.set(le.item_id,(re.get(le.item_id)||0)+1)}),R==null?void 0:R.map(le=>{const oe=Q.get(le.user_id),ne=(oe==null?void 0:oe.name)||"Unknown";return{...le,user_name:ne,user_initials:ne.split(" ").map(ie=>ie[0]).join("").toUpperCase().slice(0,2),has_voted:K.includes(le.id),comment_count:re.get(le.id)||0}})}}),S=Ct({mutationFn:async({title:D,description:R})=>{const{error:$}=await V.from("wishlist_items").insert({user_id:s.id,title:D,description:R});if($)throw $},onSuccess:()=>{n.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),m(""),y(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),T=Ct({mutationFn:async({itemId:D,hasVoted:R})=>{if(R){const{error:$}=await V.from("wishlist_votes").delete().eq("item_id",D).eq("user_id",s.id);if($)throw $;return{itemId:D,wasAdded:!1}}else{const{error:$}=await V.from("wishlist_votes").insert({item_id:D,user_id:s.id});if($)throw $;return{itemId:D,wasAdded:!0}}},onSuccess:async D=>{if(n.invalidateQueries({queryKey:["wishlist-items"]}),D!=null&&D.wasAdded){const R=b.find(F=>F.id===D.itemId),$=((R==null?void 0:R.vote_count)||0)+1;V.functions.invoke("wishlist-notify",{body:{itemId:D.itemId,voteCount:$}}).catch(console.error)}},onError:D=>{t({title:"Error",description:D.message,variant:"destructive"})}}),A=b.filter(D=>D.title.toLowerCase().includes(a.toLowerCase())||D.description.toLowerCase().includes(a.toLowerCase())),I=()=>{if(!h.trim()||!x.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}S.mutate({title:h.trim(),description:x.trim()})};return e.jsx(ws,{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(sj,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold",children:"Wishlist"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Share ideas and vote on what we build next"})]})]}),e.jsxs(fs,{open:c,onOpenChange:d,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",placeholder:"Give your idea a clear title...",value:h,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:x,onChange:D=>y(D.target.value),rows:4})]}),e.jsx(G,{onClick:I,className:"w-full",disabled:S.isPending,children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(es,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search ideas...",value:a,onChange:D=>i(D.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(On,{value:l,onValueChange:D=>o(D),children:e.jsxs(Rn,{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(G,{variant:v?"default":"outline",size:"sm",onClick:()=>w(!v),children:v?"Show All Ideas":"My Ideas"})}),N?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(es,{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(sj,{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(G,{onClick:()=>d(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:A.map(D=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>r(`/wishlist/${D.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:R=>{R.stopPropagation(),T.mutate({itemId:D.id,hasVoted:D.has_voted||!1})},className:It("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",D.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Id,{className:It("h-4 w-4",D.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:D.vote_count})]}),e.jsx(Nn,{className:"h-10 w-10 bg-primary/20",children:e.jsx(kn,{className:"bg-primary/20 text-primary text-sm font-medium",children:D.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:D.title}),e.jsx(Ge,{className:It("text-xs",uUe[D.status].color),children:uUe[D.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:D.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:D.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(D.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(xi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:D.comment_count})]})]})},D.id))})]})})}const hUe={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 e3s(){const{itemId:s}=Ki(),t=br(),{user:r}=js(),{toast:n}=Ma(),a=Xt(),[i,l]=k.useState(""),{data:o=!1}=mt({queryKey:["user-is-admin",r==null?void 0:r.id],queryFn:async()=>{if(!r)return!1;const{data:b,error:N}=await V.from("user_roles").select("role").eq("user_id",r.id).eq("role","admin").maybeSingle();return!N&&!!b},enabled:!!r}),{data:c,isLoading:d}=mt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:b,error:N}=await V.from("wishlist_items").select("*").eq("id",s).single();if(N)throw N;const{data:S}=await V.from("profiles").select("name").eq("id",b.user_id).single();let T=!1;if(r){const{data:A}=await V.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",r.id).maybeSingle();T=!!A}return{...b,user_name:(S==null?void 0:S.name)||"Unknown",user_initials:((S==null?void 0:S.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:T}}}),{data:h=[],isLoading:m}=mt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:b,error:N}=await V.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(N)throw N;const S=[...new Set((b==null?void 0:b.map(I=>I.user_id))||[])],{data:T}=await V.from("profiles").select("id, name").in("id",S),A=new Map((T==null?void 0:T.map(I=>[I.id,I]))||[]);return b==null?void 0:b.map(I=>{const D=A.get(I.user_id),R=(D==null?void 0:D.name)||"Unknown";return{...I,user_name:R,user_initials:R.split(" ").map($=>$[0]).join("").toUpperCase().slice(0,2)}})}}),x=Ct({mutationFn:async b=>{if(b){const{error:N}=await V.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",r.id);if(N)throw N;return{wasAdded:!1}}else{const{error:N}=await V.from("wishlist_votes").insert({item_id:s,user_id:r.id});if(N)throw N;return{wasAdded:!0}}},onSuccess:async b=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),b!=null&&b.wasAdded&&c){const N=(c.vote_count||0)+1;V.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:N}}).catch(console.error)}},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),y=Ct({mutationFn:async b=>{const{error:N}=await V.from("wishlist_comments").insert({item_id:s,user_id:r.id,content:b});if(N)throw N},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),n({title:"Comment added!"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),v=Ct({mutationFn:async b=>{const{error:N}=await V.from("wishlist_comments").delete().eq("id",b);if(N)throw N},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),n({title:"Comment deleted"})},onError:b=>{n({title:"Error",description:b.message,variant:"destructive"})}}),w=()=>{i.trim()&&y.mutate(i.trim())};return d?e.jsx(ws,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Fs,{className:"h-8 w-32 mb-6"}),e.jsx(Fs,{className:"h-48 w-full mb-6"}),e.jsx(Fs,{className:"h-32 w-full"})]})}):c?e.jsx(ws,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),e.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:()=>x.mutate(c.has_voted),className:It("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(Id,{className:It("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(Ge,{className:It("text-xs",hUe[c.status].color),children:hUe[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(Nn,{className:"h-6 w-6",children:e.jsx(kn,{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 (",h.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(Bue,{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(G,{onClick:w,disabled:!i.trim()||y.isPending,size:"icon",className:"h-auto",children:y.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"})})]}),m?e.jsx("div",{className:"space-y-4",children:[1,2].map(b=>e.jsx(Fs,{className:"h-20 w-full"},b))}):h.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:h.map(b=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Nn,{className:"h-8 w-8",children:e.jsx(kn,{className:"bg-primary/20 text-primary text-xs",children:b.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:b.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(b.created_at).toLocaleDateString()})]}),e.jsx(h5e,{content:b.content,className:"text-sm text-foreground"})]}),(r==null?void 0:r.id)===b.user_id&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>v.mutate(b.id),children:e.jsx(yr,{className:"h-4 w-4"})})]},b.id))})]})]})}):e.jsx(ws,{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(G,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const mUe={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"}},fUe=["open","under_review","planned","in_progress","launched","declined"];function t3s(){const{toast:s}=Ma(),t=br(),r=Xt(),[n,a]=k.useState(""),[i,l]=k.useState("all"),[o,c]=k.useState(!1),[d,h]=k.useState(null),{data:m=[],isLoading:x}=mt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:N,error:S}=await V.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(S)throw S;const T=[...new Set((N==null?void 0:N.map(F=>F.user_id))||[])],{data:A}=await V.from("profiles").select("id, name, email").in("id",T),I=new Map((A==null?void 0:A.map(F=>[F.id,F]))||[]),D=(N==null?void 0:N.map(F=>F.id))||[],{data:R}=await V.from("wishlist_comments").select("item_id").in("item_id",D),$=new Map;return R==null||R.forEach(F=>{$.set(F.item_id,($.get(F.item_id)||0)+1)}),N==null?void 0:N.map(F=>{const z=I.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:$.get(F.id)||0}})}}),y=Ct({mutationFn:async({itemId:N,status:S})=>{const{error:T}=await V.from("wishlist_items").update({status:S}).eq("id",N);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:N=>{s({title:"Error",description:N.message,variant:"destructive"})}}),v=Ct({mutationFn:async N=>{const{error:S}=await V.from("wishlist_items").delete().eq("id",N);if(S)throw S},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),h(null),s({title:"Item deleted!"})},onError:N=>{s({title:"Error",description:N.message,variant:"destructive"})}}),w=m.filter(N=>{const S=N.title.toLowerCase().includes(n.toLowerCase())||N.description.toLowerCase().includes(n.toLowerCase())||N.user_name.toLowerCase().includes(n.toLowerCase()),T=i==="all"||N.status===i;return S&&T}),b={total:m.length,open:m.filter(N=>N.status==="open").length,inProgress:m.filter(N=>N.status==="in_progress").length,launched:m.filter(N=>N.status==="launched").length,highVotes:m.filter(N=>N.vote_count>=10).length};return e.jsx(ws,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),e.jsx("p",{className:"text-2xl font-bold",children:b.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:b.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:b.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:b.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:b.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search ideas, users...",value:n,onChange:N=>a(N.target.value),className:"pl-10"})]}),e.jsxs(Is,{value:i,onValueChange:N=>l(N),children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"Filter by status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Statuses"}),fUe.map(N=>e.jsx(ct,{value:N,children:mUe[N].label},N))]})]})]}),x?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(N=>e.jsx(Fs,{className:"h-16 w-full"},N))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[60px]",children:"Votes"}),e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Nt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx($n,{children:w.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):w.map(N=>e.jsxs(Ds,{className:It(N.vote_count>=10&&"bg-primary/5"),children:[e.jsx(dt,{children:e.jsx(Ge,{variant:N.vote_count>=10?"default":"secondary",children:N.vote_count})}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:N.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:N.description})]})}),e.jsx(dt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:N.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N.user_email})]})}),e.jsx(dt,{className:"hidden sm:table-cell",children:N.comment_count}),e.jsx(dt,{children:e.jsxs(Is,{value:N.status,onValueChange:S=>y.mutate({itemId:N.id,status:S}),children:[e.jsx(As,{className:"w-[140px] h-8",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:fUe.map(S=>e.jsx(ct,{value:S,children:mUe[S].label},S))})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${N.id}`,"_blank"),children:e.jsx(Qr,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{h(N.id),c(!0)},children:e.jsx(yr,{className:"h-4 w-4"})})]})})]},N.id))})]})}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{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(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:()=>d&&v.mutate(d),disabled:v.isPending,children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function s3s(){const{user:s}=js(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState(!1),[m,x]=k.useState(null),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[I,D]=k.useState(""),[R,$]=k.useState(!1),[F,z]=k.useState(""),[Q,K]=k.useState("once"),[X,Z]=k.useState([]),[re,le]=k.useState([]),[oe,ne]=k.useState(!1),[ie,ye]=k.useState(!1),[ce,ve]=k.useState([]),[be,Ue]=k.useState({total:0,dismissed:0});k.useEffect(()=>{Be()},[]);const Be=async()=>{const{data:Ze,error:lt}=await V.from("levelup_briefs").select("*").order("created_at",{ascending:!1});lt?(ue.error("Failed to fetch briefs"),console.error(lt)):r(Ze||[]),a(!1)},De=()=>{v(""),b(""),S(""),A(""),D(""),$(!1),z(new Date().toISOString().slice(0,16)),K("once"),Z([]),le([]),c(null)},Ae=()=>{De(),l(!0)},He=async Ze=>{c(Ze),v(Ze.title),b(Ze.description||""),S(Ze.video_url||""),A(Ze.graphic_url||""),D(Ze.graphic_link_url||""),$(Ze.is_published),z(Ze.publish_date.slice(0,16)),K(Ze.show_frequency);const{data:lt}=await V.from("levelup_brief_links").select("*").eq("brief_id",Ze.id).order("sort_order");Z((lt==null?void 0:lt.map(Xe=>({title:Xe.title,url:Xe.url})))||[]);const{data:xt}=await V.from("levelup_brief_polls").select("*").eq("brief_id",Ze.id).order("sort_order");if(xt){const Xe=[];for(const Je of xt){const{data:jt}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",Je.id).order("sort_order");Xe.push({question:Je.question,poll_type:Je.poll_type,options:(jt==null?void 0:jt.map(ns=>ns.option_text))||[]})}le(Xe)}l(!0)},Le=async Ze=>{var xt;const lt=(xt=Ze.target.files)==null?void 0:xt[0];if(lt){ne(!0);try{const Xe=await V.functions.invoke("bunny-upload",{body:{action:"create",title:lt.name.replace(/\.[^/.]+$/,"")}});if(Xe.error)throw Xe.error;const{videoId:Je,libraryId:jt}=Xe.data,ns=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Je}});if(ns.error)throw ns.error;const{uploadUrl:Ns,apiKey:Ys}=ns.data,rs=new XMLHttpRequest;await new Promise((cs,yt)=>{rs.upload.addEventListener("progress",is=>{if(is.lengthComputable){const Bs=Math.round(is.loaded/is.total*100);console.log("Upload progress:",Bs)}}),rs.addEventListener("load",()=>{rs.status>=200&&rs.status<300?cs():yt(new Error(`Upload failed with status ${rs.status}`))}),rs.addEventListener("error",()=>yt(new Error("Upload failed"))),rs.open("PUT",Ns),rs.setRequestHeader("AccessKey",Ys),rs.send(lt)});const bt=`https://player.mediadelivery.net/embed/${jt}/${Je}`;S(bt),ue.success("Video uploaded successfully! It may take a few minutes to process.")}catch(Xe){console.error("Upload error:",Xe),ue.error("Failed to upload video")}finally{ne(!1)}}},Ie=async()=>{if(!y.trim()){ue.error("Title is required");return}try{let Ze;if(o){const{error:lt}=await V.from("levelup_briefs").update({title:y,description:w||null,video_url:N||null,graphic_url:T||null,graphic_link_url:I||null,is_published:R,publish_date:F,show_frequency:Q}).eq("id",o.id);if(lt)throw lt;Ze=o.id,await V.from("levelup_brief_links").delete().eq("brief_id",Ze);const{data:xt}=await V.from("levelup_brief_polls").select("id").eq("brief_id",Ze);if(xt)for(const Xe of xt)await V.from("levelup_brief_poll_options").delete().eq("poll_id",Xe.id);await V.from("levelup_brief_polls").delete().eq("brief_id",Ze)}else{const{data:lt,error:xt}=await V.from("levelup_briefs").insert({title:y,description:w||null,video_url:N||null,graphic_url:T||null,graphic_link_url:I||null,is_published:R,publish_date:F,show_frequency:Q,created_by:s==null?void 0:s.id}).select().single();if(xt)throw xt;Ze=lt.id}if(X.length>0){const lt=X.map((xt,Xe)=>({brief_id:Ze,title:xt.title,url:xt.url,sort_order:Xe}));await V.from("levelup_brief_links").insert(lt)}for(let lt=0;lt0){const jt=xt.options.map((ns,Ns)=>({poll_id:Xe.id,option_text:ns,sort_order:Ns}));await V.from("levelup_brief_poll_options").insert(jt)}}ue.success(o?"Brief updated":"Brief created"),l(!1),De(),Be()}catch(Ze){console.error("Error saving brief:",Ze),ue.error("Failed to save brief")}},Te=async Ze=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:lt}=await V.from("levelup_briefs").delete().eq("id",Ze);if(lt)throw lt;ue.success("Brief deleted"),Be()}catch(lt){console.error("Error deleting brief:",lt),ue.error("Failed to delete brief")}},xe=async Ze=>{x(Ze);const{count:lt}=await V.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Ze.id),{count:xt}=await V.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Ze.id).not("dismissed_at","is",null);Ue({total:lt||0,dismissed:xt||0});const{data:Xe}=await V.from("levelup_brief_polls").select("*").eq("brief_id",Ze.id).order("sort_order");if(Xe){const Je=[];for(const jt of Xe){const{data:ns}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",jt.id).order("sort_order"),{data:Ns}=await V.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",jt.id),Ys=[...new Set((Ns==null?void 0:Ns.map(is=>is.user_id))||[])];let rs={};if(Ys.length>0){const{data:is}=await V.from("profiles").select("id, name, email").in("id",Ys);is&&is.forEach(Bs=>{rs[Bs.id]=Bs.name||Bs.email||"Unknown"})}const bt=(Ns||[]).map(is=>({optionId:is.option_id,userName:rs[is.user_id]||"Unknown",userId:is.user_id})),cs={};let yt=0;ns&&ns.forEach(is=>{const Bs=(Ns==null?void 0:Ns.filter(ps=>ps.option_id===is.id).length)||0;cs[is.id]=Bs,yt+=Bs}),Je.push({...jt,options:ns||[],results:cs,respondents:bt,totalResponses:jt.poll_type==="single"?new Set(Ns==null?void 0:Ns.map(is=>is.user_id)).size:yt})}ve(Je)}h(!0)},et=()=>{Z([...X,{title:"",url:""}])},fe=(Ze,lt,xt)=>{const Xe=[...X];Xe[Ze][lt]=xt,Z(Xe)},it=Ze=>{Z(X.filter((lt,xt)=>xt!==Ze))},Oe=()=>{le([...re,{question:"",poll_type:"single",options:["",""]}])},Ye=(Ze,lt)=>{const xt=[...re];xt[Ze].question=lt,le(xt)},We=(Ze,lt)=>{const xt=[...re];xt[Ze].poll_type=lt,le(xt)},_e=Ze=>{const lt=[...re];lt[Ze].options.push(""),le(lt)},Re=(Ze,lt,xt)=>{const Xe=[...re];Xe[Ze].options[lt]=xt,le(Xe)},tt=(Ze,lt)=>{const xt=[...re];xt[Ze].options=xt[Ze].options.filter((Xe,Je)=>Je!==lt),le(xt)},Ke=Ze=>{le(re.filter((lt,xt)=>xt!==Ze))};return e.jsxs(ws,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(G,{onClick:Ae,children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Frequency"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:n?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(Ze=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:Ze.title}),e.jsx(dt,{children:e.jsx(Ge,{variant:Ze.is_published?"default":"secondary",children:Ze.is_published?"Published":"Draft"})}),e.jsx(dt,{className:"capitalize",children:Ze.show_frequency.replace("_"," ")}),e.jsx(dt,{children:_s(new Date(Ze.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>xe(Ze),children:e.jsx(ro,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>He(Ze),children:e.jsx(sd,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Te(Ze.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},Ze.id))})]})})})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(On,{defaultValue:"content",className:"w-full",children:[e.jsxs(Rn,{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(ts,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Title *"}),e.jsx(Ne,{value:y,onChange:Ze=>v(Ze.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:w,onChange:Ze=>b(Ze),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(he,{children:"Publish Date"}),e.jsx(Ne,{type:"datetime-local",value:F,onChange:Ze=>z(Ze.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Show Frequency"}),e.jsxs(Is,{value:Q,onValueChange:K,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"once",children:"Once (until dismissed)"}),e.jsx(ct,{value:"every_login",children:"Every login"}),e.jsx(ct,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_r,{checked:R,onCheckedChange:$}),e.jsx(he,{children:"Publish immediately"})]})]}),e.jsxs(ts,{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(he,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ne,{type:"file",accept:"video/*",onChange:Le,disabled:oe})}),oe&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Or paste embed URL"}),e.jsx(Ne,{value:N,onChange:Ze=>S(Ze.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),N&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:N,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(he,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Ne,{type:"file",accept:"image/*",onChange:async Ze=>{var xt;const lt=(xt=Ze.target.files)==null?void 0:xt[0];if(lt){ye(!0);try{const Xe=lt.name.split(".").pop(),Je=`brief-graphics/${Date.now()}.${Xe}`,{error:jt}=await V.storage.from("banner-images").upload(Je,lt,{upsert:!0});if(jt)throw jt;const{data:ns}=V.storage.from("banner-images").getPublicUrl(Je);A(ns.publicUrl),ue.success("Image uploaded!")}catch(Xe){console.error(Xe),ue.error("Failed to upload image")}finally{ye(!1)}}},disabled:ie})}),ie&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Or paste Image URL"}),e.jsx(Ne,{value:T,onChange:Ze=>A(Ze.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Click-through Link (optional)"}),e.jsx(Ne,{value:I,onChange:Ze=>D(Ze.target.value),placeholder:"https://example.com/landing-page"})]}),T&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:T,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(ts,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(he,{children:"Quick Links"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:et,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),X.map((Ze,lt)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(Ne,{value:Ze.title,onChange:xt=>fe(lt,"title",xt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(Ne,{value:Ze.url,onChange:xt=>fe(lt,"url",xt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>it(lt),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]},lt)),X.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(ts,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(he,{children:"Polls"}),e.jsxs(G,{variant:"outline",size:"sm",onClick:Oe,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),re.map((Ze,lt)=>e.jsx(ke,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(Ne,{value:Ze.question,onChange:xt=>Ye(lt,xt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(Is,{value:Ze.poll_type,onValueChange:xt=>We(lt,xt),children:[e.jsx(As,{className:"w-32",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"single",children:"Single"}),e.jsx(ct,{value:"multi",children:"Multi-select"})]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Ke(lt),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[Ze.options.map((xt,Xe)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:xt,onChange:Je=>Re(lt,Xe,Je.target.value),placeholder:`Option ${Xe+1}`}),Ze.options.length>2&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>tt(lt,Xe),children:e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"})})]},Xe)),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>_e(lt),children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},lt)),re.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(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:Ie,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(fs,{open:d,onOpenChange:h,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Results: ",m==null?void 0:m.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-2xl font-bold",children:be.total})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-2xl font-bold",children:be.dismissed})})]})]}),ce.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ce.map(Ze=>e.jsxs(ke,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:Ze.question}),e.jsx("div",{className:"space-y-2",children:Ze.options.map(lt=>{const xt=Ze.results[lt.id]||0,Xe=Ze.totalResponses>0?Math.round(xt/Ze.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:lt.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[xt," (",Xe,"%)"]})]}),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:`${Xe}%`}})}),xt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(Ze.respondents||[]).filter(Je=>Je.optionId===lt.id).map((Je,jt)=>e.jsx(Ge,{variant:"secondary",className:"text-xs font-normal",children:Je.userName},jt))})]},lt.id)})})]},Ze.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const r3s=()=>{const{user:s}=js(),{toast:t}=Ma(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,h]=k.useState(null),[m,x]=k.useState(""),{data:y=[],isLoading:v}=mt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:I,error:D}=await V.from("additional_services").select("*").order("publish_date",{ascending:!1});if(D)throw D;return I}}),w=Ct({mutationFn:async I=>{let D=I.existingImageUrl;if(I.image){const $=I.image.name.split(".").pop(),F=`${Date.now()}-${Math.random().toString(36).substring(7)}.${$}`,{error:z}=await V.storage.from("service-images").upload(F,I.image);if(z)throw z;const{data:Q}=V.storage.from("service-images").getPublicUrl(F);D=Q.publicUrl}const R={name:I.item.name,description:I.item.description||null,preview_image_url:D,signup_link_url:I.item.signup_link_url,publish_date:I.item.publish_date?new Date(I.item.publish_date).toISOString():new Date().toISOString(),is_published:I.item.is_published,created_by:s==null?void 0:s.id};if(I.itemId){const{error:$}=await V.from("additional_services").update(R).eq("id",I.itemId);if($)throw $}else{const{error:$}=await V.from("additional_services").insert(R);if($)throw $}},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),N()},onError:I=>{t({title:"Error saving service",description:I.message,variant:"destructive"})}}),b=Ct({mutationFn:async I=>{const{error:D}=await V.from("additional_services").delete().eq("id",I);if(D)throw D},onSuccess:()=>{r.invalidateQueries({queryKey:["additional-services-admin"]}),r.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:I=>{t({title:"Error deleting service",description:I.message,variant:"destructive"})}}),N=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),h(null),x(""),l(null)},S=I=>{l(I),c({name:I.name,description:I.description||"",signup_link_url:I.signup_link_url,publish_date:I.publish_date?new Date(I.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:I.is_published}),x(I.preview_image_url||""),a(!0)},T=I=>{var R;const D=(R=I.target.files)==null?void 0:R[0];D&&(h(D),x(URL.createObjectURL(D)))},A=I=>{if(I.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}w.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(ws,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:y.length})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:y.filter(I=>I.is_published).length})})]})]}),e.jsxs(fs,{open:n,onOpenChange:I=>{a(I),I||N()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{htmlFor:"name",children:"Name *"}),e.jsx(Ne,{id:"name",value:o.name,onChange:I=>c({...o,name:I.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(Uy,{content:o.description,onChange:I=>c({...o,description:I}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(Ne,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:I=>c({...o,signup_link_url:I.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(Ne,{id:"publish_date",type:"date",value:o.publish_date,onChange:I=>c({...o,publish_date:I.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_r,{id:"is_published",checked:o.is_published,onCheckedChange:I=>c({...o,is_published:I})}),e.jsx(he,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),m?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:m,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(G,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{h(null),x("")},children:e.jsx(vr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(ml,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(Ne,{type:"file",accept:"image/*",onChange:T,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:w.isPending,children:w.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:v?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"})}):y.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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-16",children:"Preview"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Signup Link"}),e.jsx(Nt,{children:"Publish Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:y.map(I=>e.jsxs(Ds,{children:[e.jsx(dt,{children:I.preview_image_url?e.jsx("img",{src:I.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(ml,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(dt,{className:"font-medium",children:I.name}),e.jsx(dt,{children:e.jsxs("a",{href:I.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Qr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(dt,{children:new Date(I.publish_date).toLocaleDateString()}),e.jsx(dt,{children:e.jsx(Ge,{variant:I.is_published?"default":"secondary",children:I.is_published?"Published":"Draft"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>S(I),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&b.mutate(I.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},I.id))})]})})})]})})};function n3s(){const{toast:s}=Ma(),[t,r]=k.useState([]),[n,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});k.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:b,error:N}=await V.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(N)throw N;r(b.coupons||[])}catch(b){console.error("Error fetching coupons:",b),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},x=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 b={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?b.percent_off=parseFloat(d.percentOff):(b.amount_off=Math.round(parseFloat(d.amountOff)*100),b.currency="usd"),d.duration==="repeating"&&(b.duration_in_months=parseInt(d.durationInMonths));const{data:N,error:S}=await V.functions.invoke("stripe-manage-coupons",{body:b});if(S)throw S;s({title:"Success",description:"Coupon created successfully"}),c(!1),h({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),m()}catch(b){console.error("Error creating coupon:",b),s({title:"Error",description:b.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},y=async b=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:N}=await V.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:b}});if(N)throw N;s({title:"Success",description:"Coupon deleted successfully"}),m()}catch(N){console.error("Error deleting coupon:",N),s({title:"Error",description:N.message||"Failed to delete coupon",variant:"destructive"})}},v=b=>b.percent_off?`${b.percent_off}% off`:b.amount_off?`$${(b.amount_off/100).toFixed(2)} off`:"N/A",w=b=>{switch(b.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${b.duration_in_months} months`;default:return b.duration}};return e.jsx(ws,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(fs,{open:o,onOpenChange:c,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create New Coupon"}),e.jsx(Hr,{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(he,{children:"Promotion Code (what users will type)"}),e.jsx(Ne,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:b=>h({...d,promotionCode:b.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(he,{children:"Coupon Name (internal label)"}),e.jsx(Ne,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:b=>h({...d,name:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Discount Type"}),e.jsxs(Is,{value:d.discountType,onValueChange:b=>{const N=b==="amount"&&d.duration==="forever"?"once":d.duration;h({...d,discountType:b,duration:N})},children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Y4,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(ct,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(wl,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:b=>h({...d,percentOff:b.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(he,{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(Ne,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:b=>h({...d,amountOff:b.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Duration"}),e.jsxs(Is,{value:d.duration,onValueChange:b=>h({...d,duration:b}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"once",children:"Once (first payment only)"}),e.jsx(ct,{value:"repeating",children:"Multiple months"}),e.jsxs(ct,{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(he,{children:"Number of Months"}),e.jsx(Ne,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:b=>h({...d,durationInMonths:b.target.value})})]}),e.jsx(G,{onClick:x,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Active Coupons"}),e.jsx(Nr,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Pe,{children:n?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(es,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Promo Code"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Discount"}),e.jsx(Nt,{children:"Duration"}),e.jsx(Nt,{children:"Redemptions"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:t.map(b=>{var N;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-mono font-medium",children:((N=b.promotion_codes)==null?void 0:N.length)>0?b.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(dt,{children:b.name||"-"}),e.jsx(dt,{children:v(b)}),e.jsx(dt,{children:w(b)}),e.jsx(dt,{children:b.times_redeemed}),e.jsx(dt,{children:e.jsx(Ge,{variant:b.valid?"default":"secondary",children:b.valid?"Active":"Inactive"})}),e.jsx(dt,{className:"text-right",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>y(b.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})})]},b.id)})})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"How to Use Coupons"})}),e.jsxs(Pe,{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 dbe={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 a3s(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("all"),[l,o]=k.useState(null),{data:c,isLoading:d,refetch:h}=mt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:N,error:S}=await V.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(S)throw S;return N}}),{data:m}=mt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:N,error:S}=await V.from("brokerages").select("*").order("name");if(S)throw S;return await Promise.all((N||[]).map(async A=>{const{data:I}=await V.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:D}=await V.from("user_roles").select("user_id").eq("role","brokerage_manager"),R=(D==null?void 0:D.map(z=>z.user_id))||[],$=(I==null?void 0:I.filter(z=>R.includes(z.id)))||[],F=(I==null?void 0:I.length)||0;return{...A,managers:$,agentCount:F}}))}}),{data:x}=mt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:N,error:S}=await V.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(S)throw S;return N}}),y=N=>{if(N.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(N.brokerage_id&&!N.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(N.is_trial&&N.trial_expires_at)return new Date(N.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(N.subscription_status==="active"||N.subscription_status==="trialing"){const S=dbe[N.subscription_product_id];return{status:(S==null?void 0:S.name)||"Active",badge:N.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return N.subscription_status==="canceled"||N.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},v=c==null?void 0:c.filter(N=>{var T,A;if(!(((T=N.name)==null?void 0:T.toLowerCase().includes(s.toLowerCase()))||((A=N.email)==null?void 0:A.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const I=N.subscription_source||"platform";if(a==="platform"&&I==="local_move_website"||a==="local_move_website"&&I!=="local_move_website")return!1}switch(y(N),r){case"active":return N.subscription_status==="active";case"trialing":return N.subscription_status==="trialing"||N.is_trial&&new Date(N.trial_expires_at)>new Date;case"grandfathered":return N.is_grandfathered;case"brokerage":return N.brokerage_id&&!N.subscription_product_id&&!N.is_grandfathered;case"expired":return N.subscription_status==="canceled"||N.subscription_status==="past_due"||N.is_trial&&new Date(N.trial_expires_at)<=new Date;case"none":return!N.subscription_status||N.subscription_status==="none";default:return!0}}),w={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(N=>N.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(N=>N.subscription_status==="trialing"||N.is_trial&&new Date(N.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(N=>N.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(N=>N.brokerage_id&&!N.subscription_product_id&&!N.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(N=>N.subscription_status==="active"&&N.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(N=>N.subscription_status==="active"&&(N.subscription_product_id==="prod_Tc08MupgoVySDG"||N.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},b=N=>{window.open(`https://dashboard.stripe.com/customers/${N}`,"_blank")};return e.jsx(ws,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(G,{onClick:()=>h(),variant:"outline",size:"sm",children:[e.jsx(Mi,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{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:w.totalUsers})]})}),e.jsx(ke,{className:"border-green-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vp,{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:w.activeSubscriptions})]})}),e.jsx(ke,{className:"border-blue-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{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:w.trials})]})}),e.jsx(ke,{className:"border-purple-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zh,{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:w.grandfathered})]})}),e.jsx(ke,{className:"border-orange-500/50",children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{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:w.brokerageMembers})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uv,{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:w.individualSubscribers})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{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:w.brokerageSubscribers})]})})]}),e.jsxs(On,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Rn,{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(fc,{className:"h-4 w-4"}),"Website Subscriptions",x&&x.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1",children:x.length})]})]}),e.jsxs(ts,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:s,onChange:N=>t(N.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:a,onValueChange:N=>i(N),children:[e.jsx(As,{className:"w-[200px]",children:e.jsx(Ls,{placeholder:"Source"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Sources"}),e.jsx(ct,{value:"platform",children:"Platform"}),e.jsx(ct,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(Is,{value:r,onValueChange:N=>n(N),children:[e.jsx(As,{className:"w-[200px]",children:e.jsx(Ls,{placeholder:"Filter by status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Statuses"}),e.jsx(ct,{value:"active",children:"Active Subscriptions"}),e.jsx(ct,{value:"trialing",children:"Trials"}),e.jsx(ct,{value:"grandfathered",children:"Grandfathered"}),e.jsx(ct,{value:"brokerage",children:"Brokerage Members"}),e.jsx(ct,{value:"expired",children:"Expired/Canceled"}),e.jsx(ct,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"User"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Plan"}),e.jsx(Nt,{children:"Brokerage"}),e.jsx(Nt,{children:"End Date"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:d?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(v==null?void 0:v.length)===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):v==null?void 0:v.map(N=>{var A,I;const S=y(N),T=dbe[N.subscription_product_id];return e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:N.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.email})]})}),e.jsx(dt,{children:e.jsx(Ge,{variant:S.variant,children:S.badge})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm",children:N.is_grandfathered?"Legacy Access":N.brokerage_id&&!N.subscription_product_id?"Brokerage Subscription":(T==null?void 0:T.name)||S.status})}),e.jsx(dt,{children:(A=N.brokerages)!=null&&A.name?e.jsx("span",{className:"text-sm",children:N.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(dt,{children:N.subscription_end_date?e.jsx("span",{className:"text-sm",children:_s(new Date(N.subscription_end_date),"MMM d, yyyy")}):N.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",_s(new Date(N.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[N.stripe_customer_id&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>b(N.stripe_customer_id),children:e.jsx(Qr,{className:"h-4 w-4"})}),e.jsxs(fs,{children:[e.jsx(vi,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",onClick:()=>o(N),children:"Details"})}),e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Subscription Details"}),e.jsxs(Hr,{children:[N.name," (",N.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(Ge,{variant:S.variant,className:"mt-1",children:S.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:N.is_grandfathered?"Grandfathered (Legacy)":N.brokerage_id&&!N.subscription_product_id?"Brokerage Subscription":(T==null?void 0:T.name)||"None"})]}),N.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((I=N.brokerages)==null?void 0:I.name)||"Unknown"})]}),N.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:_s(new Date(N.subscription_end_date),"MMMM d, yyyy")})]}),N.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:_s(new Date(N.trial_expires_at),"MMMM d, yyyy")})]}),N.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:N.stripe_customer_id})]})]}),N.stripe_customer_id&&e.jsxs(G,{className:"w-full",onClick:()=>b(N.stripe_customer_id),children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},N.id)})})]})})})]}),e.jsx(ts,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:m==null?void 0:m.map(N=>{var T,A;const S=(T=N.managers)==null?void 0:T.some(I=>I.subscription_status==="active"&&(I.subscription_product_id==="prod_Tc08MupgoVySDG"||I.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(ke,{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(Sa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:N.name}),e.jsxs(Nr,{children:[N.agentCount," agents"]})]})]}),e.jsx(Ge,{variant:S?"default":"outline",children:S?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Pe,{children:((A=N.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:"}),N.managers.map(I=>{const D=dbe[I.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:I.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:I.email})]}),e.jsx("div",{className:"text-right",children:D?e.jsxs("div",{children:[e.jsx(Ge,{variant:"default",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.price})]}):e.jsx(Ge,{variant:"outline",children:"No Subscription"})})]},I.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},N.id)})})}),e.jsx(ts,{value:"websites",className:"space-y-4",children:e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(fc,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Nr,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Setup Fee"}),e.jsx(Nt,{children:"Monthly"}),e.jsx(Nt,{children:"Next Renewal"}),e.jsx(Nt,{children:"Started"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:x?x.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):x.map(N=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:N.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.agent_email})]})}),e.jsx(dt,{children:e.jsx(Ge,{variant:N.status==="active"?"default":N.status==="canceled"?"destructive":"outline",children:N.status})}),e.jsx(dt,{children:N.setup_fee_paid?e.jsxs(Ge,{variant:"secondary",children:["Paid · $",(N.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Ge,{variant:"outline",children:"Unpaid"})}),e.jsxs(dt,{className:"font-medium",children:["$",(N.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(dt,{children:N.current_period_end?e.jsx("span",{className:"text-sm",children:_s(new Date(N.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm",children:_s(new Date(N.created_at),"MMM d, yyyy")})}),e.jsx(dt,{className:"text-right",children:N.stripe_customer_id&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>b(N.stripe_customer_id),children:e.jsx(Qr,{className:"h-4 w-4"})})})]},N.id)):e.jsx(Ds,{children:e.jsx(dt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function i3s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});k.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:w}=await V.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(w)throw w;t(v||[]);const b=(v==null?void 0:v.filter(T=>T.status==="qualified").length)||0,N=(v==null?void 0:v.filter(T=>T.status==="pending").length)||0,S=(v==null?void 0:v.filter(T=>T.status==="cancelled").length)||0;d({total:(v==null?void 0:v.length)||0,qualified:b,pending:N,cancelled:S,totalDiscounts:b*25})}catch(v){console.error("Error fetching referrals:",v),ue.error("Failed to load referrals")}finally{n(!1)}},m=async()=>{try{ue.loading("Processing qualifications...");const{error:v}=await V.functions.invoke("process-referral-qualifications");if(v)throw v;ue.dismiss(),ue.success("Qualifications processed successfully"),h()}catch(v){ue.dismiss(),console.error("Error processing qualifications:",v),ue.error("Failed to process qualifications")}},x=s.filter(v=>{var N,S,T,A,I,D;const w=((S=(N=v.referrer_brokerage)==null?void 0:N.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((A=(T=v.referred_brokerage)==null?void 0:T.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((D=(I=v.referred_user)==null?void 0:I.email)==null?void 0:D.toLowerCase().includes(a.toLowerCase())),b=l==="all"||v.status===l;return w&&b}),y=v=>{switch(v){case"qualified":return e.jsxs(Ge,{className:"bg-green-100 text-green-800",children:[e.jsx(di,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Ge,{variant:"secondary",children:[e.jsx(fn,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Sc,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Ge,{children:v})}};return e.jsx(ws,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(G,{onClick:m,variant:"outline",children:[e.jsx(Mi,{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(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{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(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(di,{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(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fn,{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(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sc,{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(ke,{children:e.jsx(Pe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(wl,{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(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"All Referrals"}),e.jsx(Nr,{children:"View and manage all referral relationships"})]}),e.jsxs(Pe,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by brokerage or email...",value:a,onChange:v=>i(v.target.value),className:"pl-10"})]}),e.jsxs(Is,{value:l,onValueChange:o,children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"Filter by status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Statuses"}),e.jsx(ct,{value:"pending",children:"Pending"}),e.jsx(ct,{value:"qualified",children:"Qualified"}),e.jsx(ct,{value:"cancelled",children:"Cancelled"})]})]})]}),r?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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Referrer"}),e.jsx(Nt,{children:"Referred"}),e.jsx(Nt,{children:"Signup Date"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Qualified Date"}),e.jsx(Nt,{children:"Discount"})]})}),e.jsx($n,{children:x.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):x.map(v=>{var w,b,N,S;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:((w=v.referrer_brokerage)==null?void 0:w.name)||"Unknown"}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((b=v.referred_brokerage)==null?void 0:b.name)||((N=v.referred_user)==null?void 0:N.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(S=v.referred_user)==null?void 0:S.email})]})}),e.jsx(dt,{children:_s(new Date(v.signup_date),"MMM d, yyyy")}),e.jsx(dt,{children:y(v.status)}),e.jsx(dt,{children:v.qualified_date?_s(new Date(v.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(dt,{children:v.discount_applied?e.jsx(Ge,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},v.id)})})]})]})]})]})})}const ube=[{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"}],o3s=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function l3s(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});k.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:S,error:T}=await V.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(T)throw T;t(S||[])}catch(S){console.error("Error fetching checklist items:",S),ue.error("Failed to load checklist items")}finally{n(!1)}},m=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},x=S=>{o(S),d({title:S.title,description:S.description||"",action_type:S.action_type,target_role:S.target_role,is_active:S.is_active}),i(!0)},y=async()=>{if(!c.title.trim()){ue.error("Title is required");return}try{if(l){const{error:S}=await V.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(S)throw S;ue.success("Checklist item updated")}else{const S=s.filter(A=>A.target_role===c.target_role).reduce((A,I)=>Math.max(A,I.sort_order),-1),{error:T}=await V.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:S+1});if(T)throw T;ue.success("Checklist item created")}i(!1),h()}catch(S){console.error("Error saving checklist item:",S),ue.error("Failed to save checklist item")}},v=async S=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:T}=await V.from("onboarding_checklist_items").delete().eq("id",S);if(T)throw T;ue.success("Checklist item deleted"),h()}catch(T){console.error("Error deleting checklist item:",T),ue.error("Failed to delete checklist item")}},w=async S=>{try{const{error:T}=await V.from("onboarding_checklist_items").update({is_active:!S.is_active}).eq("id",S.id);if(T)throw T;ue.success(S.is_active?"Item deactivated":"Item activated"),h()}catch(T){console.error("Error toggling item:",T),ue.error("Failed to update item")}},b=s.filter(S=>S.target_role==="brokerage_manager"),N=s.filter(S=>S.target_role==="agent");return e.jsxs(ws,{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(G,{onClick:m,className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ge,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Pe,{children:b.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-12",children:"#"}),e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Action Type"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:b.map((S,T)=>{var A;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"text-muted-foreground",children:T+1}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:S.title}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:S.description})]})}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",children:((A=ube.find(I=>I.value===S.action_type))==null?void 0:A.label)||S.action_type})}),e.jsx(dt,{children:e.jsx(_r,{checked:S.is_active,onCheckedChange:()=>w(S)})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(S),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(S.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},S.id)})})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ge,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Pe,{children:N.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-12",children:"#"}),e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Action Type"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:N.map((S,T)=>{var A;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"text-muted-foreground",children:T+1}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:S.title}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:S.description})]})}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",children:((A=ube.find(I=>I.value===S.action_type))==null?void 0:A.label)||S.action_type})}),e.jsx(dt,{children:e.jsx(_r,{checked:S.is_active,onCheckedChange:()=>w(S)})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(S),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(S.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},S.id)})})]})})]})]}),e.jsx(fs,{open:a,onOpenChange:i,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{htmlFor:"title",children:"Title *"}),e.jsx(Ne,{id:"title",value:c.title,onChange:S=>d({...c,title:S.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",value:c.description,onChange:S=>d({...c,description:S.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(he,{children:"Target Role"}),e.jsxs(Is,{value:c.target_role,onValueChange:S=>d({...c,target_role:S}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:o3s.map(S=>e.jsx(ct,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Action Type"}),e.jsxs(Is,{value:c.action_type,onValueChange:S=>d({...c,action_type:S}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:ube.map(S=>e.jsx(ct,{value:S.value,children:S.label},S.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"is_active",checked:c.is_active,onCheckedChange:S=>d({...c,is_active:S})}),e.jsx(he,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(G,{onClick:y,children:l?"Save Changes":"Create Item"})]})]})})]})}function c3s(){const[s,t]=k.useState(""),[r,n]=k.useState("all"),[a,i]=k.useState("name"),[l,o]=k.useState("asc"),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState(""),{data:b}=mt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:z,error:Q}=await V.from("brokerages").select("id, name").order("name");if(Q)throw Q;return z}}),N=async z=>{let K=[],X=0,Z=!0;for(;Z;){const{data:re,error:le}=await z(X,X+1e3-1);if(le)throw le;re&&re.length>0?(K=[...K,...re],X+=1e3,Z=re.length===1e3):Z=!1}return K},{data:S,isLoading:T}=mt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const z=await N((He,Le)=>V.from("profiles").select("id, name, email, brokerage_id, created_at").range(He,Le)),{data:Q}=await V.from("brokerages").select("id, name"),K=new Map((Q==null?void 0:Q.map(He=>[He.id,He.name]))||[]),[{data:X},{data:Z},{data:re},{data:le},{data:oe},{data:ne},{data:ie}]=await Promise.all([V.rpc("get_admin_contact_counts"),V.rpc("get_admin_video_counts"),V.rpc("get_admin_popby_counts"),V.rpc("get_admin_listing_counts"),V.rpc("get_admin_deal_counts"),V.rpc("get_admin_portal_counts"),V.rpc("get_admin_sendable_card_counts")]),ye=new Map;X==null||X.forEach(He=>ye.set(He.owner_user_id,He.contact_count));const ce=new Map;Z==null||Z.forEach(He=>ce.set(He.owner_user_id,He.video_count));const ve=new Map;re==null||re.forEach(He=>ve.set(He.owner_user_id,He.popby_count));const be=new Map;le==null||le.forEach(He=>be.set(He.agent_id,He.listing_count));const Ue=new Map;oe==null||oe.forEach(He=>Ue.set(He.owner_user_id,He.deal_count));const Be=new Map;ne==null||ne.forEach(He=>Be.set(He.owner_user_id,{total:He.portal_count,active:He.active_portal_count}));const De=new Map;return ie==null||ie.forEach(He=>De.set(He.owner_user_id,{total:He.card_count,sent:He.sent_card_count,views:He.total_card_views})),z.map(He=>{const Le=Be.get(He.id),Ie=De.get(He.id);return{id:He.id,name:He.name||"Unknown",email:He.email||"",brokerage_id:He.brokerage_id,brokerage_name:He.brokerage_id&&K.get(He.brokerage_id)||null,contact_count:ye.get(He.id)||0,video_count:ce.get(He.id)||0,popby_count:ve.get(He.id)||0,listing_count:be.get(He.id)||0,deal_count:Ue.get(He.id)||0,portal_count:(Le==null?void 0:Le.total)||0,active_portal_count:(Le==null?void 0:Le.active)||0,card_count:(Ie==null?void 0:Ie.total)||0,sent_card_count:(Ie==null?void 0:Ie.sent)||0,total_card_views:(Ie==null?void 0:Ie.views)||0,created_at:He.created_at}})}}),A=k.useMemo(()=>{if(!S)return[];let z=S.filter(Q=>{const K=s.toLowerCase(),X=!s||Q.name.toLowerCase().includes(K)||Q.email.toLowerCase().includes(K),Z=r==="all"||r==="none"&&!Q.brokerage_id||Q.brokerage_id===r,re=parseInt(c)||0,le=parseInt(h)||0,oe=parseInt(x)||0,ne=parseInt(v)||0,ie=Q.contact_count>=re&&Q.video_count>=le&&Q.popby_count>=oe&&Q.listing_count>=ne;return X&&Z&&ie});return z.sort((Q,K)=>{let X=0;return a==="name"?X=Q.name.localeCompare(K.name):X=Q[a]-K[a],l==="asc"?X:-X}),z},[S,s,r,a,l,c,h,x,v]),I=z=>{a===z?o(l==="asc"?"desc":"asc"):(i(z),o("desc"))},D=()=>{const z=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],Q=A.map(le=>[le.name,le.email,le.brokerage_name||"None",le.contact_count,le.video_count,le.popby_count,le.listing_count,le.deal_count,`${le.portal_count} (${le.active_portal_count})`,le.card_count,le.sent_card_count,le.total_card_views]),K=[z.join(","),...Q.map(le=>le.map(oe=>`"${oe}"`).join(","))].join(` `),X=new Blob([K],{type:"text/csv"}),Z=URL.createObjectURL(X),re=document.createElement("a");re.href=Z,re.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,re.click(),URL.revokeObjectURL(Z)},R=k.useMemo(()=>A.length?A.reduce((z,Q)=>({contacts:z.contacts+Q.contact_count,videos:z.videos+Q.video_count,popbys:z.popbys+Q.popby_count,listings:z.listings+Q.listing_count,deals:z.deals+Q.deal_count,portals:z.portals+Q.portal_count,activePortals:z.activePortals+Q.active_portal_count,cards:z.cards+Q.card_count,sentCards:z.sentCards+Q.sent_card_count,cardViews:z.cardViews+Q.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]),$=k.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:Q})=>e.jsx(Nt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>I(z),children:e.jsxs("div",{className:"flex items-center gap-1",children:[Q,e.jsx(Ad,{className:`h-3 w-3 ${a===z?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(Ub,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(ke,{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(Dt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sv,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Pe,{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:$.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:R.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:R.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(ke,{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(Dt,{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(Pe,{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:$.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:R.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:R.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:R.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Nr,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:D,children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Pe,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:s,onChange:z=>t(z.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(Is,{value:r,onValueChange:n,children:[e.jsxs(As,{children:[e.jsx(Sa,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(Ls,{placeholder:"Brokerage"})]}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Brokerages"}),e.jsx(ct,{value:"none",children:"No Brokerage"}),b==null?void 0:b.map(z=>e.jsx(ct,{value:z.id,children:z.name},z.id))]})]})}),e.jsx("div",{children:e.jsx(Ne,{type:"number",placeholder:"Min contacts",value:c,onChange:z=>d(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(Ne,{type:"number",placeholder:"Min videos",value:h,onChange:z=>m(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(Ne,{type:"number",placeholder:"Min popbys",value:x,onChange:z=>y(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:R.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:R.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:R.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:R.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:R.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:R.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:R.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),T?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(F,{field:"name",children:"Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{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(sv,{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($n,{children:A.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map(z=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:z.name}),e.jsx(dt,{className:"text-muted-foreground",children:z.email}),e.jsx(dt,{children:z.brokerage_name?e.jsx(Ge,{variant:"secondary",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(dt,{children:e.jsx(Ge,{variant:z.contact_count>0?"default":"outline",children:z.contact_count})}),e.jsx(dt,{children:e.jsx(Ge,{variant:z.video_count>0?"default":"outline",children:z.video_count})}),e.jsx(dt,{children:e.jsx(Ge,{variant:z.popby_count>0?"default":"outline",children:z.popby_count})}),e.jsx(dt,{children:e.jsx(Ge,{variant:z.listing_count>0?"default":"outline",children:z.listing_count})}),e.jsx(dt,{children:e.jsx(Ge,{variant:z.deal_count>0?"default":"outline",children:z.deal_count})}),e.jsx(dt,{children:z.portal_count>0?e.jsxs(cc,{children:[e.jsx(dc,{children:e.jsxs(Ge,{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(Gl,{children:[e.jsxs("p",{children:[z.portal_count," total portals"]}),e.jsxs("p",{children:[z.active_portal_count," currently active"]})]})]}):e.jsx(Ge,{variant:"outline",children:"0"})}),e.jsx(dt,{children:z.card_count>0?e.jsxs(cc,{children:[e.jsx(dc,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{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(en,{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(bn,{className:"h-3 w-3"}),z.total_card_views]})]})}),e.jsxs(Gl,{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(Ge,{variant:"outline",children:"0"})})]},z.id))})]})})]})]})]})})}function d3s(){Ma(),Xt();const[s,t]=k.useState("user-analytics"),{data:r}=mt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:y,error:v}=await V.from("feature_flags").select("*").order("key");if(v)throw v;return y}}),{data:n,isLoading:a}=mt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:y,error:v}=await V.from("relationship_types").select("*").order("sort_order");if(v)throw v;return y}}),{data:i,isLoading:l}=mt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:y,error:v}=await V.from("action_types").select("*").order("sort_order");if(v)throw v;return y}}),{data:o,isLoading:c}=mt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:y,error:v}=await V.from("action_scripts").select("*, action_type:action_types(*)");if(v)throw v;return y}}),{data:d,isLoading:h}=mt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:y,error:v}=await V.from("touchpoint_plans").select("*").order("name");if(v)throw v;return y}}),{data:m,isLoading:x}=mt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:y,error:v}=await V.from("popby_items").select("*").is("owner_user_id",null).order("name");if(v)throw v;return y}});return e.jsx(ws,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(On,{value:s,onValueChange:t,children:[e.jsxs(Rn,{className:"grid w-full grid-cols-9",children:[e.jsxs(Kt,{value:"user-analytics",className:"gap-2",children:[e.jsx(ro,{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(pr,{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(Cn,{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(ln,{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(gh,{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(on,{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(ii,{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(oo,{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(fb,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(ts,{value:"user-analytics",className:"mt-6",children:e.jsx(c3s,{})}),e.jsx(ts,{value:"relationship-types",className:"mt-6",children:e.jsx(u3s,{types:n||[],isLoading:a})}),e.jsx(ts,{value:"action-types",className:"mt-6",children:e.jsx(h3s,{types:i||[],isLoading:l})}),e.jsx(ts,{value:"scripts",className:"mt-6",children:e.jsx(m3s,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(ts,{value:"video-scripts",className:"mt-6",children:e.jsx(g3s,{})}),e.jsx(ts,{value:"plans",className:"mt-6",children:e.jsx(f3s,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:h})}),e.jsx(ts,{value:"popbys",className:"mt-6",children:e.jsx(x3s,{items:m||[],isLoading:x})}),e.jsx(ts,{value:"settings",className:"mt-6",children:e.jsx(y3s,{})}),e.jsx(ts,{value:"feature-flags",className:"mt-6",children:e.jsx(p3s,{flags:r||[]})})]})]})})}function u3s({types:s,isLoading:t}){const{toast:r}=Ma(),n=Xt(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Ct({mutationFn:async h=>{if(h.id){const{error:m}=await V.from("relationship_types").update({name:h.name,description:h.description,icon:h.icon}).eq("id",h.id);if(m)throw m}else{const{error:m}=await V.from("relationship_types").insert([{name:h.name,description:h.description,icon:h.icon,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await V.from("relationship_types").update({active:!h.active}).eq("id",h.id),n.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Relationship Types"}),e.jsx(Nr,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(G,{onClick:()=>{i(null),o(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Pe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-12"}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-24",children:"Actions"})]})}),e.jsx($n,{children:s.map(h=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx(vu,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(dt,{className:"font-medium",children:h.name}),e.jsx(dt,{className:"text-muted-foreground",children:h.description}),e.jsx(dt,{children:e.jsx(_r,{checked:h.active,onCheckedChange:()=>d(h)})}),e.jsx(dt,{children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})})})]},h.id))})]})}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"icon",children:"Icon"}),e.jsx(Ne,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function h3s({types:s,isLoading:t}){const{toast:r}=Ma(),n=Xt(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Ct({mutationFn:async h=>{if(h.id){const{error:m}=await V.from("action_types").update({name:h.name,description:h.description,icon:h.icon,color:h.color}).eq("id",h.id);if(m)throw m}else{const{error:m}=await V.from("action_types").insert([{name:h.name,description:h.description,icon:h.icon,color:h.color,sort_order:s.length}]);if(m)throw m}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await V.from("action_types").update({active:!h.active}).eq("id",h.id),n.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Action Types"}),e.jsx(Nr,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(G,{onClick:()=>{i(null),o(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Pe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{children:"Color"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-24",children:"Actions"})]})}),e.jsx($n,{children:s.map(h=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:h.name}),e.jsx(dt,{className:"text-muted-foreground",children:h.description}),e.jsx(dt,{children:h.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:h.color}})}),e.jsx(dt,{children:e.jsx(_r,{checked:h.active,onCheckedChange:()=>d(h)})}),e.jsx(dt,{children:e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})})})]},h.id))})]})}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description"),icon:m.get("icon"),color:m.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"icon",children:"Icon"}),e.jsx(Ne,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"color",children:"Color"}),e.jsx(Ne,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function m3s({scripts:s,actionTypes:t,isLoading:r}){const{toast:n}=Ma(),a=Xt(),[i,l]=k.useState(null),[o,c]=k.useState(!1),d=Ct({mutationFn:async m=>{if(m.id){const{error:x}=await V.from("action_scripts").update({title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:m.active}).eq("id",m.id);if(x)throw x}else{const{error:x}=await V.from("action_scripts").insert([{title:m.title,action_type_id:m.action_type_id,tone:m.tone,script_body:m.script_body,active:!0}]);if(x)throw x}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),n({title:"Saved successfully"})},onError:m=>{n({title:"Error",description:m.message,variant:"destructive"})}}),h=Ct({mutationFn:async m=>{const{error:x}=await V.from("action_scripts").delete().eq("id",m);if(x)throw x},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),n({title:"Deleted successfully"})}});return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Script Library"}),e.jsx(Nr,{children:"Create and manage scripts for each action type"})]}),e.jsxs(G,{onClick:()=>{l(null),c(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Pe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Action Type"}),e.jsx(Nt,{children:"Tone"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-24",children:"Actions"})]})}),e.jsx($n,{children:s.map(m=>{var x;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:m.title}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",children:((x=m.action_type)==null?void 0:x.name)||"Unknown"})}),e.jsx(dt,{className:"text-muted-foreground",children:m.tone}),e.jsx(dt,{children:e.jsx(Ge,{variant:m.active?"default":"secondary",children:m.active?"Active":"Inactive"})}),e.jsxs(dt,{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{l(m),c(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h.mutate(m.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})]},m.id)})})]})}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsxs(gs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const x=new FormData(m.currentTarget);d.mutate({id:i==null?void 0:i.id,title:x.get("title"),action_type_id:x.get("action_type_id"),tone:x.get("tone"),script_body:x.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(he,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(Is,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select action type"})}),e.jsx(Ms,{children:t.map(m=>e.jsx(ct,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(Ne,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_body",children:"Script Body"}),e.jsx(or,{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(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function f3s({plans:s,actionTypes:t,scripts:r,isLoading:n}){const{toast:a}=Ma(),i=Xt(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(null),[x,y]=k.useState(!1),[v,w]=k.useState(null),[b,N]=k.useState(null),{data:S}=mt({queryKey:["plan-items",h],queryFn:async()=>{if(!h)return[];const{data:F,error:z}=await V.from("touchpoint_plan_items").select("*").eq("plan_id",h).order("month_number");if(z)throw z;return F},enabled:!!h}),T=Ct({mutationFn:async F=>{if(F.id){const{error:z}=await V.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 V.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=Ct({mutationFn:async F=>{if(F.id){const{error:z}=await V.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 V.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",h]}),a({title:"Item saved"})}}),I=Ct({mutationFn:async F=>{const{error:z}=await V.from("touchpoint_plan_items").delete().eq("id",F);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",h]})}}),D=Ct({mutationFn:async F=>{const{data:z,error:Q}=await V.from("action_scripts").insert([{...F,active:!0}]).select().single();if(Q)throw Q;return z},onSuccess:async F=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),v&&await A.mutateAsync({id:v.itemId,plan_id:h,month_number:v.month,action_type_id:v.actionTypeId,default_script_id:F.id}),y(!1),w(null),a({title:"Script created and assigned"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),R=(F,z,Q)=>{w({month:F,actionTypeId:z,itemId:Q}),y(!0)},$=F=>r.find(z=>z.id===F);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Touchpoint Plans"}),e.jsx(Nr,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(G,{onClick:()=>{o(null),d(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Pe,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{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(ke,{className:`cursor-pointer transition-colors ${h===F.id?"border-primary":""}`,onClick:()=>m(F.id),children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:F.name}),e.jsx(G,{variant:"ghost",size:"icon",onClick:z=>{z.stopPropagation(),o(F),d(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})})]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:F.description}),e.jsx(Ge,{variant:F.active?"default":"secondary",className:"mt-2",children:F.active?"Active":"Inactive"})]})]},F.id))})})]}),h&&e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Plan Schedule"}),e.jsx(Nr,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Pe,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(F,z)=>z+1).map(F=>{const z=S==null?void 0:S.find(X=>X.month_number===F),Q=z!=null&&z.default_script_id?$(z.default_script_id):null,K=r.filter(X=>X.action_type_id===(z==null?void 0:z.action_type_id)&&X.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(Is,{value:(z==null?void 0:z.action_type_id)||"none",onValueChange:X=>{X==="none"&&z?I.mutate(z.id):X!=="none"&&A.mutate({id:z==null?void 0:z.id,plan_id:h,month_number:F,action_type_id:X,default_script_id:null})},children:[e.jsx(As,{className:"w-40",children:e.jsx(Ls,{placeholder:"No action"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No action"}),t.filter(X=>X.active).map(X=>e.jsx(ct,{value:X.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[X.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:X.color}}),X.name]})},X.id))]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(Is,{value:z.default_script_id||"none",onValueChange:X=>{N(null),A.mutate({id:z.id,default_script_id:X==="none"?null:X})},children:[e.jsx(As,{className:"w-56",children:e.jsx(Ls,{placeholder:"Select script"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No default script"}),K.map(X=>e.jsxs(ct,{value:X.id,children:[X.title," ",X.tone&&`(${X.tone})`]},X.id))]})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>R(F,z.action_type_id,z.id),children:[e.jsx($s,{className:"h-3 w-3 mr-1"}),"New Script"]}),Q&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>N((b==null?void 0:b.id)===Q.id?null:Q),children:(b==null?void 0:b.id)===Q.id?"Hide":"Preview"})]})]}),b&&(z==null?void 0:z.default_script_id)===b.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(Ge,{variant:"outline",children:b.title}),b.tone&&e.jsx(Ge,{variant:"secondary",children:b.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:b.script_body})]})]},F)})})})]}),e.jsx(fs,{open:c,onOpenChange:d,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);T.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(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:T.isPending,children:[T.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(fs,{open:x,onOpenChange:y,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create New Script"}),e.jsxs(Hr,{children:["Create a script for Month ",v==null?void 0:v.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);D.mutate({title:z.get("title"),action_type_id:v.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(he,{htmlFor:"script_title",children:"Title"}),e.jsx(Ne,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_tone",children:"Tone"}),e.jsx(Ne,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_body",children:"Script Body"}),e.jsx(or,{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(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:D.isPending,children:[D.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function p3s({flags:s}){const{toast:t}=Ma(),r=Xt(),n=async(a,i)=>{const{error:l}=await V.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(r.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Feature Flags"}),e.jsx(Nr,{children:"Control which features are enabled for members"})]}),e.jsx(Pe,{children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Flag"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Notes"}),e.jsx(Nt,{children:"Last Updated"})]})}),e.jsx($n,{children:s.map(a=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-mono text-sm",children:a.key}),e.jsx(dt,{children:e.jsx(_r,{checked:a.enabled,onCheckedChange:i=>n(a,{enabled:i})})}),e.jsx(dt,{children:e.jsx(Ne,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&n(a,{notes:i.target.value})}})}),e.jsx(dt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function x3s({items:s,isLoading:t}){const{toast:r}=Ma(),n=Xt(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Ct({mutationFn:async m=>{if(m.id){const{error:x}=await V.from("popby_items").update({name:m.name,description:m.description}).eq("id",m.id);if(x)throw x}else{const{error:x}=await V.from("popby_items").insert([{name:m.name,description:m.description,owner_user_id:null}]);if(x)throw x}},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),r({title:"Saved successfully"})},onError:m=>{r({title:"Error",description:m.message,variant:"destructive"})}}),d=async m=>{await V.from("popby_items").update({is_active:!m.is_active}).eq("id",m.id),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]})},h=async m=>{await V.from("popby_items").delete().eq("id",m),n.invalidateQueries({queryKey:["admin-popby-items"]}),n.invalidateQueries({queryKey:["popby-items"]}),r({title:"Deleted successfully"})};return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Popby Ideas"}),e.jsx(Nr,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(G,{onClick:()=>{i(null),o(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Pe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{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(ii,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-24",children:"Actions"})]})}),e.jsx($n,{children:s.map(m=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:m.name}),e.jsx(dt,{className:"text-muted-foreground",children:m.description}),e.jsx(dt,{children:e.jsx(_r,{checked:m.is_active,onCheckedChange:()=>d(m)})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{i(m),o(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h(m.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},m.id))})]})}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:m=>{m.preventDefault();const x=new FormData(m.currentTarget);c.mutate({id:a==null?void 0:a.id,name:x.get("name"),description:x.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function g3s(){var y;const{toast:s}=Ma(),t=Xt(),[r,n]=k.useState(null),[a,i]=k.useState(!1),{data:l,isLoading:o}=mt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:v,error:w}=await V.from("video_script_categories").select("*").order("sort_order");if(w)throw w;return v}}),{data:c,isLoading:d}=mt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:v,error:w}=await V.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(w)throw w;return v}}),h=Ct({mutationFn:async v=>{var w,b;if(v.id){const{error:N}=await V.from("video_scripts").update({title:v.title,script_text:v.script_text,category_id:v.category_id,tags:((w=v.tags)==null?void 0:w.split(",").map(S=>S.trim()).filter(Boolean))||[]}).eq("id",v.id);if(N)throw N}else{const{error:N}=await V.from("video_scripts").insert([{title:v.title,script_text:v.script_text,category_id:v.category_id||null,tags:((b=v.tags)==null?void 0:b.split(",").map(S=>S.trim()).filter(Boolean))||[]}]);if(N)throw N}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),n(null),s({title:"Video script saved!"})},onError:v=>s({title:"Error",description:v.message,variant:"destructive"})}),m=async v=>{await V.from("video_scripts").update({is_active:!v.is_active}).eq("id",v.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},x=async v=>{confirm("Delete this video script?")&&(await V.from("video_scripts").delete().eq("id",v),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Video Scripts"}),e.jsx(Nr,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(G,{onClick:()=>{n(null),i(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Pe,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Title"}),e.jsx(Nt,{children:"Category"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"w-24",children:"Actions"})]})}),e.jsx($n,{children:c==null?void 0:c.map(v=>{var w;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:v.title}),e.jsx(dt,{className:"text-muted-foreground",children:((w=v.category)==null?void 0:w.name)||"Uncategorized"}),e.jsx(dt,{children:e.jsx(_r,{checked:v.is_active,onCheckedChange:()=>m(v)})}),e.jsxs(dt,{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>{n(v),i(!0)},children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(v.id),children:e.jsx(yr,{className:"h-4 w-4"})})]})]},v.id)})})]})}),e.jsx(fs,{open:a,onOpenChange:i,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsxs(gs,{children:[r?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault();const w=new FormData(v.currentTarget);h.mutate({id:r==null?void 0:r.id,title:w.get("title"),script_text:w.get("script_text"),category_id:w.get("category_id")||null,tags:w.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",name:"title",defaultValue:r==null?void 0:r.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"category_id",children:"Category"}),e.jsxs(Is,{name:"category_id",defaultValue:(r==null?void 0:r.category_id)||"",children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select category"})}),e.jsx(Ms,{children:l==null?void 0:l.map(v=>e.jsx(ct,{value:v.id,children:v.name},v.id))})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script_text",children:"Script Text"}),e.jsx(or,{id:"script_text",name:"script_text",defaultValue:r==null?void 0:r.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(Ne,{id:"tags",name:"tags",defaultValue:((y=r==null?void 0:r.tags)==null?void 0:y.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(an,{className:"mt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:h.isPending,children:[h.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function y3s(){const{toast:s}=Ma(),[t,r]=k.useState(""),[n,a]=k.useState(!0),[i,l]=k.useState(!1);k.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&r(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await V.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 n?e.jsx(ke,{children:e.jsx(Pe,{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Nr,{children:"Configure the map feature for popbys"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(Ne,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>r(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(G,{onClick:o,disabled:i,children:[i&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Ge,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const v3s=()=>{const[s,t]=k.useState(""),[r,n]=k.useState("grid"),a=br(),{data:i=[],isLoading:l}=mt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await V.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var h;return c.name.toLowerCase().includes(s.toLowerCase())||((h=c.description)==null?void 0:h.toLowerCase().includes(s.toLowerCase()))});return e.jsx(ws,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{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(G,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>n("grid"),className:"rounded-full",children:e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(G,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>n("list"),className:"rounded-full",children:e.jsx(em,{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: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(4)].map((c,d)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(Fs,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Fs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Fs,{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(G,{variant:"outline",onClick:()=>t(""),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(c=>e.jsxs(ke,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${r==="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(jr,{className:"h-8 w-8"})})}),e.jsxs(Pe,{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:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:r8(c.description)})]})]},c.id))})]})})},b3s=()=>{const{serviceId:s}=Ki(),t=br(),{data:r,isLoading:n}=mt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await V.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return n?e.jsx(ws,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(Fs,{className:"h-8 w-48"}),e.jsx(Fs,{className:"h-64 w-full rounded-lg"}),e.jsx(Fs,{className:"h-24 w-full"})]})}):r?e.jsx(ws,{title:r.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:r.preview_image_url?e.jsx("img",{src:r.preview_image_url,alt:r.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(jr,{className:"h-16 w-16"})})})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:r.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(on,{className:"h-4 w-4 mr-1"}),"Published ",_s(new Date(r.publish_date),"MMMM d, yyyy")]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:r.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(G,{size:"lg",className:"gap-2",onClick:()=>window.open(r.signup_link_url,"_blank"),children:[e.jsx(Qr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(ws,{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(G,{onClick:()=>t("/additional-services"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},pD=[{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 _3s(){const[s,t]=k.useState(pD[0].id),r=pD.find(n=>n.id===s)||pD[0];return e.jsx(ws,{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(cA,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),e.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),e.jsx("div",{className:"md:hidden",children:e.jsxs(Is,{value:s,onValueChange:t,children:[e.jsx(As,{className:"w-full",children:e.jsx(Ls,{placeholder:"Select a tool"})}),e.jsx(Ms,{children:pD.map(n=>e.jsx(ct,{value:n.id,children:n.name},n.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(On,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Rn,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:pD.map(n=>e.jsx(Kt,{value:n.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:n.name},n.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:r.iframe}})})]})})}const pUe="agent-os-onboarding-completed",P$=[{icon:lv,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:Ku,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:pr,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:hd,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:ii,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:ro,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"]}],w3s=()=>{const[s,t]=k.useState(!1),[r,n]=k.useState(0),[a,i]=k.useState(!1);k.useEffect(()=>{if(!localStorage.getItem(pUe)){const v=setTimeout(()=>t(!0),500);return()=>clearTimeout(v)}},[]);const l=()=>{r{n(r+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(pUe,"true"),t(!1)},d=P$[r],h=d.icon,m=r===P$.length-1,x=y=>{y||c(),t(y)};return e.jsx(fs,{open:s,onOpenChange:x,children:e.jsxs(ms,{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(h,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),r===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(jr,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(ys,{className:"text-center sm:text-center pb-2",children:[e.jsx(gs,{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(Hr,{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((y,v)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+v*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(Kn,{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:y})]},v))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:P$.map((y,v)=>e.jsx("button",{onClick:()=>{v!==r&&(i(!0),setTimeout(()=>{n(v),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${v===r?"w-8 bg-gradient-to-r "+d.bgGradient:v{const{user:s}=js();return mt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(r)throw r;return t},enabled:!!s})},N3s=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async({contactId:r,days:n})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Vl(new Date,n);await V.from("contact_snoozes").delete().eq("contact_id",r);const{error:i}=await V.from("contact_snoozes").insert({contact_id:r,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"]}),cn({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:r=>{cn({title:"Error snoozing contact",description:r.message,variant:"destructive"})}})},k3s=()=>{const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("contact_snoozes").delete().eq("contact_id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),cn({title:"Snooze cancelled"})},onError:t=>{cn({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},S3s=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function xxe({open:s,onOpenChange:t,contactId:r,contactName:n}){const[a,i]=k.useState(null),l=N3s(),o=async()=>{a&&(await l.mutateAsync({contactId:r,days:a}),i(null),t(!1))},c=d=>_s(Vl(new Date,d),"MMM d, yyyy");return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(fn,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Hr,{children:["Postpone the next scheduled touch for ",n,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:S3s.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:It("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(on,{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(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const C3s={Crown:Zh,FileText:ln,Users:pr,Globe:fc,Star:Xn,Phone:Cn,MessageSquare:xi,PenTool:aj,Video:Jr,Gift:ii};function T3s({actions:s,onMarkComplete:t,onViewScript:r,isLoading:n,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=br(),[c,d]=k.useState("name"),[h,m]=k.useState("asc"),[x,y]=k.useState(null),[v,w]=k.useState(""),b=I=>{c===I?m(D=>D==="asc"?"desc":"asc"):(d(I),m("asc"))},N=k.useMemo(()=>[...s].sort((I,D)=>{var $,F;let R=0;switch(c){case"name":{const z=`${I.contact.first_name} ${I.contact.last_name||""}`.toLowerCase(),Q=`${D.contact.first_name} ${D.contact.last_name||""}`.toLowerCase();R=z.localeCompare(Q);break}case"relationship_type":R=(I.relationshipTypeName||"").localeCompare(D.relationshipTypeName||"");break;case"action_type":R=((($=I.actionType)==null?void 0:$.name)||"").localeCompare(((F=D.actionType)==null?void 0:F.name)||"");break;case"last_touch":R=(I.monthNumber||0)-(D.monthNumber||0);break}return h==="asc"?R:-R}),[s,c,h]),S=I=>C3s[I||"Phone"]||Cn,T=({field:I,children:D})=>e.jsxs(G,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>b(I),children:[D,c===I?h==="asc"?e.jsx(Id,{className:"ml-2 h-4 w-4"}):e.jsx(Hu,{className:"ml-2 h-4 w-4"}):e.jsx(Ad,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(I,D,R)=>{y(I),w(`${D} ${R||""}`.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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/50",children:[e.jsx(Nt,{className:"w-[180px]",children:e.jsx(T,{field:"name",children:"Contact"})}),e.jsx(Nt,{className:"w-[130px]",children:e.jsx(T,{field:"relationship_type",children:"Type"})}),e.jsx(Nt,{className:"w-[120px]",children:e.jsx(T,{field:"action_type",children:"Action"})}),e.jsx(Nt,{className:"w-[130px]",children:"Phone"}),e.jsx(Nt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx($n,{children:N.map((I,D)=>{var K,X,Z,re,le,oe;const R=I.isSpecialDate,$=I.specialDateType,F=R?$==="birthday"?_h:En:S(((K=I.actionType)==null?void 0:K.icon)||null),z=I.contact.phone,Q=I.contact.email;return e.jsxs(Ds,{className:It("hover:bg-muted/50 transition-colors",R&&$==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",R&&$==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(dt,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${I.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[I.contact.first_name," ",I.contact.last_name]})})}),e.jsx(dt,{children:I.relationshipTypeName?e.jsx(Ge,{variant:"secondary",className:"text-xs",children:I.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(dt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:R?e.jsx(Ge,{className:It("gap-1",$==="birthday"&&"bg-pink-500 hover:bg-pink-600",$==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:$==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(_h,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(En,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(F,{className:"h-3 w-3"}),(X=I.actionType)==null?void 0:X.name]})})}),e.jsx(dt,{children:z?e.jsx("span",{className:"text-sm font-mono",children:I.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[z&&e.jsx("a",{href:`tel:${I.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Cn,{className:"h-3.5 w-3.5"})}),z&&e.jsx("a",{href:a(I.contact.phone,(Z=I.script)==null?void 0:Z.script_body,I.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(xi,{className:"h-3.5 w-3.5"})}),Q&&(l?e.jsx("button",{onClick:()=>l({id:I.contact.id,first_name:I.contact.first_name,last_name:I.contact.last_name,email:I.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(I.contact.email,(re=I.script)==null?void 0:re.script_body,(le=I.script)==null?void 0:le.email_subject,(oe=I.actionType)==null?void 0:oe.name,I.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"})})),R&&e.jsxs("button",{onClick:()=>{const ne=`${I.contact.first_name}${I.contact.last_name?" "+I.contact.last_name:""}`,ie=$==="birthday"?"birthday":"home_anniversary",ye=new URLSearchParams({cardType:ie,contactId:I.contact.id,name:ne,...I.contact.address?{address:I.contact.address}:{},...$==="anniversary"&&I.contact.home_anniversary?{date:I.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${ye.toString()}`)},className:It("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",$==="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 ${$==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>A(I.contact.id,I.contact.first_name,I.contact.last_name),title:"Snooze",children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),e.jsxs(G,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ne;return t(I.contact.id,I.actionType.id,(ne=I.script)==null?void 0:ne.id)},disabled:n,children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${I.contact.id}-${D}`)})})]})}),e.jsx(xxe,{open:!!x,onOpenChange:I=>!I&&y(null),contactId:x||"",contactName:v})]})}function E3s({onSelect:s}){const[t,r]=k.useState(null),{data:n=[],isLoading:a}=mt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:c,error:d}=await V.from("email_template_categories").select("*").order("sort_order");if(d)throw d;return c}}),{data:i=[],isLoading:l}=mt({queryKey:["agent-email-templates",t],queryFn:async()=>{let c=V.from("agent_email_templates").select("*").eq("is_active",!0).order("sort_order");t&&(c=c.eq("category_id",t));const{data:d,error:h}=await c;if(h)throw h;return d}}),o=n.find(c=>c.id===t);return a?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>r(null),className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx($o,{className:"h-3.5 w-3.5"}),"Back to categories"]}),e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:o==null?void 0:o.icon})," ",o==null?void 0:o.name]}),l?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(Qa,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:i.map(c=>e.jsxs("button",{onClick:()=>s(c),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:c.title}),c.tone&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] shrink-0",children:c.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:c.subject})]},c.id))})})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-2",children:"Select a category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:n.map(c=>e.jsxs("button",{onClick:()=>r(c.id),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:c.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:c.name}),c.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:c.description})]})]}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},c.id))})]})}function gxe(){const{user:s}=js(),t=Xt(),{data:r,isLoading:n}=mt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:h}=await V.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(h)throw h;return d},enabled:!!(s!=null&&s.id)}),a=Ct({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:h,error:m}=await V.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ue.success("Connect page created!")},onError:d=>{var h;(h=d.message)!=null&&h.includes("duplicate")?ue.error("That slug is already taken. Try another."):ue.error("Failed to create page")}}),i=Ct({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page");const{error:h}=await V.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",r.id);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ue.success("Page updated!")},onError:()=>ue.error("Failed to update page")}),{data:l=[],isLoading:o}=mt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:h}=await V.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(h)throw h;return d},enabled:!!(s!=null&&s.id)}),c=Ct({mutationFn:async d=>{if(!(r!=null&&r.id))throw new Error("No intake page. Create your Connect page first.");const{data:h,error:m}=await V.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:r.id}).select("token").single();if(m)throw m;return`${window.location.origin}/connect/${r.slug}?t=${h.token}`}});return{intakePage:r,isLoading:n,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function A3s({value:s,onChange:t,userId:r,placeholder:n}){const[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(!1),[h,m]=k.useState(0),x=k.useRef(null),y=k.useRef(null);k.useEffect(()=>{const w=b=>{x.current&&!x.current.contains(b.target)&&i(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]),k.useEffect(()=>{y.current&&clearTimeout(y.current);const w=s.trim();if(!r||w.length<1||w.includes("@")&&w.indexOf("@")>0&&/\S+@\S+\.\S+/.test(w)){o([]);return}return y.current=setTimeout(async()=>{d(!0);const b=`%${w}%`,N=V,{data:S,error:T}=await N.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r).not("email","is",null).or(`first_name.ilike.${b},last_name.ilike.${b},email.ilike.${b}`).order("first_name",{ascending:!0}).limit(8);d(!1),!T&&S&&(o(S),m(0),i(S.length>0))},180),()=>{y.current&&clearTimeout(y.current)}},[s,r]);const v=w=>{w.email&&(t(w.email),i(!1))};return e.jsxs("div",{ref:x,className:"relative",children:[e.jsx(Ne,{id:"gmail-to",value:s,onChange:w=>t(w.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:w=>{!a||l.length===0||(w.key==="ArrowDown"?(w.preventDefault(),m(b=>Math.min(b+1,l.length-1))):w.key==="ArrowUp"?(w.preventDefault(),m(b=>Math.max(b-1,0))):w.key==="Enter"?(w.preventDefault(),v(l[h])):w.key==="Escape"&&i(!1))},placeholder:n||"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(es,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((w,b)=>{const N=[w.first_name,w.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>m(b),onClick:()=>v(w),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${b===h?"bg-accent":"bg-popover"}`,children:[e.jsx(Di,{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:N}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:w.email})]})]},w.id)})})]})}const M3s=5*1024*1024,L1=50,I3s=["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 L3s(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function P3s(s){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>{const a=n.result;t(a.split(",")[1])},n.onerror=r,n.readAsDataURL(s)})}function B_(s,t){let r=s.replace(/\{\{first_name\}\}/gi,t.first_name).replace(/\{\{last_name\}\}/gi,t.last_name||"").replace(/\{\{full_name\}\}/gi,`${t.first_name} ${t.last_name||""}`.trim());return t.updateLink&&(r=r.replace(/\{\{update_link\}\}/gi,t.updateLink)),r}function $v({open:s,onOpenChange:t,contact:r,bulkContacts:n,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o}){const{user:c}=js(),d=Xt(),{isReady:h,settings:m}=OB(),{intakePage:x}=gxe(),y=x?`https://contacts.relevelup.com/${x.slug}`:null,v=!!n&&n.length>0,w=h&&(v||!l),b=v?n:r?[r]:[],N=b[0],S=v?Math.ceil(b.length/L1):1,T=v&&b.length>L1,[A,I]=k.useState((N==null?void 0:N.email)||""),[D,R]=k.useState(a),[$,F]=k.useState(i),[z,Q]=k.useState(!1),[K,X]=k.useState(!1),[Z,re]=k.useState([]),[le,oe]=k.useState(a),[ne,ie]=k.useState(i),[ye,ce]=k.useState("composing"),[ve,be]=k.useState(0),[Ue,Be]=k.useState(0),[De,Ae]=k.useState(0),[He,Le]=k.useState(0),Ie=k.useRef(!1),[Te,xe]=k.useState(null);k.useEffect(()=>{s&&(I((N==null?void 0:N.email)||""),oe(a),ie(i),R(B_(a,N||{first_name:""})),F(B_(i,N||{first_name:""})),X(!a&&!i),re([]),ce("composing"),be(0),Be(0),Ae(0),Le(0),Ie.current=!1,xe(null))},[s,N,a,i]);const et=async Xe=>{const Je=Xe.target.files;if(!Je)return;const jt=Z.reduce((Ns,Ys)=>Ns+Ys.size,0),ns=[];for(const Ns of Array.from(Je)){if(!I3s.includes(Ns.type)){ue.error(`${Ns.name}: Unsupported file type`);continue}if(jt+Ns.size>M3s){ue.error("Total attachments exceed 5MB limit");break}try{const Ys=await P3s(Ns);ns.push({name:Ns.name,type:Ns.type,size:Ns.size,data:Ys})}catch{ue.error(`Failed to read ${Ns.name}`)}}re(Ns=>[...Ns,...ns]),Xe.target.value=""},fe=Xe=>{re(Je=>Je.filter((jt,ns)=>ns!==Xe))},it=Xe=>{oe(Xe.subject),ie(Xe.body),R(B_(Xe.subject,N||{first_name:""})),F(B_(Xe.body,N||{first_name:""})),X(!1)},Oe=Xe=>Xe.split(/\n\n+/).map(Je=>`

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

`).join(""),Ye=async Xe=>{if(!(Xe!=null&&Xe.email))return ue.error("Please enter a recipient email"),!1;const Je=Xe||{first_name:""},jt=B_(le,Je),ns=B_(ne,Je),Ns=Oe(ns);try{if(w){const Ys=(m==null?void 0:m.display_name)||"ReLevelUp",rs=`${Ys.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,bt=`${Ys} <${rs}>`,{data:cs,error:yt}=await V.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:Xe.email,from_email:bt,subject:jt,body_html:Ns,reply_to:(m==null?void 0:m.reply_to_email)||void 0}});if(yt)throw yt;if(!(cs!=null&&cs.success))throw new Error((cs==null?void 0:cs.error)||"Failed to send")}else{const{data:Ys,error:rs}=await V.functions.invoke("gmail-send",{body:{to:Xe.email,subject:jt,body:Ns,contactId:Xe.id||void 0,attachments:Z.map(({name:bt,type:cs,data:yt})=>({name:bt,type:cs,data:yt}))}});if(rs)throw rs;if(!(Ys!=null&&Ys.success))throw new Error((Ys==null?void 0:Ys.error)||"Failed to send")}return c&&Xe.id&&await V.from("bulk_email_sends").insert({user_id:c.id,contact_id:Xe.id,contact_email:Xe.email,subject:jt,source:w?"ses_bulk":"sphere_gaps"}),!0}catch(Ys){return console.error("Send error:",Ys),ue.error("Failed to send to "+Xe.first_name+": "+(Ys instanceof Error?Ys.message:"Unknown error")),!1}},We=()=>{const Xe=ve*L1;return b.slice(Xe,Xe+L1)},_e=async()=>{if(!D||!$){ue.error("Please fill in subject and message");return}const Xe=We();Q(!0),ce("sending");let Je=0,jt=0;for(let Ns=0;NssetTimeout(rs,150));Be(Ns=>Ns+Je),Ae(Ns=>Ns+jt),Q(!1),d.invalidateQueries({queryKey:["bulk-email-sends"]}),ve>=S-1||Ie.current?ce("all_done"):ce("batch_complete")},Re=async()=>{if(!D||!$){ue.error("Please fill in subject and message");return}if(!v){const Xe=N||{id:"",first_name:"",last_name:"",email:A.trim()};if(!Xe.email){ue.error("Please enter a recipient email");return}Q(!0);try{await Ye(Xe)&&(d.invalidateQueries({queryKey:["bulk-email-sends"]}),ue.success("Email sent successfully!"),t(!1),o==null||o())}finally{Q(!1)}return}await _e()},tt=async()=>{be(Xe=>Xe+1),Le(0),await new Promise(Xe=>setTimeout(Xe,50)),await _e()};k.useEffect(()=>{},[ve]);const Ke=()=>{if(z){Ie.current=!0;return}t(!1),o==null||o()},Ze=ve*L1,lt=Math.min(Ze+L1,b.length),xt=v&&b.length>0?Math.round((Ue+De)/b.length*100):0;return e.jsx(fs,{open:s,onOpenChange:Ke,children:e.jsxs(ms,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:`h-5 w-5 ${w?"text-orange-500":"text-red-500"}`}),v?`Send to ${b.length} Contacts`:"Compose Email"]}),w?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",m==null?void 0:m.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,v&&ye==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[b.length," contacts"]}),". You'll review each personalized email before sending."]})]}),ye==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(es,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",ve+1," of ",S,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[He," of ",We().length," in this batch"]})]}),e.jsx(ei,{value:He/We().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Ue+De," / ",b.length]}),e.jsxs("span",{children:[Ue," sent • ",De," failed"]})]}),e.jsx(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ie.current=!0},children:"Stop Sending"})]}),ye==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(In,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",ve+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ue," sent, ",De," failed so far"]})]}),e.jsx(ei,{value:xt,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[b.length-Ue-De," contacts remaining (",S-ve-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",className:"flex-1",onClick:Ke,children:"Done for Now"}),e.jsxs(G,{className:"flex-1 gap-2",onClick:tt,children:[e.jsx(en,{className:"h-4 w-4"}),"Send Next ",Math.min(L1,b.length-lt)," Contacts"]})]})]}),ye==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(In,{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:[Ue," emails sent successfully",De>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",De," failed"]})]})]}),e.jsx(G,{className:"w-full",onClick:Ke,children:"Close"})]}),ye==="composing"&&e.jsxs("div",{className:"space-y-4",children:[K?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(ln,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>X(!1),className:"h-7 px-2 text-xs",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(E3s,{onSelect:it})]}):e.jsxs(G,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>X(!0),children:[e.jsx(ln,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(fo,{}),!v&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"gmail-to",children:"To"}),e.jsx(A3s,{value:A,onChange:I,userId:c==null?void 0:c.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(Ne,{id:"gmail-subject",value:D,onChange:Xe=>{R(Xe.target.value),oe(Xe.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(he,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{F(Xe=>Xe+"{{first_name}}"),ie(Xe=>Xe+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Ge,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{F(Xe=>Xe+"{{last_name}}"),ie(Xe=>Xe+"{{last_name}}")},children:"{{last_name}}"}),y&&e.jsx(Ge,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Xe=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${y} `;F(Je=>Je+Xe),ie(Je=>Je+Xe)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(or,{id:"gmail-body",value:$,onChange:Xe=>{F(Xe.target.value),ie(Xe.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),v&&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(G,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var Xe;return(Xe=document.getElementById("gmail-attachments"))==null?void 0:Xe.click()},disabled:z,children:[e.jsx(nj,{className:"h-4 w-4"}),"Attach Files"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"PDF, images, Word, Excel (max 5MB 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:et})]}),Z.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Z.map((Xe,Je)=>e.jsxs(Ge,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(nj,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Xe.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",L3s(Xe.size),")"]}),e.jsx("button",{type:"button",onClick:()=>fe(Je),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(vr,{className:"h-3 w-3"})})]},Je))})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),v?e.jsxs(G,{onClick:()=>{xe(b[0]||null),ce("reviewing")},disabled:!D||!$,className:"gap-2",children:["Review Emails",e.jsx(Ha,{className:"h-4 w-4"})]}):e.jsxs(G,{onClick:Re,disabled:z||!D||!$||!A.trim(),className:"gap-2",children:[z?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),z?"Sending...":"Send Email"]})]})]}),ye==="reviewing"&&v&&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."]}),T&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",b.length," contacts will be sent in ",S," batches of up to ",L1,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{children:["Recipients (",b.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:b.map(Xe=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(Te==null?void 0:Te.id)===Xe.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>xe(Xe),children:[Xe.first_name," ",Xe.last_name," — ",Xe.email]},Xe.id))})]}),Te&&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 ",Te.first_name," ",Te.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:"})," ",Te.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",B_(le,Te)]})]}),e.jsx(fo,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:B_(ne,Te)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>{ce("composing"),xe(null)},children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(G,{onClick:Re,disabled:z,className:"gap-2",children:[z?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),T?`Send First ${L1}`:`Send to ${b.length}`]})]})]})]})})}function D3s(){const s=br(),{data:t}=Sm(),{data:r}=uB(),n=qfe(),{isGmailConnected:a,gmailEmail:i}=Eh(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(new Set),x=yf(new Date),y=Vl(x,30),v=A=>{if(!A)return null;const I=A.split(/[-/T]/);if(I.length<3)return null;const D=parseInt(I[1],10)-1,R=parseInt(I[2],10);return isNaN(D)||isNaN(R)?null:new Date(x.getFullYear(),D,R)},w=k.useMemo(()=>{if(!t)return[];const A=[];for(const I of t){if(I.birthday){const D=v(I.birthday);D&&(Ol(D,x)||M3(D,x)&&I3(D,y))&&A.push({contact:I,type:"birthday",date:D,daysUntil:$p(D,x),dateStr:I.birthday})}if(I.home_anniversary){const D=v(I.home_anniversary);D&&(Ol(D,x)||M3(D,x)&&I3(D,y))&&A.push({contact:I,type:"anniversary",date:D,daysUntil:$p(D,x),dateStr:I.home_anniversary})}}return A.sort((I,D)=>I.daysUntil-D.daysUntil),A},[t]),b=async A=>{const I=(r==null?void 0:r.find(D=>D.name==="Call"))||(r==null?void 0:r[0]);if(I)try{await n.mutateAsync({contactId:A.contact.id,actionTypeId:I.id,notes:`${A.type==="birthday"?"Birthday":"Home Anniversary"} outreach`}),m(D=>new Set(D).add(`${A.contact.id}-${A.type}`)),cn({title:"Touch logged!",description:`Logged outreach for ${A.contact.first_name}`})}catch{cn({title:"Error",description:"Failed to log touch",variant:"destructive"})}},N=A=>{const I=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,D=A.type==="birthday"?"birthday":"home_anniversary",R=new URLSearchParams({cardType:D,contactId:A.contact.id,name:I,...A.contact.address?{address:A.contact.address}:{},...A.type==="anniversary"&&A.dateStr?{date:A.dateStr}:{}});s(`/mission-control/card-studio?${R.toString()}`)},S=A=>A===0?"Today!":A===1?"Tomorrow":`${A} days`,T=A=>A===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":A<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":A<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(hd,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Ge,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[w.length," event",w.length!==1?"s":""]})]})}),e.jsxs(Pe,{className:"space-y-2",children:[w.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_h,{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."})]}),w.map((A,I)=>{var F,z;const D=`${A.contact.id}-${A.type}`,R=h.has(D),$=`${((F=A.contact.first_name)==null?void 0:F[0])||""}${((z=A.contact.last_name)==null?void 0:z[0])||""}`.toUpperCase();return e.jsxs("div",{className:It("p-3 rounded-lg border transition-colors",A.daysUntil===0&&A.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":A.daysUntil===0&&A.type==="anniversary"?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":A.type==="birthday"?"bg-pink-50/60 border-pink-200/60 hover:bg-pink-100/60 dark:bg-pink-950/20 dark:border-pink-900/30 dark:hover:bg-pink-950/30":"bg-blue-50/60 border-blue-200/60 hover:bg-blue-100/60 dark:bg-blue-950/20 dark:border-blue-900/30 dark:hover:bg-blue-950/30"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(Nn,{className:It("h-10 w-10",A.type==="birthday"?"ring-2 ring-pink-300/50 dark:ring-pink-700/50":"ring-2 ring-blue-300/50 dark:ring-blue-700/50"),children:e.jsx(kn,{className:It("text-xs font-medium",A.type==="birthday"?"bg-pink-100 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300":"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"),children:$})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:A.type==="birthday"?"🎂":"🏠"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[A.contact.first_name," ",A.contact.last_name||""]}),e.jsx(Ge,{variant:"outline",className:It("text-[10px] shrink-0 whitespace-nowrap",T(A.daysUntil)),children:S(A.daysUntil)})]}),e.jsxs("div",{className:It("text-xs flex items-center gap-1.5 mt-0.5",A.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[A.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(_h,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(En,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:_s(A.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[A.contact.phone&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${A.contact.phone}`,children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})}),A.contact.phone&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${A.contact.phone}`,children:e.jsx(xi,{className:"h-3.5 w-3.5"})})}),A.contact.email&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.contact.email}),d(!0)):window.location.href=`mailto:${A.contact.email}`},children:e.jsx(Vs,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${A.contact.id}`),children:e.jsx(Jr,{className:"h-3.5 w-3.5"})}),e.jsxs(G,{variant:"ghost",size:"sm",className:It("h-7 px-2 gap-1 text-xs",A.type==="birthday"?"text-pink-600 hover:text-pink-700 dark:text-pink-400":"text-blue-600 hover:text-blue-700 dark:text-blue-400"),title:`Send ${A.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>N(A),children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(G,{variant:"ghost",size:"icon",className:It("h-7 w-7",R&&"text-green-600"),title:"Log a touch",disabled:R||n.isPending,onClick:()=>b(A),children:e.jsx(In,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${A.contact.id}`),children:e.jsx(bn,{className:"h-3.5 w-3.5"})})]})]},`${D}-${I}`)})]})]}),a&&l&&e.jsx($v,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function R3s(s){const[t,r]=k.useState([]),[n,a]=k.useState(!1),{data:i,isLoading:l}=mt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await V.rpc("cleanup_stale_visitors")}catch{}const{data:h}=await V.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(!h)return[];const m=h.map(v=>v.contact_id).filter(Boolean);let x={};if(m.length>0){const{data:v}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",m);(v||[]).forEach(w=>{x[w.id]=w})}const y=h.map(v=>v.auth_user_id).filter(Boolean);if(y.length>0){const{data:v}=await V.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",y);(v||[]).forEach(w=>{const b=h.find(N=>N.auth_user_id===w.user_id);b&&!b.contact_id&&w.contact_id&&(b.contact_id=w.contact_id),b&&!x[b.contact_id||""]&&w.name&&(x[b.contact_id||b.auth_user_id||""]={first_name:w.name.split(" ")[0],last_name:w.name.split(" ").slice(1).join(" ")||null,email:null,phone:w.phone})})}return h.map(v=>{var w,b;return{...v,contact_name:x[v.contact_id||v.auth_user_id||""]?`${x[v.contact_id||v.auth_user_id||""].first_name} ${x[v.contact_id||v.auth_user_id||""].last_name||""}`.trim():null,contact_email:((w=x[v.contact_id||v.auth_user_id||""])==null?void 0:w.email)||null,contact_phone:((b=x[v.contact_id||v.auth_user_id||""])==null?void 0:b.phone)||null}})},enabled:!!s,refetchInterval:6e4});k.useEffect(()=>{if(!s)return;const h=V.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},m=>{m.eventType==="INSERT"?r(x=>x.find(v=>v.id===m.new.id)?x:[m.new,...x]):m.eventType==="UPDATE"?r(x=>x.map(y=>y.id===m.new.id?{...y,...m.new}:y)):m.eventType==="DELETE"&&r(x=>x.filter(y=>y.id!==m.old.id))}).subscribe(m=>{m==="SUBSCRIBED"&&a(!0)});return()=>{V.removeChannel(h)}},[s]);const o=n&&t.length>0?O3s([...t,...i||[]]):i||[],c=Date.now(),d=o.filter(h=>c-new Date(h.last_seen_at).getTime()<2*60*1e3);return{activeVisitors:d,isLoading:l,count:d.length}}function O3s(s){const t=new Set;return s.filter(r=>t.has(r.id)?!1:(t.add(r.id),!0))}const F3s={property_view:{label:"Viewed",icon:bn,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:sl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:ci,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function B3s(){const{user:s}=js(),t=br(),{isGmailConnected:r,gmailEmail:n}=Eh(),{leadSite:a}=_g(),{count:i}=R3s(a==null?void 0:a.id),[l,o]=k.useState(!1),[c,d]=k.useState(null),{data:h,isLoading:m}=mt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:N,error:S}=await V.rpc("get_lead_site_activity",{_user_id:s.id});if(S)throw S;return N},enabled:!!s,refetchInterval:6e4});if(m||!(h!=null&&h.has_site))return null;const x=(h.activities||[]).filter(N=>N.visitor_name&&N.visitor_name!=="Site Visitor"),y=x.filter(N=>N.activity_type==="new_lead"),v=(h.activities||[]).filter(N=>N.activity_type==="property_view").length,w=(h.activities||[]).filter(N=>N.activity_type==="saved_listing").length,b=N=>{if(N.visitor_email)if(r){const S=(N.visitor_name||"").split(" ");d({id:N.contact_id||"",first_name:S[0]||"",last_name:S.slice(1).join(" ")||null,email:N.visitor_email}),o(!0)}else window.location.href=`mailto:${N.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(fc,{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(G,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(Ha,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-emerald-500/5 border border-emerald-200 dark:border-emerald-800",children:[e.jsx(sl,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:y.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(bn,{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:v}),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(ci,{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:w}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),x.length>0?e.jsxs("div",{className:"space-y-2",children:[x.slice(0,5).map((N,S)=>{const T=F3s[N.activity_type],A=T.icon,I=rl(new Date(N.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 ${T.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${T.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:()=>{N.contact_id&&t(`/mission-control/contacts/${N.contact_id}`)},children:N.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:T.label}),N.mls_number&&e.jsxs("span",{children:["· MLS# ",N.mls_number]}),N.lead_type&&e.jsxs("span",{children:["· ",N.lead_type]}),e.jsxs("span",{children:["· ",I]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[N.visitor_email&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>b(N),children:e.jsx(Vs,{className:"h-3.5 w-3.5"})}),N.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${N.visitor_phone}`,children:e.jsx(Cn,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${N.visitor_phone}`,children:e.jsx(xi,{className:"h-3.5 w-3.5"})})]}),N.contact_id&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${N.contact_id}`),children:e.jsx(va,{className:"h-3.5 w-3.5"})})]})]},`${N.activity_type}-${N.occurred_at}-${S}`)}),x.length>5&&e.jsxs(G,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",x.length-5," more activities",e.jsx(Ha,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 text-center",children:[e.jsx(vh,{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:v>0?`${v} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(G,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Ha,{className:"h-3.5 w-3.5 ml-1"})]})]})}),r&&c&&e.jsx($v,{open:l,onOpenChange:o,contact:c,gmailEmail:n})]})}const xUe={Crown:Zh,FileText:ln,Users:pr,Globe:fc,Star:Xn,Phone:Cn,MessageSquare:xi,PenTool:aj,Video:Jr,Gift:ii},z3s={"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 $3s(){var Re,tt,Ke,Ze,lt,xt;const s=br(),{user:t}=js(),{data:r}=fx(),{data:n}=Zrt(),{data:a}=Sm(),{data:i}=uB(),{data:l}=tnt(),o=a$t(),c=o3e(),d=r$t(90),h=qfe(),[m,x]=k.useState(null),[y,v]=k.useState(null),[w,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState(!1),[I,D]=k.useState(""),[R,$]=k.useState(Wde()),[F,z]=k.useState("cards"),[Q,K]=k.useState(!1),[X,Z]=k.useState(null),[re,le]=k.useState(null),[oe,ne]=k.useState(""),{isGmailConnected:ie,gmailEmail:ye}=Eh(),ce=()=>{const Xe=parseInt(I,10);if(isNaN(Xe)||Xe<1){cn({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}$(Xe),ent(Xe),A(!1),cn({title:"Goal updated",description:`Weekly touch goal set to ${Xe}`})},ve=()=>{D(R.toString()),A(!0)};k.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:Je}=await V.from("profiles").select("name").eq("id",t.id).single();Je!=null&&Je.name&&S(Je.name.split(" ")[0])})()},[t==null?void 0:t.id]),k.useEffect(()=>{o.mutate()},[]);const be=yf(new Date),Ue=Vl(be,7),Be=Xe=>{if(!Xe)return null;const Je=Xe.split(/[-/T]/);if(Je.length<3)return null;const jt=parseInt(Je[1],10)-1,ns=parseInt(Je[2],10);return isNaN(jt)||isNaN(ns)?null:new Date(be.getFullYear(),jt,ns)},De=(a==null?void 0:a.filter(Xe=>{const Je=Be(Xe.birthday),jt=Be(Xe.home_anniversary);return Je&&Ol(Je,be)||jt&&Ol(jt,be)}))||[];a!=null&&a.filter(Xe=>{if(!Xe.birthday&&!Xe.home_anniversary)return!1;const Je=jt=>{if(!jt)return!1;const ns=Be(jt);return ns?M3(ns,be)&&I3(ns,Ue):!1};return Je(Xe.birthday)||Je(Xe.home_anniversary)}).slice(0,5);const Ae=[],He=(i==null?void 0:i.find(Xe=>Xe.name==="Call"))||(i==null?void 0:i[0]);for(const Xe of De){const Je=Be(Xe.birthday),jt=Be(Xe.home_anniversary),ns=Je&&Ol(Je,be),Ns=jt&&Ol(jt,be);ns&&Ae.push({contact:Xe,actionType:He||{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:((Ke=(tt=(Re=Xe.tags)==null?void 0:Re[0])==null?void 0:tt.relationship_type)==null?void 0:Ke.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Ns&&Ae.push({contact:Xe,actionType:He||{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:((xt=(lt=(Ze=Xe.tags)==null?void 0:Ze[0])==null?void 0:lt.relationship_type)==null?void 0:xt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Ie=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Xe,Je)=>{var ns,Ns,Ys;const jt=i==null?void 0:i[Je%((i==null?void 0:i.length)||1)];return jt?{contact:Xe,actionType:jt,planName:"Quick Touch",relationshipTypeName:((Ys=(Ns=(ns=Xe.tags)==null?void 0:ns[0])==null?void 0:Ns.relationship_type)==null?void 0:Ys.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Te=[...Ae,...Ie],xe=async(Xe,Je,jt)=>{await h.mutateAsync({contactId:Xe,actionTypeId:Je,scriptUsedId:jt}),b(!1),v(null)},et=Xe=>{Xe.script?(v(Xe),b(!0)):xe(Xe.contact.id,Xe.actionType.id)},fe=Xe=>xUe[Xe||"Phone"]||Cn,it=Xe=>xUe[Xe||"Users"]||pr,Oe=(Xe,Je)=>Xe.replace(/\{\{FirstName\}\}/g,Je.first_name).replace(/\{\{LastName\}\}/g,Je.last_name||"").replace(/\{\{AgentName\}\}/g,N||"there"),Ye=(Xe,Je)=>({Call:`Thinking of you, ${Je}!`,Text:`Quick hello, ${Je}`,Email:`Checking in, ${Je}`,"Handwritten Note":`A note for ${Je}`,Video:`Video message for ${Je}`,Gift:`Something special for you, ${Je}`})[Xe]||`Hello ${Je}!`,We=(Xe,Je,jt)=>{const ns=`sms:${Xe}`;if(Je&&jt){const Ns=Oe(Je,jt);return`${ns}?body=${encodeURIComponent(Ns)}`}return ns},_e=(Xe,Je,jt,ns,Ns)=>{const Ys=`mailto:${Xe}`,rs=[];if(Ns){const bt=jt||Ye(ns||"Email",Ns.first_name);if(rs.push(`subject=${encodeURIComponent(bt)}`),Je){const cs=Oe(Je,Ns);rs.push(`body=${encodeURIComponent(cs)}`)}}return rs.length>0?`${Ys}?${rs.join("&")}`:Ys};return e.jsxs(e.Fragment,{children:[e.jsxs(ws,{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(B3s,{}),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:r==null?void 0:r.filter(Xe=>Xe.active).map(Xe=>{const Je=it(Xe.icon),jt=(n==null?void 0:n[Xe.id])||0,ns=m===Xe.id,Ns=z3s[Xe.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{ns?(x(null),s("/mission-control/contacts")):(x(Xe.id),s(`/mission-control/contacts?type=${Xe.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${ns?Ns:"bg-card hover:bg-accent"} `,children:[e.jsx(Je,{className:"h-5 w-5"}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:Xe.name}),e.jsxs("div",{className:`text-sm ${ns?"opacity-90":"text-muted-foreground"}`,children:[jt," Contacts"]})]})]},Xe.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs(G,{onClick:()=>s("/mission-control/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(gh,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),e.jsxs(G,{onClick:()=>s("/mission-control/contacts"),className:"w-full",variant:"outline",children:["View Contacts",e.jsx(va,{className:"h-4 w-4 ml-1"})]}),e.jsx(G,{variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"w-full",children:"Video Library"}),e.jsx(G,{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(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(jr,{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(G,{variant:F==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("cards"),title:"Card view",children:e.jsx(xf,{className:"h-4 w-4"})}),e.jsx(G,{variant:F==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("table"),title:"Table view",children:e.jsx(em,{className:"h-4 w-4"})})]})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:Te.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(G,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):F==="table"?e.jsx(T3s,{actions:Te,onMarkComplete:xe,onViewScript:et,isLoading:h.isPending,buildSmsLink:We,buildEmailLink:_e,onGmailCompose:ie?Xe=>{Z(Xe),K(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Te.map((Xe,Je)=>{var yt,is,Bs,ps,lr,kr,Lr;const jt=Xe.isSpecialDate,ns=Xe.specialDateType,Ns=jt?ns==="birthday"?_h:En:fe(((yt=Xe.actionType)==null?void 0:yt.icon)||null),Ys=Xe.contact.phone,rs=Xe.contact.email,bt=jt?ns==="birthday"?"#EC4899":"#8B5CF6":((is=Xe.actionType)==null?void 0:is.color)||"#3B82F6",cs=jt?ns==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Bs=Xe.actionType)==null?void 0:Bs.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${jt?"ring-2 ring-offset-2":""}`,style:jt?{"--tw-ring-color":bt}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:bt},children:[e.jsx(Ns,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:cs})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Xe.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Xe.contact.first_name," ",Xe.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[Ys&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Xe.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(Cn,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:We(Xe.contact.phone,(ps=Xe.script)==null?void 0:ps.script_body,Xe.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(xi,{className:"h-3 w-3"}),"Text"]})]}),rs&&(ie?e.jsxs("button",{onClick:()=>{Z({id:Xe.contact.id,first_name:Xe.contact.first_name,last_name:Xe.contact.last_name,email:Xe.contact.email}),K(!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:_e(Xe.contact.email,(lr=Xe.script)==null?void 0:lr.script_body,(kr=Xe.script)==null?void 0:kr.email_subject,(Lr=Xe.actionType)==null?void 0:Lr.name,Xe.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"]}))]}),jt&&e.jsxs("button",{onClick:()=>{const qr=`${Xe.contact.first_name}${Xe.contact.last_name?" "+Xe.contact.last_name:""}`,Ur=ns==="birthday"?"birthday":"home_anniversary",Mr=new URLSearchParams({cardType:Ur,contactId:Xe.contact.id,name:qr,...Xe.contact.address?{address:Xe.contact.address}:{},...ns==="anniversary"&&Xe.contact.home_anniversary?{date:Xe.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Mr.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 ",ns==="birthday"?"Birthday":"Anniversary"," Card"]}),!Ys&&!rs&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Xe.relationshipTypeName&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:Xe.relationshipTypeName}),Xe.monthNumber>0&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:["Month ",Xe.monthNumber]})]}),Xe.script&&e.jsx(G,{size:"sm",variant:"outline",className:"w-full",onClick:()=>et(Xe),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{le(Xe.contact.id),ne(`${Xe.contact.first_name} ${Xe.contact.last_name||""}`.trim())},children:[e.jsx(tm,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(G,{size:"sm",className:"flex-1",onClick:()=>{var qr;return xe(Xe.contact.id,Xe.actionType.id,(qr=Xe.script)==null?void 0:qr.id)},disabled:h.isPending,children:"Mark Complete"})]})]})]},Xe.contact.id+Je)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Lp,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(xd,{children:e.jsx(Pa,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"text-lg",children:"Momentum"}),e.jsxs(fs,{open:T,onOpenChange:A,children:[e.jsx(vi,{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(oo,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),e.jsxs(ms,{className:"sm:max-w-[360px]",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Set Weekly Goal"}),e.jsx(Hr,{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(he,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(Ne,{id:"weekly-goal-ic",type:"number",min:"1",value:I,onChange:Xe=>D(Xe.target.value),placeholder:"20",onKeyDown:Xe=>{Xe.key==="Enter"&&ce()}})]}),e.jsx(G,{onClick:ce,className:"w-full",children:"Save Goal"})]})]})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(ei,{value:Math.min(c.actionsThisWeek/R*100,100),className:"h-3 w-full max-w-full"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(mc,{className:"h-5 w-5 text-orange-500"}),e.jsxs("span",{className:"font-medium",children:[c.actionsThisWeek," / ",R]}),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(fn,{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(va,{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(xnt,{}),e.jsx(D3s,{})]})]}),e.jsx(fs,{open:w,onOpenChange:b,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{className:"flex items-center gap-2",children:y&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:y.actionType.color||"#3B82F6"}}),y.actionType.name," Script"]})})}),y&&y.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:[y.contact.first_name," ",y.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:Oe(y.script.script_body,y.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",className:"flex-1",onClick:()=>b(!1),children:"Close"}),e.jsx(G,{className:"flex-1",onClick:()=>{var Xe;return xe(y.contact.id,y.actionType.id,(Xe=y.script)==null?void 0:Xe.id)},disabled:h.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(w3s,{})]}),ie&&X&&e.jsx($v,{open:Q,onOpenChange:K,contact:X,gmailEmail:ye}),e.jsx(xxe,{open:!!re,onOpenChange:Xe=>!Xe&&le(null),contactId:re||"",contactName:oe})]})}const U3s=[{value:"bidirectional",label:"Two-Way",icon:Ad,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Id,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:Hu,tooltip:"Only pull BoldTrail → Agent OS"}];function dke({value:s,onChange:t,size:r="default"}){const n=r==="sm"?"text-xs":"text-sm";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:`font-medium ${n} text-muted-foreground`,children:"Sync Direction"}),e.jsx(ATe,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:U3s.map(a=>e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsxs(Whe,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${n} 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:r==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Gl,{children:a.tooltip})]},a.value))})]})}function gUe(){const s=Xt(),[t,r]=k.useState(!1),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),[y,v]=k.useState(0),w=k.useRef(!1),{data:b}=mt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:F,error:z}=await V.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(z)throw z;return F}}),N=(b==null?void 0:b.sync_direction)||"bidirectional",S=d??N,T=Ct({mutationFn:async()=>{const{data:F,error:z}=await V.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=>{h(null),a(F),r(!0)},onError:F=>{ue.error(F.message||"Failed to generate sync preview")}}),A=Ct({mutationFn:async()=>{w.current=!1,x("Initializing sync..."),v(5);const{data:F,error:z}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:S}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);const Q=F;let K=Q.sync_log_id,X=Q.next_phase,Z=Q.next_offset,re=Q.push_total||0,le=Q.pull_total||0,oe=Q.update_total||0,ne=0,ie=0,ye=0;for(;X!=="finalize"&&!w.current;){const be=re+le+oe;X==="fetch_bt"?x("Fetching BoldTrail contacts..."):X==="analyze"?(x("Analyzing contacts..."),v(15)):X==="push"?(x(`Pushing contacts to BoldTrail... (${ne}/${re})`),v(be>0?ne/be*90:0)):X==="pull"?(x(`Pulling contacts from BoldTrail... (${ie}/${le})`),v(be>0?(re+ie)/be*90:0)):X==="update"&&(x(`Updating existing contacts... (${ye}/${oe})`),v(be>0?(re+le+ye)/be*90:0));const{data:Ue,error:Be}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:X,offset:Z,sync_log_id:K,sync_direction:S}});if(Be)throw Be;if(Ue!=null&&Ue.error)throw new Error(Ue.error);const De=Ue;ne+=De.chunk_pushed||0,ie+=De.chunk_pulled||0,ye+=De.chunk_updated||0,De.push_total!==void 0&&(re=De.push_total||0),De.pull_total!==void 0&&(le=De.pull_total||0),De.update_total!==void 0&&(oe=De.update_total||0),De.progress&&x(De.progress),X=De.next_phase,Z=De.next_offset}x("Finalizing sync..."),v(95);const{data:ce,error:ve}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:K,sync_direction:S}});if(ve)throw ve;return v(100),ce},onSuccess:F=>{x(null),v(0),r(!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`];ue.success(`Sync complete! ${z.join(", ")}.`)},onError:F=>{x(null),v(0),ue.error(F.message||"Sync failed")}});if(!(b!=null&&b.connected))return null;const I=S==="pull_only"?0:(n==null?void 0:n.to_push)??0,D=S==="push_only"?0:(n==null?void 0:n.to_pull)??0,R=(n==null?void 0:n.to_update)??0,$=I>0||D>0||R>0;return e.jsxs(e.Fragment,{children:[e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"icon",onClick:()=>T.mutate(),disabled:T.isPending,className:"shrink-0",children:T.isPending?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx(Ad,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Gl,{children:"Sync with BoldTrail"})]}),e.jsx(fs,{open:t,onOpenChange:F=>{A.isPending||r(F)},children:e.jsxs(ms,{className:"sm:max-w-lg",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Hr,{children:"Review what will happen when you sync your contacts."})]}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(dke,{value:S,onChange:h,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${S==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:I}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Id,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${S==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Hu,{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:R}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(NA,{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:n.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",n.agent_os_total," contacts · BoldTrail: ",n.boldtrail_total," contacts"]}),R>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(NA,{className:"h-3 w-3 inline mr-1"}),R," contacts have missing fields that will be filled from the other system"]}),I>0&&e.jsxs(Gp,{open:i,onOpenChange:l,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Id,{className:"h-3 w-3 text-emerald-600"}),I," contacts to push to BoldTrail"]}),e.jsx(Wi,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(Kp,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.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)),n.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",n.to_push-20," more"]})]})})]}),D>0&&e.jsxs(Gp,{open:o,onOpenChange:c,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hu,{className:"h-3 w-3 text-blue-600"}),D," contacts to pull from BoldTrail"]}),e.jsx(Wi,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(Kp,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[n.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)),n.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",n.to_pull-20," more"]})]})})]}),!$&&!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(ei,{value:y||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:m||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>r(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(G,{onClick:()=>A.mutate(),disabled:A.isPending||!$,className:"gap-2",children:[A.isPending?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx(Ad,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const q3s=()=>{const{user:s}=js();return mt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})},yxe=s=>{const{user:t}=js();return mt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let r=V.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),r=r.gte("completed_at",i.toISOString())}const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})},PTe=()=>{const{user:s}=js();return mt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("relationship_type_popby_defaults").select("*");if(r)throw r;return t},enabled:!!s})},Sht=()=>{const{user:s}=js();return mt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_popby_settings").select("*");if(r)throw r;return t},enabled:!!s})},V3s=()=>{const{data:s}=Sm();fx();const{data:t}=yxe(),{data:r}=Sht(),{data:n}=PTe(),a=new Map;t==null||t.forEach(d=>{const h=a.get(d.contact_id);(!h||new Date(d.completed_at)>new Date(h))&&a.set(d.contact_id,d.completed_at)});const i=new Map;n==null||n.forEach(d=>i.set(d.relationship_type_id,d.frequency_days));const l=new Map;r==null||r.filter(d=>d.is_active).forEach(d=>{l.set(d.contact_id,d.frequency_days)});const o=yf(new Date);return(s||[]).map(d=>{let h=90;if(l.has(d.id))h=l.get(d.id);else if(d.tags&&d.tags.length>0){const w=d.tags.map(b=>i.get(b.relationship_type_id)).filter(b=>b!==void 0);w.length>0&&(h=Math.min(...w))}const m=a.get(d.id)||null,x=m?pg(o,yf(new Date(m))):null,y=x===null||x>=h,v=y&&x!==null?x-h:0;return{...d,lastPopby:m,daysSinceLastPopby:x,frequencyDays:h,isDue:y,daysOverdue:v}}).sort((d,h)=>h.daysOverdue-d.daysOverdue)},Cht=()=>V3s().filter(t=>t.isDue),H3s=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{error:n}=await V.from("popby_items").insert({...r,owner_user_id:t==null?void 0:t.id});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),cn({title:"Popby item created!"})},onError:r=>{cn({title:"Error creating popby item",description:r.message,variant:"destructive"})}})},G3s=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const n=new Date().toISOString(),{error:a}=await V.from("popby_logs").insert({...r,owner_user_id:t==null?void 0:t.id,completed_at:n});if(a)throw a;try{const{data:i}=await V.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await V.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:r.contact_id,action_type_id:i.id,notes:r.notes??"Pop-by logged",completed_at:n})}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"]}),cn({title:"Popby logged!"})},onError:r=>{cn({title:"Error logging popby",description:r.message,variant:"destructive"})}})},W3s=()=>{const s=Xt(),{user:t}=js();return Ct({mutationFn:async r=>{const{error:n}=await V.from("relationship_type_popby_defaults").upsert({...r,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),cn({title:"Frequency updated!"})},onError:r=>{cn({title:"Error updating frequency",description:r.message,variant:"destructive"})}})},K3s=()=>{const{data:s}=yxe(30),t=Cht(),r=new Date;r.setDate(r.getDate()-7);const n=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=r).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:n,thisMonthCount:a,dueCount:t.length}};function Y3s(){const{user:s}=js();return mt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Tht(s){const{data:t}=Y3s(),{data:r}=Sht(),{data:n}=PTe(),{data:a}=j3s();return k.useMemo(()=>{const i=a==null?void 0:a.find(b=>b.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=yf(new Date);if(l&&!I3(l,o))return{nextTouchDate:l,daysUntil:pg(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(b=>b.contact_id===s.id))||[]).sort((b,N)=>new Date(N.completed_at).getTime()-new Date(b.completed_at).getTime())[0],h=d?new Date(d.completed_at):null;let m=90;const x=r==null?void 0:r.find(b=>b.contact_id===s.id&&b.is_active);if(x)m=x.frequency_days;else if(s.tags&&s.tags.length>0){const b=s.tags.map(N=>{const S=n==null?void 0:n.find(T=>T.relationship_type_id===N.relationship_type_id);return S==null?void 0:S.frequency_days}).filter(N=>N!==void 0);b.length>0&&(m=Math.min(...b))}if(!h)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:m,lastTouchDate:null,snoozedUntil:null};const y=Vl(yf(h),m),v=pg(y,o);let w;return v<0?w="overdue":v<=7?w="due-soon":w="on-track",{nextTouchDate:y,daysUntil:v,status:w,frequencyDays:m,lastTouchDate:h,snoozedUntil:null}},[s,t,r,n,a])}function uke({contact:s}){const t=Tht(s),n=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Oi,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:fn,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:In,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:tm,text:`Snoozed until ${_s(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:on,text:"Never touched",className:"border-dashed"}}})(),a=n.icon;return e.jsxs(Ge,{variant:n.variant,className:It("gap-1",n.className),children:[e.jsx(a,{className:"h-3 w-3"}),n.text]})}function Z3s({contact:s,onLogTouch:t,onSnooze:r}){const n=Tht(s),a=k3s(),[i,l]=k.useState(!1),o=()=>{switch(n.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(n.status){case"overdue":return e.jsx(Oi,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(fn,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(In,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(tm,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(on,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(n.status){case"overdue":return`${Math.abs(n.daysUntil)} days overdue`;case"due-soon":return n.daysUntil===0?"Due today!":`Due in ${n.daysUntil} days`;case"on-track":return`On track - ${n.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${n.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},h=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:It("font-medium",o()),children:d()})]}),n.status==="snoozed"&&n.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",_s(n.snoozedUntil,"MMMM d, yyyy")]}),n.status!=="snoozed"&&n.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",_s(n.nextTouchDate,"MMMM d, yyyy")]}),n.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",_s(n.lastTouchDate,"MMM d, yyyy")]}),n.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",n.frequencyDays," days"]}),n.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1",onClick:h,disabled:a.isPending,children:[e.jsx(vr,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(G,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),n.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(G,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(tm,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(n.status==="overdue"||n.status==="due-soon"||n.status==="never-touched")&&t&&e.jsx(G,{size:"sm",className:"flex-1",variant:n.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(xxe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const hbe=768;function gL(){const[s,t]=k.useState(void 0);return k.useEffect(()=>{const r=window.matchMedia(`(max-width: ${hbe-1}px)`),n=()=>{t(window.innerWidthr.removeEventListener("change",n)},[]),!!s}function X3s(){const{user:s}=js(),{hasLeadSite:t,leadSite:r}=_g(),{data:n,isLoading:a}=mt({queryKey:["website-active-contacts",s==null?void 0:s.id,r==null?void 0:r.id],queryFn:async()=>{if(!r)return new Set;const{data:i}=await V.from("lead_site_visitors").select("contact_id").eq("lead_site_id",r.id).not("contact_id","is",null),{data:l}=await V.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",r.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:n??new Set,hasLeadSite:t,isLoading:a}}const Q3s={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"}},J3s={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 LO({score:s,showScore:t=!1,showTooltip:r=!0,size:n="sm",className:a}){const i=Q3s[s.status],l=J3s[n],o=e.jsxs("div",{className:It("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:It("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return r?e.jsx(Ub,{children:e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:o}),e.jsx(Gl,{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:It("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(ei,{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 e5s=[{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}],D$=s=>{if(!s||!s.trim())return null;const t=s.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;const r=t.match(/^(\d{1,2})[\/\-](\d{1,2})(?:[\/\-](\d{2,4}))?$/);if(r){const a=r[1].padStart(2,"0"),i=r[2].padStart(2,"0");let l="2000";r[3]&&(l=r[3].length===2?(parseInt(r[3])>50?"19":"20")+r[3]:r[3]);const o=parseInt(a),c=parseInt(i);if(o>=1&&o<=12&&c>=1&&c<=31)return`${l}-${a}-${i}`}const n=new Date(t);return isNaN(n.getTime())?null:n.toISOString().split("T")[0]},t5s=({open:s,onOpenChange:t,relationshipTypes:r,onSuccess:n})=>{const{user:a}=js(),{toast:i}=Ma(),l=k.useRef(null),[o,c]=k.useState("upload"),[d,h]=k.useState([]),[m,x]=k.useState([]),[y,v]=k.useState({}),[w,b]=k.useState([]),[N,S]=k.useState([]),[T,A]=k.useState([]),[I,D]=k.useState(""),[R,$]=k.useState(!1),[F,z]=k.useState([]),[Q,K]=k.useState(!1),[X,Z]=k.useState(null);k.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Ie}=await V.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");S(Ie||[])})()},[s,a==null?void 0:a.id]);const re=Ie=>{A(Te=>Te.includes(Ie)?Te.filter(xe=>xe!==Ie):[...Te,Ie])},le=async()=>{const Ie=I.trim();if(!(!Ie||!(a!=null&&a.id))){$(!0);try{const{data:Te,error:xe}=await V.from("contact_custom_tags").insert({owner_user_id:a.id,name:Ie}).select("id, name, color").single();if(xe)throw xe;Te&&(S(et=>[...et,Te].sort((fe,it)=>fe.name.localeCompare(it.name))),A(et=>[...et,Te.id]),D(""))}catch(Te){i({title:"Could not create tag",description:Te.message||"Try a different name.",variant:"destructive"})}finally{$(!1)}}},oe=()=>{c("upload"),h([]),x([]),v({}),b([]),A([]),D(""),z([]),Z(null),l.current&&(l.current.value="")},ne=()=>{oe(),t(!1)},ie=Ie=>{const Te=Ie.split(` `).map(Ye=>Ye.trim()).filter(Ye=>Ye);if(Te.length===0)return{headers:[],data:[]};const xe=Ye=>{const We=[];let _e="",Re=!1;for(let tt=0;tt0&&(et[0]=et[0].replace(/^\uFEFF/,""));const fe=new Map,it=et.map((Ye,We)=>{let _e=(Ye||"").trim();_e||(_e=`Column ${We+1}`);const Re=fe.get(_e)||0;return fe.set(_e,Re+1),Re===0?_e:`${_e} (${Re+1})`}),Oe=Te.slice(1).map(xe);return{headers:it,data:Oe}},ye=Ie=>{var et;const Te=(et=Ie.target.files)==null?void 0:et[0];if(!Te)return;const xe=new FileReader;xe.onload=fe=>{var _e;const it=(_e=fe.target)==null?void 0:_e.result,{headers:Oe,data:Ye}=ie(it);if(Oe.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}h(Oe),x(Ye);const We={};Oe.forEach(Re=>{const tt=Re.toLowerCase().replace(/[_\s-]/g,"");tt.includes("firstname")||tt==="first"?We.first_name=Re:tt.includes("lastname")||tt==="last"?We.last_name=Re:tt.includes("spouse")&&tt.includes("email")?We.spouse_email=Re:tt.includes("spouse")||tt.includes("partner")?We.spouse_name=Re:tt.includes("email")?We.email=Re:tt.includes("phone")||tt.includes("mobile")||tt.includes("cell")?We.phone=Re:tt.includes("address")||tt.includes("street")?We.address=Re:tt==="city"?We.city=Re:tt==="state"||tt==="province"?We.state=Re:tt==="zip"||tt==="zipcode"||tt==="postalcode"?We.zip=Re:tt.includes("company")||tt.includes("organization")||tt.includes("business")?We.company_name=Re:tt.includes("jobtitle")||tt.includes("title")&&!tt.includes("spouse")?We.job_title=Re:tt.includes("birthday")||tt.includes("dob")||tt.includes("birthdate")?We.birthday=Re:tt.includes("anniversary")||tt.includes("homeanniversary")?We.home_anniversary=Re:(tt.includes("notes")||tt.includes("comment"))&&(We.notes=Re)}),v(We),c("mapping")},xe.readAsText(Te)},ce=(Ie,Te)=>{v(xe=>{if(Te==="none"){const{[Ie]:et,...fe}=xe;return fe}return{...xe,[Ie]:Te}})},ve=Ie=>{b(Te=>Te.includes(Ie)?Te.filter(xe=>xe!==Ie):[...Te,Ie])},be=async()=>{if(!(a!=null&&a.id))return;const{data:Ie}=await V.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Te=new Set((Ie||[]).filter(fe=>fe.email).map(fe=>fe.email.toLowerCase())),xe=new Set((Ie||[]).filter(fe=>fe.phone).map(fe=>fe.phone.replace(/[^0-9]/g,""))),et=m.map(fe=>{const it=tt=>{const Ke=y[tt];if(!Ke)return"";const Ze=d.indexOf(Ke);return Ze>=0?(fe[Ze]||"").trim():""},Oe=it("first_name"),Ye=it("email"),We=it("phone"),_e=Oe.length>0,Re=!!(Ye&&Te.has(Ye.toLowerCase())||We&&xe.has(We.replace(/[^0-9]/g,"")));return{first_name:Oe,last_name:it("last_name"),email:Ye,phone:We,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:_e,isDuplicate:Re,error:_e?void 0:"First name is required"}});z(et),c("preview")},Ue=Ie=>{const Te=Ie.trim().split(/\s+/);return{first_name:Te[0],last_name:Te.length>1?Te.slice(1).join(" "):null}},Be=async()=>{if(!(a!=null&&a.id))return;const Ie=F.filter(fe=>fe.isValid);if(Ie.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}K(!0);let Te=0,xe=0,et=0;try{for(const fe of Ie)try{let it=null;if(fe.email){const{data:We}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",fe.email).maybeSingle();it=We}if(!it&&fe.phone){const We=fe.phone.replace(/[^0-9]/g,""),{data:_e}=await V.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(_e){const Re=_e.find(tt=>tt.phone&&tt.phone.replace(/[^0-9]/g,"")===We);Re&&(it={id:Re.id})}}const Oe={owner_user_id:a.id,first_name:fe.first_name,last_name:fe.last_name||null,email:fe.email||null,phone:fe.phone||null,address:fe.address||null,city:fe.city||null,state:fe.state||null,zip:fe.zip||null,spouse_name:fe.spouse_name||null,spouse_email:fe.spouse_email||null,company_name:fe.company_name||null,job_title:fe.job_title||null,birthday:D$(fe.birthday),home_anniversary:D$(fe.home_anniversary),notes:fe.notes||null};let Ye=null;if(it){const{data:We}=await V.from("innercircle_contacts").select("*").eq("id",it.id).single();if(We){const _e={},Re=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const tt of Re){const Ke=We[tt],Ze=Oe[tt];(!Ke||Ke==="")&&Ze&&(_e[tt]=Ze)}Object.keys(_e).length>0&&await V.from("innercircle_contacts").update(_e).eq("id",it.id)}Ye=it.id,xe++}else{const{data:We,error:_e}=await V.from("innercircle_contacts").insert(Oe).select("id").single();_e?(console.error("Insert error for contact:",fe.first_name,_e),et++):We?(Ye=We.id,w.length>0&&await V.from("innercircle_contact_tags").insert(w.map(Re=>({contact_id:We.id,relationship_type_id:Re}))),Te++):et++}if(Ye&&T.length>0&&await V.from("contact_custom_tag_assignments").upsert(T.map(We=>({contact_id:Ye,tag_id:We})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Ye&&fe.spouse_name){const We=Ue(fe.spouse_name);let _e=null;if(fe.spouse_email){const{data:tt}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",fe.spouse_email).maybeSingle();_e=tt}if(!_e){const{data:tt}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",We.first_name).eq("last_name",We.last_name||fe.last_name||"").maybeSingle();_e=tt}let Re=null;if(_e){Re=_e.id;const tt=D$(fe.home_anniversary);tt&&await V.from("innercircle_contacts").update({home_anniversary:tt}).eq("id",_e.id).is("home_anniversary",null)}else{const{data:tt}=await V.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:We.first_name,last_name:We.last_name||fe.last_name||null,email:fe.spouse_email||null,address:fe.address||null,city:fe.city||null,state:fe.state||null,zip:fe.zip||null,home_anniversary:D$(fe.home_anniversary),spouse_name:`${fe.first_name}${fe.last_name?" "+fe.last_name:""}`,spouse_email:fe.email||null,notes:`Spouse of ${fe.first_name} ${fe.last_name||""} (imported via CSV)`.trim()}).select("id").single();tt&&(Re=tt.id,Te++)}Re&&(await V.from("innercircle_contacts").update({spouse_contact_id:Re}).eq("id",Ye),await V.from("innercircle_contacts").update({spouse_contact_id:Ye}).eq("id",Re))}}catch(it){console.error("Error importing contact:",it),et++}Z({created:Te,updated:xe,failed:et}),c("result"),(Te>0||xe>0)&&n(),i({title:"Import Complete",description:`${Te} created, ${xe} updated${et>0?`, ${et} failed`:""}.`})}catch(fe){console.error("Import error:",fe),i({title:"Import Failed",description:fe.message||"Failed to import contacts",variant:"destructive"})}finally{K(!1)}},De=F.filter(Ie=>Ie.isValid).length,Ae=F.filter(Ie=>!Ie.isValid).length,He=F.filter(Ie=>Ie.isValid&&Ie.isDuplicate).length,Le=De-He;return e.jsx(fs,{open:s,onOpenChange:ne,children:e.jsxs(ms,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(mb,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Hr,{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:ye,className:"hidden"}),e.jsx(da,{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(G,{onClick:()=>{var Ie;return(Ie=l.current)==null?void 0:Ie.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(G,{variant:"outline",size:"sm",onClick:()=>{const Ie=`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`,Te=new Blob([Ie],{type:"text/csv"}),xe=URL.createObjectURL(Te),et=document.createElement("a");et.href=xe,et.download="contact_import_template.csv",et.click(),URL.revokeObjectURL(xe)},children:[e.jsx(Ya,{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(he,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:e5s.map(Ie=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(he,{className:"w-40 text-sm",children:[Ie.label,Ie.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Is,{value:y[Ie.key]||"none",onValueChange:Te=>ce(Ie.key,Te),children:[e.jsx(As,{className:"w-48",children:e.jsx(Ls,{placeholder:"Select column..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"-- Not mapped --"}),d.map(Te=>e.jsx(ct,{value:Te,children:Te},Te))]})]})]},Ie.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.map(Ie=>e.jsx(Ge,{variant:w.includes(Ie.id)?"default":"outline",className:"cursor-pointer",onClick:()=>ve(Ie.id),children:Ie.name},Ie.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{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."}),N.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(Ie=>{const Te=T.includes(Ie.id);return e.jsxs(Ge,{variant:Te?"default":"outline",className:"cursor-pointer gap-1",style:Te&&Ie.color?{backgroundColor:Ie.color,borderColor:Ie.color}:void 0,onClick:()=>re(Ie.id),children:[Ie.name,Te&&e.jsx(vr,{className:"h-3 w-3"})]},Ie.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:I,onChange:Ie=>D(Ie.target.value),onKeyDown:Ie=>{Ie.key==="Enter"&&(Ie.preventDefault(),le())},className:"max-w-xs"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:le,disabled:!I.trim()||R,children:[R?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{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: ",m.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(In,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Le," new"]})]}),He>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Oi,{className:"h-4 w-4"}),e.jsxs("span",{children:[He," existing (will merge gaps)"]})]}),Ae>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Oi,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ae," invalid"]})]})]}),He>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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/30",children:[e.jsx(Nt,{children:"First Name"}),e.jsx(Nt,{children:"Last Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Phone"}),e.jsx(Nt,{children:"Status"})]})}),e.jsx($n,{children:F.slice(0,100).map((Ie,Te)=>e.jsxs(Ds,{children:[e.jsx(dt,{children:Ie.first_name}),e.jsx(dt,{children:Ie.last_name}),e.jsx(dt,{children:Ie.email}),e.jsx(dt,{children:Ie.phone}),e.jsx(dt,{children:Ie.isValid?Ie.isDuplicate?e.jsx(Ge,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Ge,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Ge,{variant:"destructive",children:Ie.error||"Invalid"})})]},Te))})]}),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"&&X&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(In,{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:[X.created," created, ",X.updated," merged"]}),X.failed>0&&e.jsxs("p",{className:"text-destructive",children:[X.failed," failed to import"]})]}),e.jsxs(an,{children:[o==="upload"&&e.jsx(G,{variant:"outline",onClick:ne,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:oe,children:"Back"}),e.jsx(G,{onClick:be,disabled:!y.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(G,{onClick:Be,disabled:Q||De===0,children:Q?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${De} Contact${De!==1?"s":""}`})]}),o==="result"&&e.jsx(G,{onClick:ne,children:"Done"})]})]})})};function s5s(){return"contacts"in navigator&&"ContactsManager"in window}function r5s(s){const t=[],r=s.split("BEGIN:VCARD").filter(n=>n.trim());for(const n of r){const a=n.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const h of a){const m=h.replace(/^\s+/,"");if(m.startsWith("N:")||m.startsWith("N;")){const y=m.substring(m.indexOf(":")+1).split(";");l=(y[0]||"").trim(),i=(y[1]||"").trim()}if((m.startsWith("FN:")||m.startsWith("FN;"))&&!i){const y=m.substring(m.indexOf(":")+1).trim().split(" ");i=y[0]||"",l=y.slice(1).join(" ")}(m.startsWith("EMAIL")||m.match(/^item\d+\.EMAIL/i))&&!o&&(o=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("TEL")||m.match(/^item\d+\.TEL/i))&&!c&&(c=m.substring(m.indexOf(":")+1).trim()),(m.startsWith("ADR")||m.match(/^item\d+\.ADR/i))&&!d&&(d=m.substring(m.indexOf(":")+1).split(";").map(v=>v.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function n5s({open:s,onOpenChange:t,onComplete:r}){js();const{data:n}=Sm(),a=Ufe(),i=k.useRef(null),[l,o]=k.useState("choose"),[c,d]=k.useState([]),[h,m]=k.useState(new Set),[x,y]=k.useState(0),[v,w]=k.useState(0),b=s5s(),N=k.useCallback(z=>{if(!n)return z;const Q=new Set(n.filter(X=>X.email).map(X=>X.email.toLowerCase())),K=new Set(n.filter(X=>X.phone).map(X=>X.phone.replace(/\D/g,"")));return z.map(X=>{var le,oe;const Z=(le=X.email)==null?void 0:le.toLowerCase(),re=(oe=X.phone)==null?void 0:oe.replace(/\D/g,"");return Z&&Q.has(Z)?{...X,isDuplicate:!0,duplicateField:"email"}:re&&re.length>=7&&K.has(re)?{...X,isDuplicate:!0,duplicateField:"phone"}:X})},[n]),S=async()=>{try{const z=["name","email","tel","address"],Q=await navigator.contacts.select(z,{multiple:!0});if(!Q||Q.length===0)return;const K=Q.map(re=>{var ne,ie,ye,ce;const oe=(((ne=re.name)==null?void 0:ne[0])||"").split(" ");return{first_name:oe[0]||"",last_name:oe.slice(1).join(" "),email:((ie=re.email)==null?void 0:ie[0])||"",phone:((ye=re.tel)==null?void 0:ye[0])||"",address:(ce=re.address)!=null&&ce[0]?[re.address[0].streetAddress,re.address[0].city,re.address[0].region,re.address[0].postalCode].filter(Boolean).join(", "):""}}),X=N(K);d(X);const Z=new Set;X.forEach((re,le)=>{re.isDuplicate||Z.add(le)}),m(Z),o("preview")}catch(z){console.error("Contact Picker error:",z),cn({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},T=z=>{var X;const Q=(X=z.target.files)==null?void 0:X[0];if(!Q)return;const K=new FileReader;K.onload=Z=>{var ie;const re=(ie=Z.target)==null?void 0:ie.result,le=r5s(re);if(le.length===0){cn({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const oe=N(le);d(oe);const ne=new Set;oe.forEach((ye,ce)=>{ye.isDuplicate||ne.add(ce)}),m(ne),o("preview")},K.readAsText(Q),i.current&&(i.current.value="")},A=async()=>{const z=c.filter((K,X)=>h.has(X));if(z.length===0)return;o("importing");let Q=0;for(const K of z)try{await a.mutateAsync({first_name:K.first_name,last_name:K.last_name||void 0,email:K.email||void 0,phone:K.phone||void 0,address:K.address||void 0}),Q++,w(Math.round(Q/z.length*100))}catch(X){console.error(`Failed to import ${K.first_name} ${K.last_name}:`,X)}y(Q),o("done")},I=z=>{m(Q=>{const K=new Set(Q);return K.has(z)?K.delete(z):K.add(z),K})},D=()=>{h.size===c.length?m(new Set):m(new Set(c.map((z,Q)=>Q)))},R=z=>{z||(o("choose"),d([]),m(new Set),y(0),w(0),l==="done"&&r()),t(z)},$=c.filter(z=>z.isDuplicate).length,F=h.size;return e.jsx(fs,{open:s,onOpenChange:R,children:e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(ig,{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(Hr,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[b&&e.jsxs(G,{onClick:S,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(ig,{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:[b&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),b&&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(G,{variant:b?"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(da,{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:b?"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:T,className:"hidden"}),!b&&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",$>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",$," already exist)"]})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:D,children:h.size===c.length?"Deselect All":"Select All"})]}),e.jsx(Qa,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((z,Q)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${z.isDuplicate?"opacity-60":""}`,onClick:()=>I(Q),children:[e.jsx(Si,{checked:h.has(Q),onCheckedChange:()=>I(Q),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(Ge,{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})]})]})]},Q))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(G,{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(es,{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:[v,"% 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:`${v}%`}})})]}),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(Kn,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[x," contact",x!==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(G,{onClick:()=>R(!1),className:"mt-2",children:"Done"})]})]})})}function a5s(s){return mt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function i5s(){const{user:s}=js();return mt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await V.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(r)throw r;const n=t;return{totalSent:n.length,totalOpened:n.filter(a=>a.opened_at).length,totalClicked:n.filter(a=>a.clicked_at).length,totalWatched:n.filter(a=>a.watched_at).length,openRate:n.length>0?Math.round(n.filter(a=>a.opened_at).length/n.length*100):0,clickRate:n.length>0?Math.round(n.filter(a=>a.clicked_at).length/n.length*100):0,watchRate:n.length>0?Math.round(n.filter(a=>a.watched_at).length/n.length*100):0}},enabled:!!(s!=null&&s.id)})}function o5s(){const{user:s}=js();return mt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function Eht(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await V.from("video_share_recipients").insert([{video_id:r.video_id,owner_user_id:s.id,recipient_email:r.recipient_email,recipient_name:r.recipient_name||null,contact_id:r.contact_id||null,sent_via:r.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return n},onSuccess:r=>{t.invalidateQueries({queryKey:["video-share-recipients",r.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function Aht(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function Mht(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const l5s=100;function c5s({open:s,onOpenChange:t,contacts:r,isGmailConnected:n,isMassEmailReady:a,onSendComplete:i}){const l=br(),o=sa(),c=Eht(),[d,h]=k.useState([]),[m,x]=k.useState(!1),[y,v]=k.useState(""),[w,b]=k.useState(null),[N,S]=k.useState(""),[T,A]=k.useState(""),[I,D]=k.useState(!1),[R,$]=k.useState({done:0,total:0,failed:0}),F=r.filter(oe=>!!oe.email),z=r.length-F.length,Q=F.length>l5s;k.useEffect(()=>{s&&(b(null),v(""),$({done:0,total:0,failed:0}))},[s]),k.useEffect(()=>{!s||!o||(x(!0),V.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:oe})=>{h(oe||[]),x(!1)}))},[s,o]),k.useEffect(()=>{if(!w)return;const oe=w.title||"a quick video";S(`I recorded a video for you — ${oe}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[w]);const K=d.filter(oe=>!y||(oe.title||"").toLowerCase().includes(y.toLowerCase())),X=(oe,ne)=>{if(!w)return"";const ie=w.share_token?`https://video.relevelup.com/share/video/${w.share_token}`:"",ye=w.share_token?`https://video.relevelup.com/thumb/${w.share_token}`:w.thumbnail_url||"",ce=w.title||"Video Message",be=T.replace(/\{\{first_name\}\}/gi,oe).split(/\n\n+/).map(De=>`

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

`).join(""),Ue=ne?Mht(ne):ie,Be=ne?``:"";return`
${be}

▶ Watch Video

${Be}
`},Z=async()=>{if(!w)return;D(!0),$({done:0,total:F.length,failed:0});let oe=0,ne=0;for(const ie of F)try{let ye;try{ye=(await c.mutateAsync({video_id:w.id,recipient_email:ie.email,recipient_name:`${ie.first_name} ${ie.last_name||""}`.trim(),contact_id:ie.id,sent_via:"gmail"})).share_token}catch(Be){console.warn("Tracking record failed for",ie.email,Be)}const ce=X(ie.first_name,ye),ve=N.replace(/\{\{first_name\}\}/gi,ie.first_name),{data:be,error:Ue}=await V.functions.invoke("gmail-send",{body:{to:ie.email,subject:ve,body:ce,contactId:ie.id}});if(Ue||!(be!=null&&be.success))throw new Error((be==null?void 0:be.error)||(Ue==null?void 0:Ue.message)||"Send failed");oe+=1}catch(ye){console.error("Failed to send to",ie.email,ye),ne+=1}finally{$({done:oe+ne,total:F.length,failed:ne}),await new Promise(ye=>setTimeout(ye,250))}D(!1),ne===0?ue.success(`Video sent to ${oe} ${oe===1?"contact":"contacts"}!`):ue.warning(`Sent to ${oe}, ${ne} failed. Check console for details.`),t(!1),i==null||i()},re=()=>{if(!w)return;const oe=X("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:F.map(ne=>({email:ne.email,name:`${ne.first_name} ${ne.last_name||""}`.trim()})),initialSubject:N,initialBodyHtml:oe}}),t(!1)},le=!!w&&!!N.trim()&&F.length>0&&(Q?a:n);return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary"}),"Send Video to ",F.length," ",F.length===1?"Contact":"Contacts"]}),e.jsxs(Hr,{children:[Q?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(bu,{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:[Q&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Oi,{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."]})]}),!Q&&!n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Oi,{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(he,{children:"Choose a video"}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx($s,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search your video library...",value:y,onChange:oe=>v(oe.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"h-14 w-full"}),e.jsx(Fs,{className:"h-14 w-full"})]}):K.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."}):K.map(oe=>{const ne=(w==null?void 0:w.id)===oe.id;return e.jsxs("button",{type:"button",onClick:()=>b(oe),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ne?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[oe.thumbnail_url?e.jsx("img",{src:oe.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(gh,{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(Uo,{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:oe.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[oe.duration_seconds?`${Math.round(oe.duration_seconds)}s`:"",oe.created_at?` · ${new Date(oe.created_at).toLocaleDateString()}`:""]})]})]},oe.id)})})]}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(Ne,{id:"bulk-video-subject",value:N,onChange:oe=>S(oe.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(or,{id:"bulk-video-message",value:T,onChange:oe=>A(oe.target.value),rows:4,className:"resize-y"})]}),I&&R.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",R.done," / ",R.total,R.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",R.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:I,children:"Cancel"}),Q?e.jsxs(G,{onClick:re,disabled:!le,className:"gap-2",children:[e.jsx(bu,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(G,{onClick:Z,disabled:!le||I,className:"gap-2",children:[I?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),I?"Sending…":`Send to ${F.length}`]})]})]})]})})}function DTe(){const s=sa();return mt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})}function d5s(s){return mt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function u5s(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description??null,category:r.category??"nurture",icon:r.icon??"🌱",cover_color:r.cover_color??"from-emerald-500 to-teal-600",goal:r.goal??null,is_active:!1}).select().single();if(a)throw a;return n},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Iht(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("drip_campaigns").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",r.id]})}})}function h5s(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("drip_campaigns").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function m5s(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const[{data:n,error:a},{data:i,error:l}]=await Promise.all([V.from("drip_campaigns").select("*").eq("id",r).single(),V.from("drip_campaign_steps").select("*").eq("campaign_id",r).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await V.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description,category:n.category,icon:n.icon,cover_color:n.cover_color,goal:n.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(m=>({campaign_id:o.id,step_order:m.step_order,channel:m.channel,subject:m.subject,body:m.body,video_url:m.video_url,delay_type:m.delay_type,delay_days:m.delay_days,delay_hours:m.delay_hours,anchor_field:m.anchor_field,anchor_offset_days:m.anchor_offset_days,send_window_start:m.send_window_start,send_window_end:m.send_window_end})),{error:h}=await V.from("drip_campaign_steps").insert(d);if(h)throw h}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function Lht(s){return mt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function f5s(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.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(n)throw n;return r},onSuccess:(t,r)=>s.invalidateQueries({queryKey:["drip-campaign-steps",r.campaign_id]})})}function p5s(){const s=Xt();return Ct({mutationFn:async({id:t,campaign_id:r,...n})=>{const{data:a,error:i}=await V.from("drip_campaign_steps").update(n).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:r}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function x5s(){const s=Xt();return Ct({mutationFn:async({id:t,campaign_id:r})=>{const{error:n}=await V.from("drip_campaign_steps").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function g5s(s){return mt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function y5s(s){return mt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:r}=await V.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(r)throw r;return t??0},enabled:!!s,staleTime:3e4})}function Pht(){const s=Xt();return Ct({mutationFn:async({campaignId:t,contactIds:r})=>{const{data:n,error:a}=await V.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:r}});if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function v5s(){const s=Xt();return Ct({mutationFn:async({id:t,status:r})=>{const n={status:r};r==="paused"&&(n.paused_at=new Date().toISOString()),r==="exited"&&(n.exited_at=new Date().toISOString(),n.exit_reason="manual");const{data:a,error:i}=await V.from("drip_campaign_enrollments").update(n).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const b5s=[{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"}],vxe={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"},_5s={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 yL({userId:s,onSelect:t,onSelectVideo:r,triggerLabel:n="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=k.useState(!1),[d,h]=k.useState([]),[m,x]=k.useState(!1),[y,v]=k.useState("");k.useEffect(()=>{!o||!s||(x(!0),V.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:b})=>{h(b||[]),x(!1)}))},[o,s]);const w=d.filter(b=>!y||(b.title||b.recipient_name||"").toLowerCase().includes(y.toLowerCase()));return e.jsxs(fs,{open:o,onOpenChange:c,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(gh,{className:"h-3.5 w-3.5"}),n]})}),e.jsxs(ms,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsx(gs,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos...",value:y,onChange:b=>v(b.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:m?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{className:"h-16 w-full"}),e.jsx(Fs,{className:"h-16 w-full"})]}):w.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"}):w.map(b=>e.jsxs("button",{onClick:()=>{t(b.playback_url||""),r==null||r(b),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:b.thumbnail_url?e.jsx("img",{src:b.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:N=>{const S=N.currentTarget.parentElement;if(S){N.currentTarget.remove();const T=document.createElement("span");T.innerHTML="🎬",T.className="text-lg",S.appendChild(T)}}}):e.jsx(Jr,{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:b.title||b.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.duration_seconds?`${Math.round(b.duration_seconds)}s`:"",b.created_at?` · ${new Date(b.created_at).toLocaleDateString()}`:""]})]})]},b.id))})]})]})}function w5s(){return mt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await V.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function j5s(s){return mt({queryKey:["video-scripts",s],queryFn:async()=>{let t=V.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:r,error:n}=await t;if(n)throw n;return r}})}function N5s(){const{user:s}=js();return mt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await V.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function k5s(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await V.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:r.id,category_id:r.category_id,title:r.title,script_text:r.script_text,tags:r.tags,is_custom:!1}]).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function S5s(s){const{user:t}=js();return mt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let r=V.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});r=r.eq("is_deleted",!1);const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!(t!=null&&t.id)})}function C5s(s){return mt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:r}=await V.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function Yb(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:n,error:a}=await V.from("agent_videos").insert([{owner_user_id:s.id,contact_id:r.contact_id,bunny_video_id:r.bunny_video_id,playback_url:r.playback_url,thumbnail_url:r.thumbnail_url,preview_url:r.preview_url,duration_seconds:r.duration_seconds,file_size_mb:r.file_size_mb||0,title:r.title,notes:r.notes,task_id:r.task_id,status:r.status||"processing",touch_type:r.touch_type||"video",page_template:"default",category:r.category||"general"}]).select("*, share_token").single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function T5s(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("agent_videos").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function E5s(){const s=Xt();return Ct({mutationFn:async({id:t,bunnyVideoId:r,hardDelete:n=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:r,hardDelete:n}),r){console.log("Calling bunny-upload delete for videoId:",r);const{data:a,error:i}=await V.functions.invoke("bunny-upload",{body:{action:"delete",videoId:r,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(n){console.log("Hard deleting from database:",t);const{error:a}=await V.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await V.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 bxe(){const{user:s}=js();return mt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:r}=await V.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function Dht(){const{data:s,isLoading:t}=bxe(),r=s?s.total_storage_mb0?s.total_storage_mb/s.max_storage_mb*100:0,i=a>=80;return{canRecord:r,remainingMb:n,usagePercent:a,isNearLimit:i,storage:s,isLoading:t}}async function h5(s){const{data:t,error:r}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(r)throw r;return t}async function m5(s){const{data:t,error:r}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}async function Ev(s){const{data:t,error:r}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(r)throw r;return t}function A5s(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async({contactId:r,videoId:n,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await V.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 V.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:r,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${n}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function Rht({open:s,onOpenChange:t,onUploadComplete:r}){const{data:n}=Sm(),{data:a}=bxe(),i=Yb(),l=k.useRef(null),[o,c]=k.useState(null),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(!1),[N,S]=k.useState(0),[T,A]=k.useState("idle"),I=(a==null?void 0:a.total_storage_mb)||0,R=((a==null?void 0:a.max_storage_mb)||1024)-I,$=K=>{var re;const X=(re=K.target.files)==null?void 0:re[0];if(!X)return;if(!X.type.startsWith("video/")){ue.error("Please select a video file");return}const Z=X.size/(1024*1024);if(Z>500){ue.error("Video file must be less than 500MB");return}if(Z>R){ue.error(`Not enough storage. You have ${R.toFixed(1)} MB remaining.`);return}c(X),d||h(X.name.replace(/\.[^/.]+$/,""))},F=async()=>{if(!o){ue.error("Please select a video file");return}b(!0),S(0),A("creating");try{const{data:K,error:X}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(X)throw new Error(X.message);const{videoId:Z,libraryId:re}=K;A("uploading");const{data:le,error:oe}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Z,isAgentVideo:!0}});if(oe)throw new Error(oe.message);await new Promise((ye,ce)=>{const ve=new XMLHttpRequest;ve.upload.addEventListener("progress",be=>{if(be.lengthComputable){const Ue=Math.round(be.loaded/be.total*100);S(Ue)}}),ve.addEventListener("load",()=>{ve.status>=200&&ve.status<300?ye():ce(new Error(`Upload failed with status ${ve.status}`))}),ve.addEventListener("error",()=>ce(new Error("Upload failed"))),ve.open("PUT",le.uploadUrl),ve.setRequestHeader("AccessKey",le.apiKey),ve.send(o)}),A("processing");const ne=o.size/(1024*1024),ie=`https://iframe.mediadelivery.net/embed/${re}/${Z}`;await i.mutateAsync({bunny_video_id:Z,playback_url:ie,file_size_mb:ne,title:d||o.name,notes:m||void 0,contact_id:y||void 0,status:"processing",touch_type:"video_upload"}),ue.success("Video uploaded successfully! Processing may take a few minutes."),r==null||r(ie),z()}catch(K){console.error("Upload error:",K),ue.error(K instanceof Error?K.message:"Failed to upload video")}finally{b(!1),A("idle")}},z=()=>{w||(c(null),h(""),x(""),v(""),S(0),A("idle"),t(!1))},Q=()=>{switch(T){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${N}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(fs,{open:s,onOpenChange:z,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Upload Video"}),e.jsx(Hr,{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(he,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Jr,{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"]})]}),!w&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:K=>{K.stopPropagation(),c(null)},children:e.jsx(vr,{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 K;return(K=l.current)==null?void 0:K.click()},children:[e.jsx(da,{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:$,disabled:w})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"title",children:"Title"}),e.jsx(Ne,{id:"title",value:d,onChange:K=>h(K.target.value),placeholder:"Enter video title",disabled:w})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Associate with Contact (optional)"}),e.jsxs(Is,{value:y||"__none__",onValueChange:K=>v(K==="__none__"?"":K),disabled:w,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a contact"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"__none__",children:"No contact"}),n==null?void 0:n.map(K=>e.jsxs(ct,{value:K.id,children:[K.first_name," ",K.last_name||""]},K.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(or,{id:"notes",value:m,onChange:K=>x(K.target.value),placeholder:"Add any notes about this video",rows:2,disabled:w})]}),w&&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(es,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:Q()})]}),e.jsx(ei,{value:T==="uploading"?N:T==="processing"?100:10})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:z,disabled:w,children:"Cancel"}),e.jsx(G,{onClick:F,disabled:!o||w,children:w?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const M5s=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"];function Oht({open:s,onOpenChange:t,campaignId:r}){const[n,a]=k.useState(r??null),[i,l]=k.useState("details");k.useEffect(()=>{a(r??null),l("details")},[r,s]);const o=n,c=!!o,{data:d}=d5s(o||void 0),{data:h,isLoading:m}=Lht(o||void 0),x=u5s(),y=Iht(),v=f5s(),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState("nurture"),[I,D]=k.useState("🌱"),[R,$]=k.useState("");k.useEffect(()=>{d?(b(d.name),S(d.description||""),A(d.category),D(d.icon),$(d.goal||"")):c||(b(""),S(""),A("nurture"),D("🌱"),$(""))},[d,c,s]);const F=_5s[T],z=async()=>{if(!w.trim()){ue.error("Give your campaign a name");return}try{if(c&&o)await y.mutateAsync({id:o,name:w,description:N,category:T,icon:I,goal:R,cover_color:F}),ue.success("Campaign updated");else{const K=await x.mutateAsync({name:w,description:N,category:T,icon:I,goal:R,cover_color:F});return ue.success("Campaign created — now add your first step!"),a(K.id),l("steps"),K}}catch(K){ue.error(K.message||"Failed to save")}},Q=async()=>{if(!o){ue.error("Save the campaign first, then add steps");return}const K=((h==null?void 0:h.length)||0)+1;try{await v.mutateAsync({campaign_id:o,step_order:K,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:K===1?0:2,delay_hours:0})}catch{ue.error("Failed to add step")}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{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:I}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(gs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Hr,{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(On,{value:i,onValueChange:K=>l(K),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Rn,{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 ",h&&h.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1.5 text-[10px]",children:h.length})]})]}),e.jsx(ts,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(Qa,{className:"h-full",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Campaign Name *"}),e.jsx(Ne,{value:w,onChange:K=>b(K.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Description"}),e.jsx(or,{value:N,onChange:K=>S(K.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Goal (optional)"}),e.jsx(Ne,{value:R,onChange:K=>$(K.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(he,{className:"text-xs",children:"Category"}),e.jsxs(Is,{value:T,onValueChange:K=>A(K),children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:Object.entries(vxe).map(([K,X])=>e.jsx(ct,{value:K,children:X},K))})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:M5s.map(K=>e.jsx("button",{type:"button",onClick:()=>D(K),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${I===K?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:K},K))})]})]}),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(ts,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(Qa,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:m?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!h||h.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(jr,{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(G,{size:"sm",onClick:Q,disabled:v.isPending,children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[h.map((K,X)=>e.jsx(I5s,{step:K,index:X,totalSteps:h.length},K.id)),e.jsxs(G,{variant:"outline",size:"sm",onClick:Q,disabled:v.isPending,className:"w-full",children:[v.isPending?e.jsx(es,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx($s,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(an,{className:"border-t p-4 shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(G,{onClick:z,disabled:x.isPending||y.isPending,children:[(x.isPending||y.isPending)&&e.jsx(es,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function I5s({step:s,index:t,totalSteps:r}){const n=p5s(),a=x5s(),i=sa(),[l,o]=k.useState(!1),[c,d]=k.useState(s),[h,m]=k.useState(!1),[x,y]=k.useState(!1),[v,w]=k.useState(""),[b,N]=k.useState(!1);k.useEffect(()=>d(s),[s]);const S=JSON.stringify(c)!==JSON.stringify(s),T=async()=>{m(!0);try{await n.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}),ue.success(`Step ${t+1} saved`)}catch{ue.error("Failed to save step")}finally{m(!1)}},A=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ue.success("Step deleted")}catch{ue.error("Failed to delete")}},I=R=>{d({...c,body:c.body+R})},D=()=>{if(c.delay_type==="calendar_anchor"){const $=c.anchor_field==="birthday"?"birthday":"home anniversary",F=c.anchor_offset_days||0;return F===0?`On their ${$}`:F<0?`${Math.abs(F)}d before ${$}`:`${F}d after ${$}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const R=[];return c.delay_days&&R.push(`${c.delay_days}d`),c.delay_hours&&R.push(`${c.delay_hours}h`),t===0?`After ${R.join(" ")||"0"}`:`+${R.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(on,{className:"h-3 w-3"}):e.jsx(fn,{className:"h-3 w-3"}),e.jsx("span",{children:D()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(Vs,{className:"h-3 w-3"}):e.jsx(xi,{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(Jf,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Wi,{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(he,{className:"text-xs",children:"Channel"}),e.jsxs(Is,{value:c.channel,onValueChange:R=>d({...c,channel:R}),children:[e.jsx(As,{className:"mt-1 h-9",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:e.jsx(ct,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Timing Type"}),e.jsxs(Is,{value:c.delay_type,onValueChange:R=>d({...c,delay_type:R}),children:[e.jsx(As,{className:"mt-1 h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"relative",children:"⏱ Relative delay"}),e.jsx(ct,{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(he,{className:"text-xs",children:"Days delay"}),e.jsx(Ne,{type:"number",min:0,value:c.delay_days,onChange:R=>d({...c,delay_days:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Hours delay"}),e.jsx(Ne,{type:"number",min:0,max:23,value:c.delay_hours,onChange:R=>d({...c,delay_hours:parseInt(R.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(he,{className:"text-xs",children:"Anchor"}),e.jsxs(Is,{value:c.anchor_field||"birthday",onValueChange:R=>d({...c,anchor_field:R}),children:[e.jsx(As,{className:"mt-1 h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"birthday",children:"🎂 Birthday"}),e.jsx(ct,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(Ne,{type:"number",value:c.anchor_offset_days||0,onChange:R=>d({...c,anchor_offset_days:parseInt(R.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subject Line"}),e.jsx(Ne,{value:c.subject,onChange:R=>d({...c,subject:R.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(he,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(or,{value:c.body,onChange:R=>d({...c,body:R.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:"}),b5s.map(R=>e.jsx("button",{type:"button",onClick:()=>I(R.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R.label},R.key))]})]}),e.jsxs("div",{children:[e.jsx(he,{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(Jr,{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(G,{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(yL,{userId:i||void 0,onSelect:R=>d({...c,video_url:R}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>N(!0),children:[e.jsx(da,{className:"h-3 w-3"})," Upload"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{w(""),y(!0)},children:[e.jsx(po,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(Rht,{open:b,onOpenChange:N,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(fs,{open:x,onOpenChange:y,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add video URL"}),e.jsx(Hr,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(Ne,{value:v,onChange:R=>w(R.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:R=>{R.key==="Enter"&&v.trim()&&(d({...c,video_url:v.trim()}),y(!1))}}),e.jsxs(an,{children:[e.jsx(G,{variant:"ghost",onClick:()=>y(!1),children:"Cancel"}),e.jsx(G,{disabled:!v.trim(),onClick:()=>{d({...c,video_url:v.trim()}),y(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(G,{size:"sm",onClick:T,disabled:!S||h,children:[h&&e.jsx(es,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function L5s({open:s,onOpenChange:t,contactIds:r,onSuccess:n}){const{data:a,isLoading:i}=DTe(),l=Pht(),[o,c]=k.useState(""),[d,h]=k.useState(null),[m,x]=k.useState(!1),y=(a||[]).filter(b=>!b.is_starter),v=y.filter(b=>b.name.toLowerCase().includes(o.toLowerCase())||(b.description||"").toLowerCase().includes(o.toLowerCase())),w=async()=>{if(d)try{const b=await l.mutateAsync({campaignId:d,contactIds:r}),N=[`${b.enrolled} enrolled`];b.skipped>0&&N.push(`${b.skipped} skipped`),b.errors>0&&N.push(`${b.errors} errors`),ue.success(N.join(" · ")),t(!1),h(null),n==null||n()}catch(b){ue.error(b.message||"Failed to enroll contacts")}};return e.jsxs(fs,{open:s,onOpenChange:t,children:[e.jsxs(ms,{className:"max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Hr,{children:[r.length," contact",r.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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search campaigns...",value:o,onChange:b=>c(b.target.value),className:"pl-9 h-9"})]}),e.jsx(Qa,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):v.length===0?e.jsx("div",{className:"text-center py-8",children:y.length===0?e.jsxs(e.Fragment,{children:[e.jsx(jr,{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(G,{size:"sm",onClick:()=>x(!0),children:[e.jsx($s,{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:v.map(b=>e.jsxs("button",{onClick:()=>h(b.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===b.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 ${b.cover_color} flex items-center justify-center text-lg`,children:b.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:b.name}),b.is_active&&e.jsx(Ge,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:b.description})]}),d===b.id&&e.jsx(Kn,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},b.id))})})]}),e.jsxs(an,{className:"gap-2 sm:gap-2",children:[y.length>0&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>x(!0),className:"mr-auto text-xs",children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:w,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(es,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",r.length," contact",r.length!==1?"s":""]})]})]}),e.jsx(Oht,{open:m,onOpenChange:x})]})}function P5s({selectedIds:s,contacts:t,onClearSelection:r,onSendToLeadPond:n,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=br(),{data:c}=fx(),d=i3e(),h=Xt(),{isGmailConnected:m}=Eh(),{isReady:x}=OB(),{data:y}=xL(),v=MTe(),w=Nht(),[b,N]=k.useState(!1),[S,T]=k.useState(!1),[A,I]=k.useState(!1),[D,R]=k.useState(!1),[$,F]=k.useState(!1),[z,Q]=k.useState(""),K=s.size;if(K===0)return null;const X=async ye=>{N(!0);try{const ve=Array.from(s).map(Ue=>({contact_id:Ue,relationship_type_id:ye})),{error:be}=await V.from("innercircle_contact_tags").upsert(ve,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(be)throw be;h.invalidateQueries({queryKey:["innercircle-contacts"]}),h.invalidateQueries({queryKey:["innercircle-contact-counts"]}),cn({title:`Assigned type to ${K} contacts`}),r()}catch(ce){cn({title:"Error assigning type",description:ce.message,variant:"destructive"})}finally{N(!1)}},Z=async ye=>{N(!0);try{const ce=Array.from(s);for(const ve of ce)try{await w.mutateAsync({contactId:ve,tagId:ye})}catch{}h.invalidateQueries({queryKey:["all-contact-custom-tags"]}),cn({title:`Tagged ${K} contacts`}),F(!1),Q("")}catch(ce){cn({title:"Error adding tags",description:ce.message,variant:"destructive"})}finally{N(!1)}},re=async()=>{if(z.trim()){N(!0);try{const ye=await v.mutateAsync({name:z.trim()});await Z(ye.id)}catch(ye){cn({title:"Error creating tag",description:ye.message,variant:"destructive"}),N(!1)}}},le=(y==null?void 0:y.filter(ye=>ye.name.toLowerCase().includes(z.toLowerCase())))||[],oe=y==null?void 0:y.find(ye=>ye.name.toLowerCase()===z.trim().toLowerCase()),ne=()=>{const ye=t.filter(Ae=>s.has(Ae.id)),ce=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],ve=ye.map(Ae=>{var He;return[Ae.first_name,Ae.last_name||"",Ae.email||"",Ae.phone||"",Ae.address||"",Ae.birthday||"",Ae.home_anniversary||"",Ae.notes||"",((He=Ae.tags)==null?void 0:He.map(Le=>{var Ie;return(Ie=Le.relationship_type)==null?void 0:Ie.name}).join("; "))||""]}),be=[ce.join(","),...ve.map(Ae=>Ae.map(He=>`"${(He||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ue=new Blob([be],{type:"text/csv"}),Be=URL.createObjectURL(Ue),De=document.createElement("a");De.href=Be,De.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,De.click(),URL.revokeObjectURL(Be),cn({title:`Exported ${K} contacts`})},ie=async()=>{if(confirm(`Are you sure you want to delete ${K} contacts? This cannot be undone.`)){N(!0);try{const ye=Array.from(s);for(const ce of ye)await d.mutateAsync(ce);r()}catch(ye){cn({title:"Error deleting contacts",description:ye.message,variant:"destructive"})}finally{N(!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(Ge,{variant:"secondary",className:"font-semibold",children:[K," selected"]}),e.jsxs(Is,{onValueChange:X,disabled:b,children:[e.jsx(As,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(wh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(Ms,{children:c==null?void 0:c.filter(ye=>ye.active).map(ye=>e.jsx(ct,{value:ye.id,children:ye.name},ye.id))})]}),e.jsxs(To,{open:$,onOpenChange:F,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",disabled:b,children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(_o,{className:"w-56 p-2",align:"start",children:[e.jsx(Ne,{placeholder:"Search or create tag...",value:z,onChange:ye=>Q(ye.target.value),onKeyDown:ye=>{ye.key==="Enter"&&z.trim()&&!oe?(ye.preventDefault(),re()):ye.key==="Enter"&&oe&&(ye.preventDefault(),Z(oe.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[le.map(ye=>e.jsxs("button",{onClick:()=>Z(ye.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:ye.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ye.name})]},ye.id)),z.trim()&&!oe&&e.jsxs("button",{onClick:re,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($s,{className:"h-3.5 w-3.5"}),'Create "',z.trim(),'"']}),le.length===0&&!z.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),m&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:b,children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),x&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{const ye=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${ye}`)},disabled:b,children:[e.jsx(bu,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>I(!0),disabled:b,children:[e.jsx(Jr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>R(!0),disabled:b,children:[e.jsx(jr,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&n&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>n(Array.from(s)),disabled:b,children:[e.jsx(ky,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:b,children:[e.jsx(ub,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ne,disabled:b,children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ie,disabled:b,className:"text-destructive hover:text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:r,className:"ml-auto",children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(L5s,{open:D,onOpenChange:R,contactIds:Array.from(s),onSuccess:r}),e.jsx($v,{open:S,onOpenChange:T,bulkContacts:Array.from(s).map(ye=>{const ce=t.find(ve=>ve.id===ye);return ce?{id:ce.id,first_name:ce.first_name,last_name:ce.last_name,email:ce.email||""}:null}).filter(ye=>ye!==null&&ye.email!==""),onSendComplete:()=>{T(!1),r()}}),e.jsx(c5s,{open:A,onOpenChange:I,contacts:Array.from(s).map(ye=>t.find(ce=>ce.id===ye)).filter(ye=>!!ye).map(ye=>({id:ye.id,first_name:ye.first_name,last_name:ye.last_name,email:ye.email})),isGmailConnected:!!m,isMassEmailReady:!!x,onSendComplete:()=>{I(!1),r()}})]})}function yUe({contact:s,onEdit:t,onDelete:r,onSnooze:n,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=br(),{isReady:d}=OB(),h=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:m=>m.stopPropagation(),children:e.jsx(Lp,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",onClick:m=>m.stopPropagation(),children:[e.jsxs(Pa,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Cn,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Pa,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Pa,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Pa,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Pa,{onClick:()=>n(s.id,h),children:[e.jsx(tm,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Pa,{onClick:()=>a(s.id),children:[e.jsx(ky,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Pa,{onClick:()=>l(s.id),children:[e.jsx(ub,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Pa,{onClick:()=>t(s),children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Pa,{onClick:()=>r(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function D5s({currentFilters:s,currentSortBy:t,onApplySmartList:r}){const{data:n}=kht(),a=$4s(),i=U4s(),[l,o]=k.useState(!1),[c,d]=k.useState(""),h=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all",m=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(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Sy,{className:"h-3.5 w-3.5"}),"Smart Filters",n&&n.length>0&&e.jsx(Ge,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:n.length}),e.jsx(Wi,{className:"h-3.5 w-3.5"})]})}),e.jsxs(xd,{align:"start",className:"w-56",children:[n&&n.length>0?e.jsxs(e.Fragment,{children:[n.map(x=>e.jsxs(Pa,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>r(x.filters,x.sort_by),children:x.name}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:y=>{y.stopPropagation(),i.mutate(x.id)},children:e.jsx(yr,{className:"h-3 w-3 text-destructive"})})]},x.id)),e.jsx(_v,{})]}):e.jsx(Pa,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),h&&e.jsxs(Pa,{onClick:()=>o(!0),children:[e.jsx(iR,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{className:"max-w-sm",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ne,{placeholder:"e.g. Buyers in 40205",value:c,onChange:x=>d(x.target.value),onKeyDown:x=>x.key==="Enter"&&m(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{onClick:m,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}function vUe(s){if(!s)return null;const t=Fl(s);if(!t)return null;const r=new Date;r.setHours(0,0,0,0);const n=new Date(r.getFullYear(),t.getMonth(),t.getDate());return ns.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",subtitle:"No outreach yet",icon:sl,gradient:"from-violet-500/15 via-purple-500/10 to-transparent",iconBg:"bg-violet-500/15",iconColor:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",subtitle:"Time to reconnect",icon:fn,gradient:"from-amber-500/15 via-yellow-500/10 to-transparent",iconBg:"bg-amber-500/15",iconColor:"text-amber-600 dark:text-amber-400",match:s=>{const t=s.relationshipScore.daysSinceTouch;return t!==null&&t>90}},{key:"cooling",title:"Cooling Off",subtitle:"Engagement dropping",icon:H0,gradient:"from-cyan-500/15 via-sky-500/10 to-transparent",iconBg:"bg-cyan-500/15",iconColor:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",subtitle:"Next 30 days",icon:_h,gradient:"from-pink-500/15 via-fuchsia-500/10 to-transparent",iconBg:"bg-pink-500/15",iconColor:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",subtitle:"Next 30 days",icon:En,gradient:"from-emerald-500/15 via-green-500/10 to-transparent",iconBg:"bg-emerald-500/15",iconColor:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",subtitle:"In your pipeline",icon:Gu,gradient:"from-teal-500/15 via-[#406E71]/10 to-transparent",iconBg:"bg-teal-500/15",iconColor:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",subtitle:"Browsing right now",icon:fc,gradient:"from-indigo-500/15 via-blue-500/10 to-transparent",iconBg:"bg-indigo-500/15",iconColor:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",subtitle:"Top relationships",icon:jr,gradient:"from-amber-400/20 via-yellow-300/10 to-transparent",iconBg:"bg-amber-400/20",iconColor:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",subtitle:"No email or phone",icon:id,gradient:"from-slate-500/15 via-zinc-500/10 to-transparent",iconBg:"bg-slate-500/15",iconColor:"text-slate-600 dark:text-slate-400",match:s=>{var t,r;return!((t=s.email)!=null&&t.trim())&&!((r=s.phone)!=null&&r.trim())}}];function R5s({contacts:s,contactDealsMap:t,websiteActiveIds:r,activeKey:n,onSelect:a}){const i=k.useRef(null),l=k.useMemo(()=>{const c={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":r.size,"missing-info":0,vips:0};if(!s)return c;for(const d of s){const h={hasDeal:!!(t&&t[d.id]),daysToBirthday:vUe(d.birthday),daysToAnniv:vUe(d.home_anniversary)};for(const m of bUe)m.key!=="website-active"&&m.match(d,h)&&c[m.key]++}return c},[s,t,r]),o=c=>{var d;(d=i.current)==null||d.scrollBy({left:c,behavior:"smooth"})};return e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Smart Segments"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Auto-organized for you"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[n&&e.jsxs("button",{onClick:()=>a(null),className:"flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:[e.jsx(vr,{className:"h-3 w-3"}),"Clear"]}),e.jsx("button",{onClick:()=>o(-320),className:"hidden md:flex h-7 w-7 rounded-full items-center justify-center bg-muted/60 hover:bg-muted transition-colors","aria-label":"Scroll left",children:e.jsx($o,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>o(320),className:"hidden md:flex h-7 w-7 rounded-full items-center justify-center bg-muted/60 hover:bg-muted transition-colors","aria-label":"Scroll right",children:e.jsx(va,{className:"h-4 w-4"})})]})]}),e.jsx("div",{ref:i,style:{touchAction:"pan-x",WebkitOverflowScrolling:"touch"},className:"flex gap-3 overflow-x-auto overflow-y-hidden overscroll-x-contain pb-2 px-1 -mx-1 snap-x snap-mandatory scroll-smooth [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]",children:bUe.map(c=>{const d=c.icon,h=l[c.key],m=n===c.key,x=h===0;return e.jsxs("button",{onClick:()=>a(m?null:c.key),disabled:x&&!m,className:`group relative shrink-0 snap-start w-[180px] text-left rounded-xl border transition-all duration-200 overflow-hidden ${m?"border-[#406E71] ring-2 ring-[#406E71]/30 shadow-lg scale-[1.02] bg-card":x?"border-border/40 bg-card/50 opacity-50 cursor-not-allowed":"border-border hover:border-[#406E71]/50 hover:shadow-md hover:-translate-y-0.5 bg-card cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${c.gradient} pointer-events-none`}),e.jsxs("div",{className:"relative p-3.5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg ${c.iconBg} flex items-center justify-center`,children:e.jsx(d,{className:`h-4.5 w-4.5 ${c.iconColor}`,strokeWidth:2.25})}),e.jsx("div",{className:"text-right",children:e.jsx("div",{className:"text-2xl font-bold leading-none text-foreground tabular-nums",children:h.toLocaleString()})})]}),e.jsx("div",{className:"text-sm font-semibold text-foreground leading-tight",children:c.title}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5 leading-tight",children:c.subtitle})]})]},c.key)})})]})}const Fht="innercircle_geocode_cache_v1";function O5s(){try{return JSON.parse(localStorage.getItem(Fht)||"{}")}catch{return{}}}function F5s(s){try{localStorage.setItem(Fht,JSON.stringify(s))}catch{}}function B5s(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 z5s({open:s,onOpenChange:t,contacts:r,onCitySelect:n}){const a=k.useRef(null),i=k.useRef(null),[l,o]=k.useState(""),[c,d]=k.useState(!0),[h,m]=k.useState([]),[x,y]=k.useState({done:0,total:0}),[v,w]=k.useState(!1),[b,N]=k.useState("heat");k.useEffect(()=>{if(!s)return;let T=!1;return(async()=>{d(!0);const{data:A}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();T||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{T=!0}},[s]),k.useEffect(()=>{if(!s||!l)return;let T=!1;return(async()=>{const I=O5s(),D=r.map(Z=>({c:Z,addr:B5s(Z)})).filter(Z=>Z.addr),R=[],$=[];for(const{c:Z,addr:re}of D){const le=I[re];le!==null&&(le?R.push({id:Z.id,name:`${Z.first_name||""} ${Z.last_name||""}`.trim(),city:Z.city||null,state:Z.state||null,zip:Z.zip||Z.zip_code||null,lat:le.lat,lng:le.lng}):$.push({c:Z,addr:re}))}if(T||m(R),y({done:R.length,total:D.length}),$.length===0)return;w(!0);const F=6;let z=0;const Q={...I},K=[...R],X=async()=>{var Z;for(;z<$.length&&!T;){const re=z++,{c:le,addr:oe}=$[re];try{const ye=(Z=(await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(oe)}.json?access_token=${l}&limit=1&country=us`)).json()).features)==null?void 0:Z[0];if(ye!=null&&ye.center){const[ce,ve]=ye.center;Q[oe]={lat:ve,lng:ce},K.push({id:le.id,name:`${le.first_name||""} ${le.last_name||""}`.trim(),city:le.city||null,state:le.state||null,zip:le.zip||le.zip_code||null,lat:ve,lng:ce})}else Q[oe]=null}catch{}T||y({done:K.length,total:D.length})}};await Promise.all(Array.from({length:F},X)),!T&&(F5s(Q),m(K),w(!1))})(),()=>{T=!0}},[s,l,r]);const S=k.useMemo(()=>{const T=new Map;for(const A of r){const I=(A.city||"").trim();if(!I)continue;const D=(A.state||"").trim()||null,R=`${I.toLowerCase()}|${D||""}`,$=T.get(R);$?$.count++:T.set(R,{city:I,state:D,count:1})}return Array.from(T.values()).sort((A,I)=>I.count-A.count)},[r]);return k.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return Tl.accessToken=l,i.current=new Tl.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new Tl.NavigationControl,"top-right"),()=>{var T;(T=i.current)==null||T.remove(),i.current=null}},[s,l]),k.useEffect(()=>{const T=i.current;if(!T||h.length===0)return;const A=()=>{const D={type:"FeatureCollection",features:h.map($=>({type:"Feature",properties:{id:$.id,name:$.name},geometry:{type:"Point",coordinates:[$.lng,$.lat]}}))},R=T.getSource("contacts-src");if(R?R.setData(D):(T.addSource("contacts-src",{type:"geojson",data:D}),T.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]}}),T.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}}),T.on("click","contacts-points",$=>{var Q;const F=(Q=$.features)==null?void 0:Q[0];if(!F)return;const z=F.geometry.coordinates.slice();new Tl.Popup({offset:12}).setLngLat(z).setHTML(`
${F.properties.name||"Contact"}
`).addTo(T)}),T.on("mouseenter","contacts-points",()=>{T.getCanvas().style.cursor="pointer"}),T.on("mouseleave","contacts-points",()=>{T.getCanvas().style.cursor=""})),T.getLayer("contacts-heat")&&T.setLayoutProperty("contacts-heat","visibility",b==="heat"?"visible":"none"),T.getLayer("contacts-points")&&(T.setPaintProperty("contacts-points","circle-opacity",b==="points"?.9:0),T.setLayoutProperty("contacts-points","visibility","visible")),h.length>0&&!T._fitDone){const $=new Tl.LngLatBounds;h.forEach(F=>$.extend([F.lng,F.lat]));try{T.fitBounds($,{padding:60,maxZoom:11,duration:600}),T._fitDone=!0}catch{}}};T.isStyleLoaded()?A():T.once("load",A)},[h,b]),e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(ys,{className:"p-4 pb-2 border-b",children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(mc,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Ge,{variant:"secondary",className:"ml-2",children:[h.length," mapped · ",S.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(es,{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(G,{size:"sm",variant:b==="heat"?"default":"ghost",onClick:()=>N("heat"),className:"h-8",children:[e.jsx(mc,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(G,{size:"sm",variant:b==="points"?"default":"ghost",onClick:()=>N("points"),className:"h-8",children:[e.jsx(wR,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),v&&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(es,{className:"h-3 w-3 animate-spin"}),"Mapping ",x.done," / ",x.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Oi,{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(Ca,{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(Qa,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[S.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."}),S.slice(0,50).map((T,A)=>{var R;const I=((R=S[0])==null?void 0:R.count)||1,D=T.count/I*100;return e.jsx(ke,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{n==null||n(T.city,T.state),t(!1)},children:e.jsxs(Pe,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${D}%`}}),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:[T.city,T.state?`, ${T.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(Ge,{variant:"secondary",className:"shrink-0",children:T.count})]})]})},`${T.city}-${T.state}-${A}`)})]})})]})]})]})})}function HC(s){if(!s)return null;try{const t=s.split(/[-/T]/);if(t.length<3)return null;const r=parseInt(t[1],10)-1,n=parseInt(t[2],10);if(isNaN(r)||isNaN(n))return null;const a=new Date;a.setHours(0,0,0,0);let i=new Date(a.getFullYear(),r,n);return i.setHours(0,0,0,0),ir)return null;const a=t==="birthday"?"🎂":"🏡",i=n===0?t==="birthday"?"Birthday today!":"Anniversary today!":n===1?t==="birthday"?"Birthday tomorrow":"Anniversary tomorrow":`${a} in ${n}d`;return{emoji:a,label:i,daysUntil:n}}function wUe({birthday:s,homeAnniversary:t,className:r,contactId:n,contactName:a,contactAddress:i}){const l=br(),o=_Ue(s,"birthday",7),c=_Ue(t,"anniversary",7);if(!o&&!c)return null;const d=(h,m)=>{m.stopPropagation();const x=new URLSearchParams;n&&x.set("contactId",n),a&&x.set("name",a),i&&x.set("address",i),h==="home_anniversary"&&t&&x.set("date",t),x.set("cardType",h),l(`/mission-control/card-studio?${x.toString()}`)};return e.jsxs("div",{className:It("flex flex-wrap gap-1",r),children:[o&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Ge,{variant:"secondary",className:It("text-[10px] gap-0.5 font-medium",o.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:o.label}),n&&e.jsxs("button",{onClick:h=>d("birthday",h),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"]})]}),c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Ge,{variant:"secondary",className:It("text-[10px] gap-0.5 font-medium",c.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:c.label}),n&&e.jsxs("button",{onClick:h=>d("home_anniversary",h),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"]})]})]})}function jUe({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Ge,{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 NUe({count:s,className:t}){return!s||s<=0?null:e.jsxs(Ge,{variant:"outline",className:It("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(r3,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function $5s(){const s=sa();return mt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:r}=await V.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(r)throw r;const n={};return(t||[]).forEach(a=>{a.contact_id&&(n[a.contact_id]=(n[a.contact_id]||0)+1)}),n},enabled:!!s,staleTime:6e4})}function U5s(){const s=sa();return mt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_pipeline").select(` id, deal_name, contact_id, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(r)throw r;const n={};return(t||[]).forEach(a=>{a.contact_id&&!n[a.contact_id]&&(n[a.contact_id]=a)}),n},enabled:!!s})}function q5s({contactId:s,compact:t=!1}){const{data:r}=xL(),{data:n}=O4s(s),a=MTe(),i=Nht(),l=z4s(),[o,c]=k.useState(!1),[d,h]=k.useState(""),m=k.useRef(null),x=new Set((n==null?void 0:n.map(N=>N.tag_id))||[]),y=(r==null?void 0:r.filter(N=>N.name.toLowerCase().includes(d.toLowerCase())))||[],v=r==null?void 0:r.find(N=>N.name.toLowerCase()===d.trim().toLowerCase()),w=async N=>{x.has(N.id)?await l.mutateAsync({contactId:s,tagId:N.id}):await i.mutateAsync({contactId:s,tagId:N.id})},b=async()=>{if(!(!d.trim()||v))try{const N=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:N.id}),h("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[n==null?void 0:n.map(N=>{var S,T,A;return e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((S=N.tag)==null?void 0:S.color)||"#6366F1",color:((T=N.tag)==null?void 0:T.color)||"#6366F1"},children:[e.jsx(wh,{className:"h-2.5 w-2.5"}),(A=N.tag)==null?void 0:A.name,e.jsx("button",{onClick:I=>{I.stopPropagation(),l.mutate({contactId:s,tagId:N.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(vr,{className:"h-2.5 w-2.5"})})]},N.id)}),e.jsxs(To,{open:o,onOpenChange:c,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:N=>N.stopPropagation(),children:[e.jsx($s,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(_o,{className:"w-56 p-2",align:"start",onClick:N=>N.stopPropagation(),children:[e.jsx(Ne,{ref:m,placeholder:"Search or create tag...",value:d,onChange:N=>h(N.target.value),onKeyDown:N=>{N.key==="Enter"&&d.trim()&&!v?(N.preventDefault(),b()):N.key==="Enter"&&v&&!x.has(v.id)&&(N.preventDefault(),w(v))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[y.map(N=>e.jsxs("button",{onClick:()=>w(N),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:N.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:N.name}),x.has(N.id)&&e.jsx(Kn,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},N.id)),d.trim()&&!v&&e.jsxs("button",{onClick:b,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($s,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),y.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 kUe({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(r=>{var n,a,i;return e.jsx(Ge,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((n=r.tag)==null?void 0:n.color)||"#6366F1",color:((a=r.tag)==null?void 0:a.color)||"#6366F1"},children:(i=r.tag)==null?void 0:i.name},r.tag_id)})})}const R$=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function V5s({open:s,onOpenChange:t}){const{data:r,isLoading:n}=xL(),a=MTe(),i=B4s(),l=F4s(),[o,c]=k.useState(""),[d,h]=k.useState(R$[0]),[m,x]=k.useState(null),[y,v]=k.useState(""),[w,b]=k.useState(""),N=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),h(R$[0]),cn({title:"Tag created"})}catch(I){cn({title:"Error",description:I.message,variant:"destructive"})}},S=async I=>{if(y.trim())try{await i.mutateAsync({id:I,name:y.trim(),color:w}),x(null),cn({title:"Tag updated"})}catch(D){cn({title:"Error",description:D.message,variant:"destructive"})}},T=async(I,D)=>{if(confirm(`Delete tag "${D}"? It will be removed from all contacts.`))try{await l.mutateAsync(I),cn({title:"Tag deleted"})}catch(R){cn({title:"Error",description:R.message,variant:"destructive"})}},A=I=>{x(I.id),v(I.name),b(I.color)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"New tag name...",value:o,onChange:I=>c(I.target.value),onKeyDown:I=>I.key==="Enter"&&N(),className:"flex-1 h-9"}),e.jsxs(G,{size:"sm",onClick:N,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:R$.map(I=>e.jsx("button",{onClick:()=>h(I),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===I?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:I}},I))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),r==null?void 0:r.map(I=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:m===I.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:R$.map(D=>e.jsx("button",{onClick:()=>b(D),className:`h-5 w-5 rounded-full border-2 ${w===D?"border-foreground":"border-transparent"}`,style:{backgroundColor:D}},D))}),e.jsx(Ne,{value:y,onChange:D=>v(D.target.value),onKeyDown:D=>D.key==="Enter"&&S(I.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>S(I.id),children:e.jsx(Kn,{className:"h-4 w-4 text-primary"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(null),children:e.jsx(vr,{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:I.color}}),e.jsx("span",{className:"flex-1 text-sm",children:I.name}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>A(I),children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{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:()=>T(I.id,I.name),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})},I.id))]})]})})}function H5s({open:s,onOpenChange:t}){const{data:r,isLoading:n}=WI(),a=l3e(),i=$$t(),l=U$t(),[o,c]=k.useState(""),[d,h]=k.useState(null),[m,x]=k.useState(""),y=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(N){ue.error(N.message||"Failed to add lead source")}},v=async N=>{if(m.trim())try{await i.mutateAsync({id:N,name:m.trim()}),h(null)}catch(S){ue.error(S.message||"Failed to update")}},w=async(N,S)=>{if(confirm(`Remove lead source "${S}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(N)}catch(T){ue.error(T.message||"Failed to remove")}},b=N=>{h(N.id),x(N.name)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"New lead source name...",value:o,onChange:N=>c(N.target.value),onKeyDown:N=>N.key==="Enter"&&y(),className:"flex-1 h-9"}),e.jsxs(G,{size:"sm",onClick:y,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(r==null?void 0:r.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),r==null?void 0:r.map(N=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===N.id?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{value:m,onChange:S=>x(S.target.value),onKeyDown:S=>S.key==="Enter"&&v(N.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>v(N.id),children:e.jsx(Kn,{className:"h-4 w-4 text-primary"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(null),children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:N.name}),N.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>b(N),children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{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:()=>w(N.id,N.name),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),!N.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},N.id))]})]})})}function Bht({value:s,onChange:t,label:r="Lead Source"}){const{data:n}=WI(),a=l3e(),[i,l]=k.useState(!1),[o,c]=k.useState(""),d=async()=>{if(o.trim())try{const h=await a.mutateAsync(o.trim());h&&(t(h.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:r}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{value:s||"_none",onValueChange:h=>t(h==="_none"?"":h),children:[e.jsx(As,{className:"flex-1",children:e.jsx(Ls,{placeholder:"Select lead source"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"_none",children:"No source"}),n==null?void 0:n.map(h=>e.jsx(ct,{value:h.id,children:h.name},h.id))]})]}),e.jsx(G,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(vr,{className:"h-4 w-4"}):e.jsx($s,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"New lead source name...",value:o,onChange:h=>c(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d())},className:"flex-1"}),e.jsx(G,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function hke({contactId:s,currentSpouseContactId:t,currentSpouseName:r,currentSpouseEmail:n,onLink:a,onUnlink:i,isEditing:l}){const o=br(),[c,d]=k.useState(!1),[h,m]=k.useState(""),{data:x}=mt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:v,error:w}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(w)throw w;return v},enabled:!!t}),{data:y}=mt({queryKey:["spouse-search",h],queryFn:async()=>{let v=V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").neq("id",s).order("first_name").limit(20);h.trim()&&(v=v.or(`first_name.ilike.%${h}%,last_name.ilike.%${h}%,email.ilike.%${h}%,phone.ilike.%${h}%`));const{data:w,error:b}=await v;if(b)throw b;return w},enabled:c});if(t&&x){const v=`${x.first_name} ${x.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{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(Di,{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/${x.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:v}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[x.phone,x.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(n3,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${x.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(r||n)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{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(Di,{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:r}),n&&e.jsx("span",{className:"text-xs text-muted-foreground block truncate",children:n})]}),l&&e.jsxs(To,{open:c,onOpenChange:d,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(tl,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(_o,{className:"w-72 p-2",align:"end",children:e.jsx(SUe,{search:h,setSearch:m,results:y,onSelect:v=>{a(v),d(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(To,{open:c,onOpenChange:d,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(_o,{className:"w-72 p-2",align:"start",children:e.jsx(SUe,{search:h,setSearch:m,results:y,onSelect:v=>{a(v),d(!1),m("")}})})]})]}):null}function SUe({search:s,setSearch:t,results:r,onSelect:n}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Qa,{className:"max-h-48",children:r&&r.length>0?e.jsx("div",{className:"space-y-0.5",children:r.map(a=>e.jsxs("button",{onClick:()=>n(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"})})]})}function G5s(){var Qn;const s=br(),[t,r]=Ac(),{user:n}=js(),a=gL(),i=Xt(),l=t.get("type"),o=t.get("filter")??t.get("status"),c=t.get("new")==="true",{contactsWithScores:d,isLoading:h}=Gfe(),{activeContactIds:m,hasLeadSite:x}=X3s(),{data:y}=$5s(),{data:v}=fx(),{data:w}=U5s(),{data:b}=xL(),{data:N}=ITe(),[S,T]=k.useState(new Set),[A,I]=k.useState("any"),D=Ufe(),R=a3e(),$=i3e(),F=Xrt(),[z,Q]=k.useState(""),[K,X]=k.useState(!1),[Z,re]=k.useState(l||"all"),[le,oe]=k.useState(o||"all"),[ne,ie]=k.useState("date-added"),[ye,ce]=k.useState(c),[ve,be]=k.useState(null),[Ue,Be]=k.useState(!1),[De,Ae]=k.useState(!1),[He,Le]=k.useState(null),[Ie,Te]=k.useState(""),[xe,et]=k.useState(new Set),[fe,it]=k.useState(!1),Oe=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Ye,We]=k.useState(Oe),_e=k.useCallback(Gt=>{We(gr=>{const zt=typeof Gt=="function"?Gt(gr):Gt;return r(Se=>{const ze=new URLSearchParams(Se);return zt<=1?ze.delete("page"):ze.set("page",String(zt)),ze},{replace:!0}),zt})},[]),[Re,tt]=k.useState(50),[Ke,Ze]=k.useState("my"),[lt,xt]=k.useState(!1),[Xe,Je]=k.useState(!1),{data:jt}=yg(),{addToLeadPond:ns}=qot(jt==null?void 0:jt.teamId),Ns=!!((Qn=jt==null?void 0:jt.team)!=null&&Qn.lead_pond_enabled&&(jt!=null&&jt.teamId)),Ys=!!(jt!=null&&jt.teamId),[rs,bt]=k.useState([]),[cs,yt]=k.useState(!1),is=Gt=>{bt([Gt]),yt(!0)},Bs=Gt=>{bt(Gt),yt(!0)},ps=Gt=>{jt!=null&&jt.teamId&&ns.mutate({contact_id:Gt,team_id:jt.teamId})},lr=Gt=>{jt!=null&&jt.teamId&&Gt.forEach(gr=>{ns.mutate({contact_id:gr,team_id:jt.teamId})})},kr=k.useCallback(Gt=>{it(!1),et(gr=>{const zt=new Set(gr);return zt.has(Gt)?zt.delete(Gt):zt.add(Gt),zt})},[]);k.useEffect(()=>{if(!(n!=null&&n.id))return;const Gt=V.channel(`innercircle_contacts_inserts_${n.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${n.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{V.removeChannel(Gt)}},[i,n==null?void 0:n.id]),k.useEffect(()=>{o&&oe(o)},[o]);const[Lr,qr]=k.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});k.useEffect(()=>{c&&ce(!0)},[c]),k.useEffect(()=>{var Gt;ve&&qr({first_name:ve.first_name||"",last_name:ve.last_name||"",email:ve.email||"",phone:ve.phone||"",address:ve.address||"",city:ve.city||"",state:ve.state||"",zip_code:ve.zip_code||"",birthday:ve.birthday||"",home_anniversary:ve.home_anniversary||"",spouse_name:ve.spouse_name||"",spouse_email:ve.spouse_email||"",lead_source_id:ve.lead_source_id||"",notes:ve.notes||"",tagIds:((Gt=ve.tags)==null?void 0:Gt.map(gr=>gr.relationship_type_id))||[]})},[ve]);const Ur=k.useMemo(()=>{if(!d)return[];let Gt=d.filter(gr=>{var st,gt,At,Ft,Wt;const zt=z===""||`${gr.first_name} ${gr.last_name}`.toLowerCase().includes(z.toLowerCase())||((st=gr.email)==null?void 0:st.toLowerCase().includes(z.toLowerCase()))||((gt=gr.phone)==null?void 0:gt.includes(z))||((At=gr.city)==null?void 0:At.toLowerCase().includes(z.toLowerCase()))||((Ft=gr.state)==null?void 0:Ft.toLowerCase().includes(z.toLowerCase())),Se=Z==="all"||((Wt=gr.tags)==null?void 0:Wt.some(Vt=>Vt.relationship_type_id===Z)),ze=S.size===0||(()=>{const Vt=(N==null?void 0:N.filter(Jt=>Jt.contact_id===gr.id).map(Jt=>Jt.tag_id))||[];return A==="any"?Vt.some(Jt=>S.has(Jt)):Array.from(S).every(Jt=>Vt.includes(Jt))})();return zt&&Se&&ze});return le==="not-touched-90"?Gt=Gt.filter(gr=>{const zt=gr.relationshipScore.daysSinceTouch;return zt===null||zt>90}):le==="at-risk"?Gt=Gt.filter(gr=>gr.relationshipScore.status==="at-risk"):le==="cooling"?Gt=Gt.filter(gr=>gr.relationshipScore.status==="cooling"):le==="warm"?Gt=Gt.filter(gr=>gr.relationshipScore.status==="warm"):le==="has-deal"?Gt=Gt.filter(gr=>w&&w[gr.id]):le==="no-deal"?Gt=Gt.filter(gr=>!w||!w[gr.id]):le==="open-house"?Gt=Gt.filter(gr=>{var Se;return(((Se=gr.lead_source_ref)==null?void 0:Se.name)||gr.lead_source)==="Open House"}):le==="website-active"?Gt=Gt.filter(gr=>m.has(gr.id)):le==="never-contacted"?Gt=Gt.filter(gr=>gr.relationshipScore.daysSinceTouch===null):le==="vips"?Gt=Gt.filter(gr=>gr.relationshipScore.score>=80):le==="missing-info"?Gt=Gt.filter(gr=>{var zt,Se;return!((zt=gr.email)!=null&&zt.trim())&&!((Se=gr.phone)!=null&&Se.trim())}):le==="birthdays-soon"?Gt=Gt.filter(gr=>{const zt=HC(gr.birthday);return zt!==null&&zt<=30}):le==="anniversary-soon"?Gt=Gt.filter(gr=>{const zt=HC(gr.home_anniversary);return zt!==null&&zt<=30}):le==="in-drip"?Gt=Gt.filter(gr=>((y==null?void 0:y[gr.id])??0)>0):le==="not-in-drip"&&(Gt=Gt.filter(gr=>((y==null?void 0:y[gr.id])??0)===0)),Gt=[...Gt].sort((gr,zt)=>{switch(ne){case"important-dates":{const Se=HC(gr.birthday),ze=HC(zt.birthday),st=HC(gr.home_anniversary),gt=HC(zt.home_anniversary),At=[Se,st].filter(Wt=>Wt!==null).sort((Wt,Vt)=>(Wt??1/0)-(Vt??1/0))[0]??1/0,Ft=[ze,gt].filter(Wt=>Wt!==null).sort((Wt,Vt)=>(Wt??1/0)-(Vt??1/0))[0]??1/0;return At-Ft}case"last-touched":{const Se=gr.relationshipScore.lastTouchDate,ze=zt.relationshipScore.lastTouchDate;return!Se&&!ze?0:Se?ze?new Date(Se).getTime()-new Date(ze).getTime():1:-1}case"next-touch":{const Se=gr.relationshipScore.daysSinceTouch,ze=zt.relationshipScore.daysSinceTouch;return Se===null&&ze===null?0:Se===null?-1:ze===null?1:ze-Se}case"score":return gr.relationshipScore.score-zt.relationshipScore.score;case"date-added":{const Se=gr.created_at,ze=zt.created_at;return!Se&&!ze?0:Se?ze?new Date(ze).getTime()-new Date(Se).getTime():-1:1}case"name":default:{const Se=`${gr.first_name||""} ${gr.last_name||""}`.toLowerCase(),ze=`${zt.first_name||""} ${zt.last_name||""}`.toLowerCase();return Se.localeCompare(ze)}}}),Gt},[d,z,Z,S,A,le,ne,w,N,m,y]),Mr=Ur.length,Cr=Math.max(1,Math.ceil(Mr/Re)),Xr=Math.min(Ye,Cr),Ln=k.useMemo(()=>{const Gt=(Xr-1)*Re;return Ur.slice(Gt,Gt+Re)},[Ur,Xr,Re]),Zs=k.useRef(!1);k.useEffect(()=>{if(!Zs.current){Zs.current=!0;return}_e(1)},[z,Z,S,A,le,ne]);const Yr=k.useCallback(()=>{it(!1),et(Gt=>Gt.size>0?new Set:new Set(Ln.map(gr=>gr.id)))},[Ln]),ss=k.useCallback(()=>{it(!0),et(new Set(Ur.map(Gt=>Gt.id)))},[Ur]),ta=k.useCallback((Gt,gr)=>{Q(Gt.search||""),re(Gt.type||"all"),oe(Gt.status||"all"),ie(gr||"name")},[]),nn=()=>{qr({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},hr=async Gt=>{Gt.preventDefault();const gr={...Lr,lead_source_id:Lr.lead_source_id||null};ve?(await R.mutateAsync({id:ve.id,...gr}),be(null)):(await D.mutateAsync(gr),ce(!1)),nn()},Pr=async Gt=>{confirm("Are you sure you want to delete this contact?")&&await $.mutateAsync(Gt)};return e.jsx(ws,{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"})]}),jt&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>Ze("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ke==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(jt.team.contact_visibility==="full_team"||jt.team.contact_visibility==="leader_only"&&jt.role==="team_leader")&&e.jsxs("button",{onClick:()=>Ze("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Ke==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Team"]}),jt.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>Ze("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Ke==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(ky,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx($o,{className:"h-4 w-4 mr-1"}),"Back"]})}),Ke==="team"?e.jsx(m5e,{}):Ke==="lead-pond"&&jt?e.jsx(f5e,{teamId:jt.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(R5s,{contacts:d,contactDealsMap:w,websiteActiveIds:m,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"}[le]??null,onSelect:Gt=>{const zt=Gt?{"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"}[Gt]:"all";oe(zt),_e(1)}}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-3",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or phone...",value:z,onChange:Gt=>Q(Gt.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-2 sm:space-y-0",children:[e.jsxs(G,{onClick:()=>X(!0),className:"sm:hidden w-full h-11 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white border-0 shadow-sm",children:[e.jsx(mc,{className:"h-4 w-4 mr-2"}),"View Geographic Heat Map"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:hidden",children:[e.jsxs(G,{onClick:()=>ce(!0),className:"h-10 w-full justify-center",children:[e.jsx($s,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"Add Contact"})]}),e.jsxs(G,{variant:"outline",onClick:()=>Be(!0),className:"h-10 w-full justify-center",children:[e.jsx(da,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"Import CSV"})]}),e.jsxs(G,{variant:"outline",onClick:()=>Ae(!0),className:"h-10 w-full justify-center",children:[e.jsx(ig,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"truncate",children:"From Phone"})]}),e.jsx("div",{className:"w-full [&>*]:w-full [&_button]:w-full [&_button]:h-10 [&_button]:justify-center",children:e.jsx(gUe,{})})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 flex-wrap",children:[e.jsxs(G,{onClick:()=>ce(!0),className:"shrink-0",children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add Contact"]}),e.jsxs(G,{variant:"outline",onClick:()=>Be(!0),className:"shrink-0",children:[e.jsx(da,{className:"h-4 w-4 mr-1"}),"Import CSV"]}),e.jsxs(G,{variant:"outline",onClick:()=>Ae(!0),className:"shrink-0",children:[e.jsx(ig,{className:"h-4 w-4 mr-1"}),"Import from Phone"]}),e.jsx(gUe,{}),e.jsxs(G,{variant:"outline",onClick:()=>X(!0),className:"shrink-0 border-orange-200 text-orange-700 hover:bg-orange-50 hover:text-orange-800 dark:border-orange-900 dark:text-orange-400",children:[e.jsx(mc,{className:"h-4 w-4 mr-1"}),"Heat Map"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Is,{value:Z,onValueChange:re,children:[e.jsx(As,{className:"w-[145px] h-9 text-sm",children:e.jsx(Ls,{placeholder:"Filter by type"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),v==null?void 0:v.filter(Gt=>Gt.active).map(Gt=>e.jsx(ct,{value:Gt.id,children:Gt.name},Gt.id))]})]}),b&&b.length>0&&e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"h-9 justify-start text-sm",children:[e.jsx(wh,{className:"h-3.5 w-3.5 mr-1.5 shrink-0 text-muted-foreground"}),S.size===0?"Filter by Tags":`${S.size} tag${S.size>1?"s":""}`]})}),e.jsx(_o,{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:()=>I("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${A==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>I("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${A==="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:b.map(Gt=>{const gr=S.has(Gt.id);return e.jsxs("button",{onClick:()=>{T(zt=>{const Se=new Set(zt);return Se.has(Gt.id)?Se.delete(Gt.id):Se.add(Gt.id),Se})},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(Si,{checked:gr,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Gt.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Gt.name})]},Gt.id)})}),S.size>0&&e.jsx(G,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>T(new Set),children:"Clear tags"})]})})]}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",title:"Settings",children:e.jsx(oo,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(Pa,{onClick:()=>xt(!0),children:[e.jsx(wh,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Pa,{onClick:()=>Je(!0),children:[e.jsx(ky,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]}),e.jsxs(Is,{value:le,onValueChange:oe,children:[e.jsx(As,{className:"w-[145px] h-9 text-sm",children:e.jsx(Ls,{placeholder:"Filter by status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Status"}),e.jsx(ct,{value:"warm",children:"🟢 Warm"}),e.jsx(ct,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(ct,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(ct,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(ct,{value:"no-deal",children:"📭 No Deal"}),e.jsx(ct,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(ct,{value:"website-active",children:"🌐 Website Active"}),e.jsx(ct,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(ct,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(Is,{value:ne,onValueChange:ie,children:[e.jsx(As,{className:"w-[165px] h-9 text-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ls,{placeholder:"Sort by"})]})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"name",children:"Name (A-Z)"}),e.jsx(ct,{value:"important-dates",children:"Important Dates"}),e.jsx(ct,{value:"last-touched",children:"Last Touched"}),e.jsx(ct,{value:"next-touch",children:"Next Touch Due"}),e.jsx(ct,{value:"score",children:"Relationship Score"}),e.jsx(ct,{value:"date-added",children:"Date Added"})]})]}),e.jsx(D5s,{currentFilters:{search:z,type:Z,status:le},currentSortBy:ne,onApplySmartList:ta})]})]})})}),e.jsx(P5s,{selectedIds:xe,contacts:Ur,onClearSelection:()=>{et(new Set),it(!1)},showLeadPondAction:Ns,onSendToLeadPond:lr,showTransferAction:Ys,onTransfer:Bs}),xe.size>0&&xe.size===Ln.length&&!fe&&Mr>Re&&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 ",Ln.length," contacts on this page are selected."]}),e.jsxs(G,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:ss,children:["Select all ",Mr.toLocaleString()," matching contacts"]})]}),fe&&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 ",Mr.toLocaleString()," matching contacts are selected.",e.jsx(G,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{et(new Set),it(!1)},children:"Clear selection"})]}),Mr>Re&&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 ",(Xr-1)*Re+1,"–",Math.min(Xr*Re,Mr)," of ",Mr.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"sm",disabled:Xr<=1,onClick:()=>_e(1),children:"First"}),e.jsx(G,{variant:"outline",size:"sm",disabled:Xr<=1,onClick:()=>_e(Gt=>Gt-1),children:e.jsx($o,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Xr," of ",Cr]}),e.jsx(G,{variant:"outline",size:"sm",disabled:Xr>=Cr,onClick:()=>_e(Gt=>Gt+1),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"sm",disabled:Xr>=Cr,onClick:()=>_e(Cr),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:h?e.jsx(ke,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):Ur.length===0?e.jsx(ke,{className:"p-6 text-center text-muted-foreground",children:z||Z!=="all"||le!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):Ln.map(Gt=>{var zt,Se,ze;const{relationshipScore:gr}=Gt;return e.jsx(ke,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const st=new URLSearchParams;z&&st.set("search",z),Z!=="all"&&st.set("type",Z),le!=="all"&&st.set("filter",le);const gt=st.toString();s(`/mission-control/contacts/${Gt.id}${gt?`?${gt}`:""}`)},children:e.jsx(Pe,{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:[Gt.first_name," ",Gt.last_name]}),e.jsx(NUe,{count:(y==null?void 0:y[Gt.id])??0}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Gt.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:Gt.email})]}),Gt.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Cn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Gt.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(LO,{score:gr,size:"sm"}),e.jsx(uke,{contact:Gt}),(((zt=Gt.lead_source_ref)==null?void 0:zt.name)||Gt.lead_source)&&e.jsx(Ge,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Se=Gt.lead_source_ref)==null?void 0:Se.name)||Gt.lead_source}),(ze=Gt.tags)==null?void 0:ze.map(st=>{var gt;return e.jsx(Ge,{variant:"secondary",className:"text-xs",children:(gt=st.relationship_type)==null?void 0:gt.name},st.id)}),e.jsx(kUe,{contactId:Gt.id,tags:N==null?void 0:N.filter(st=>st.contact_id===Gt.id)}),e.jsx(jUe,{deal:w==null?void 0:w[Gt.id]})]}),e.jsx(wUe,{birthday:Gt.birthday,homeAnniversary:Gt.home_anniversary,className:"mb-2",contactId:Gt.id,contactName:`${Gt.first_name}${Gt.last_name?" "+Gt.last_name:""}`,contactAddress:[Gt.address,Gt.city,Gt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[gr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),_s(new Date(gr.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Gt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),_s(Fl(Gt.birthday),"MMM d")]}),Gt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-3 w-3"}),_s(Fl(Gt.home_anniversary),"MMM d")]}),Gt.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($s,{className:"h-3 w-3"}),"Added ",_s(new Date(Gt.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:st=>st.stopPropagation(),children:e.jsx(yUe,{contact:Gt,onEdit:be,onDelete:Pr,onSnooze:(st,gt)=>{Le(st),Te(gt)},showLeadPondAction:Ns,onSendToLeadPond:ps,showTransferAction:Ys,onTransfer:is})})]})})},Gt.id)})}):e.jsx(ke,{children:e.jsx(Pe,{className:"p-0 overflow-x-auto",children:e.jsxs(Bn,{className:"min-w-[800px]",children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[40px]",children:e.jsx(Si,{checked:Ln.length>0&&Ln.every(Gt=>xe.has(Gt.id)),onCheckedChange:()=>Yr()})}),e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Score"}),e.jsx(Nt,{children:"Contact Info"}),e.jsx(Nt,{children:"Types / Pipeline"}),e.jsx(Nt,{children:"Last Contact"}),e.jsx(Nt,{className:"cursor-pointer select-none",onClick:()=>ie(ne==="date-added"?"name":"date-added"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Date Added",ne==="date-added"&&e.jsx(Ad,{className:"h-3 w-3"})]})}),e.jsx(Nt,{children:"Important Dates"}),e.jsx(Nt,{className:"w-[50px]",children:"Actions"})]})}),e.jsx($n,{children:h?e.jsx(Ds,{children:e.jsx(dt,{colSpan:10,className:"text-center py-8",children:"Loading contacts..."})}):Ur.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:z||Z!=="all"||le!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):Ln.map(Gt=>{var Se,ze,st;const{relationshipScore:gr}=Gt,zt=w==null?void 0:w[Gt.id];return e.jsxs(Ds,{className:`cursor-pointer hover:bg-accent/50 ${xe.has(Gt.id)?"bg-accent/30":""}`,onClick:()=>{const gt=new URLSearchParams;z&>.set("search",z),Z!=="all"&>.set("type",Z),le!=="all"&>.set("status",le);const At=gt.toString();s(`/mission-control/contacts/${Gt.id}${At?`?${At}`:""}`)},children:[e.jsx(dt,{onClick:gt=>gt.stopPropagation(),children:e.jsx(Si,{checked:xe.has(Gt.id),onCheckedChange:()=>kr(Gt.id)})}),e.jsx(dt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[Gt.first_name," ",Gt.last_name]}),e.jsx(NUe,{count:(y==null?void 0:y[Gt.id])??0})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(LO,{score:gr,size:"sm"}),e.jsx(uke,{contact:Gt})]})}),e.jsx(dt,{children:e.jsx(LO,{score:gr,size:"sm",showScore:!0})}),e.jsx(dt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[Gt.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Vs,{className:"h-3 w-3"}),Gt.email]}),Gt.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Cn,{className:"h-3 w-3"}),Gt.phone]})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(((Se=Gt.lead_source_ref)==null?void 0:Se.name)||Gt.lead_source)&&e.jsx(Ge,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((ze=Gt.lead_source_ref)==null?void 0:ze.name)||Gt.lead_source}),(st=Gt.tags)==null?void 0:st.map(gt=>{var At;return e.jsx(Ge,{variant:"secondary",className:"text-xs",children:(At=gt.relationship_type)==null?void 0:At.name},gt.id)}),e.jsx(kUe,{contactId:Gt.id,tags:N==null?void 0:N.filter(gt=>gt.contact_id===Gt.id)}),e.jsx(jUe,{deal:zt})]})}),e.jsx(dt,{children:e.jsx("div",{className:"text-sm",children:gr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(fn,{className:"h-3 w-3"}),_s(new Date(gr.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-muted-foreground text-xs italic",children:"Never contacted"})})}),e.jsx(dt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Gt.created_at?_s(new Date(Gt.created_at),"MMM d, yyyy"):"—"})}),e.jsx(dt,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(wUe,{birthday:Gt.birthday,homeAnniversary:Gt.home_anniversary,contactId:Gt.id,contactName:`${Gt.first_name}${Gt.last_name?" "+Gt.last_name:""}`,contactAddress:[Gt.address,Gt.city,Gt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Gt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),_s(Fl(Gt.birthday),"MMM d")]}),Gt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(En,{className:"h-3 w-3"}),_s(Fl(Gt.home_anniversary),"MMM d")]})]})]})}),e.jsx(dt,{children:e.jsx(yUe,{contact:Gt,onEdit:be,onDelete:Pr,onSnooze:(gt,At)=>{Le(gt),Te(At)},showLeadPondAction:Ns,onSendToLeadPond:ps,showTransferAction:Ys,onTransfer:is})})]},Gt.id)})})]})})}),Mr>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 ",(Xr-1)*Re+1,"–",Math.min(Xr*Re,Mr)," of ",Mr.toLocaleString()," contacts"]}),e.jsxs(Is,{value:String(Re),onValueChange:Gt=>{tt(Number(Gt)),_e(1)},children:[e.jsx(As,{className:"w-[80px] h-8",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"50",children:"50"}),e.jsx(ct,{value:"100",children:"100"}),e.jsx(ct,{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(G,{variant:"outline",size:"sm",disabled:Xr<=1,onClick:()=>_e(1),children:"First"}),e.jsx(G,{variant:"outline",size:"sm",disabled:Xr<=1,onClick:()=>_e(Gt=>Gt-1),children:e.jsx($o,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Xr," of ",Cr]}),e.jsx(G,{variant:"outline",size:"sm",disabled:Xr>=Cr,onClick:()=>_e(Gt=>Gt+1),children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"sm",disabled:Xr>=Cr,onClick:()=>_e(Cr),children:"Last"})]})]}),e.jsx(fs,{open:ye||!!ve,onOpenChange:Gt=>{Gt||(ce(!1),be(null),nn())},children:e.jsxs(ms,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:ve?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:hr,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"first_name",children:"First Name *"}),e.jsx(Ne,{id:"first_name",value:Lr.first_name,onChange:Gt=>qr({...Lr,first_name:Gt.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Ne,{id:"last_name",value:Lr.last_name,onChange:Gt=>qr({...Lr,last_name:Gt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:Lr.email,onChange:Gt=>qr({...Lr,email:Gt.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone"}),e.jsx(Ne,{id:"phone",value:Lr.phone,onChange:Gt=>qr({...Lr,phone:Gt.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"address",children:"Address"}),e.jsx(Ne,{id:"address",value:Lr.address,onChange:Gt=>qr({...Lr,address:Gt.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:Lr.city,onChange:Gt=>qr({...Lr,city:Gt.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:Lr.state,onChange:Gt=>qr({...Lr,state:Gt.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"zip_code",children:"Zip"}),e.jsx(Ne,{id:"zip_code",value:Lr.zip_code,onChange:Gt=>qr({...Lr,zip_code:Gt.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"birthday",children:"Birthday"}),e.jsx(Ne,{id:"birthday",type:"date",value:Lr.birthday,onChange:Gt=>qr({...Lr,birthday:Gt.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(Ne,{id:"home_anniversary",type:"date",value:Lr.home_anniversary,onChange:Gt=>qr({...Lr,home_anniversary:Gt.target.value})})]})]}),ve&&e.jsx(hke,{contactId:ve.id,currentSpouseContactId:(ve==null?void 0:ve.spouse_contact_id)||null,currentSpouseName:(ve==null?void 0:ve.spouse_name)||null,currentSpouseEmail:(ve==null?void 0:ve.spouse_email)||null,onLink:Gt=>F.mutate({contactId:ve.id,spouseContactId:Gt}),onUnlink:()=>F.mutate({contactId:ve.id,spouseContactId:null}),isEditing:!0}),e.jsx(Bht,{value:Lr.lead_source_id,onChange:Gt=>qr({...Lr,lead_source_id:Gt})}),e.jsxs("div",{children:[e.jsx(he,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v==null?void 0:v.filter(Gt=>Gt.active).map(Gt=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Si,{checked:Lr.tagIds.includes(Gt.id),onCheckedChange:gr=>{qr(gr?{...Lr,tagIds:[...Lr.tagIds,Gt.id]}:{...Lr,tagIds:Lr.tagIds.filter(zt=>zt!==Gt.id)})}}),e.jsx("span",{className:"text-sm",children:Gt.name})]},Gt.id))})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"notes",children:"Notes"}),e.jsx(or,{id:"notes",value:Lr.notes,onChange:Gt=>qr({...Lr,notes:Gt.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>{ce(!1),be(null),nn()},children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:D.isPending||R.isPending,children:[ve?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(t5s,{open:Ue,onOpenChange:Be,relationshipTypes:(v==null?void 0:v.filter(Gt=>Gt.active))||[],onSuccess:()=>{Be(!1)}}),e.jsx(n5s,{open:De,onOpenChange:Ae,onComplete:()=>Ae(!1)}),e.jsx(xxe,{open:!!He,onOpenChange:Gt=>{Gt||Le(null)},contactId:He||"",contactName:Ie}),e.jsx(V5s,{open:lt,onOpenChange:xt}),e.jsx(H5s,{open:Xe,onOpenChange:Je}),e.jsx(z5s,{open:K,onOpenChange:X,contacts:d||[],onCitySelect:Gt=>{Q(Gt),_e(1)}}),e.jsx(Vot,{open:cs,onOpenChange:yt,contactIds:rs,contactNames:rs.map(Gt=>{const gr=Ur.find(zt=>zt.id===Gt);return gr?`${gr.first_name} ${gr.last_name||""}`.trim():""}),onComplete:()=>{bt([]),et(new Set),it(!1)}})]})]})})}const W5s="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function K5s({open:s,onOpenChange:t,contact:r}){var K;const{user:n}=js(),a=br(),i=Xt(),{intakePage:l,isLoading:o}=gxe(),{isGmailConnected:c,gmailEmail:d}=Eh(),h=qfe(),{data:m}=mt({queryKey:["profile-for-invite",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&s,queryFn:async()=>{const{data:X}=await V.from("profiles").select("name, email, avatar_url").eq("id",n.id).maybeSingle();return X}}),x=(m==null?void 0:m.name)||((K=n==null?void 0:n.email)==null?void 0:K.split("@")[0])||"Your Agent",y=x.split(" ")[0],v=l?`https://contacts.relevelup.com/${l.slug}`:"",w=k.useMemo(()=>`Hi ${r.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!`,[r.first_name]),[b,N]=k.useState("gmail"),[S,T]=k.useState(""),[A,I]=k.useState(""),[D,R]=k.useState(!1);k.useEffect(()=>{s&&(T(`Quick favor, ${r.first_name} — can you update your info?`),I(w),N(c?"gmail":"system"))},[s,w,r.first_name,c]);const $=k.useMemo(()=>A.split(/\n\n+/).map(X=>`

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

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

A note from ${x}

${$}

Update Your Info

Takes about a minute — promise

Share My Info →

${v}

Sent with care by ${x}

Powered by ReLevelUp

`,z=async()=>{if(!l){ue.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!S.trim()||!A.trim()){ue.error("Subject and message are required");return}R(!0);const X=F();try{if(b==="gmail"&&c){const{data:Z,error:re}=await V.functions.invoke("gmail-send",{body:{to:r.email,subject:S,body:X,contactId:r.id}});if(re)throw re;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Failed to send")}else{const{data:Z,error:re}=await V.functions.invoke("send-connect-invite",{body:{contactEmail:r.email,subject:S,htmlBody:X,replyToEmail:(m==null?void 0:m.email)||(n==null?void 0:n.email),agentName:x}});if(re)throw re;if(!(Z!=null&&Z.success))throw new Error((Z==null?void 0:Z.error)||"Failed to send")}try{await h.mutateAsync({contactId:r.id,actionTypeId:W5s,notes:`Sent Connect Page invite — Subject: "${S}"`})}catch(Z){console.warn("Failed to log activity:",Z)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ue.success("Connect Page invite sent!"),t(!1)}catch(Z){console.error("Send error:",Z),ue.error(Z instanceof Error?Z.message:"Failed to send invite")}finally{R(!1)}},Q=F();return e.jsx(fs,{open:s,onOpenChange:X=>!D&&t(X),children:e.jsxs(ms,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(jr,{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:[r.first_name," ",r.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(es,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(On,{value:b,onValueChange:X=>N(X),className:"mt-1.5",children:e.jsxs(Rn,{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(jr,{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:b==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(m==null?void 0:m.email)||(n==null?void 0:n.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(Ne,{id:"invite-subject",value:S,onChange:X=>T(X.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(or,{id:"invite-message",value:A,onChange:X=>I(X.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(he,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Qr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:Q,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(G,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsx(G,{onClick:z,disabled:D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Oi,{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(G,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function Y5s(s){return mt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Z5s(s){return mt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function RTe(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("client_portals").insert({deal_id:r.deal_id,owner_user_id:s,slug:"",is_enabled:r.is_enabled??!0,visibility:r.visibility||"private",require_onboarding:r.require_onboarding??!0,allow_spouse:r.allow_spouse??!1,client_name:r.client_name||null,client_email:r.client_email||null,client_phone:r.client_phone||null,invite_method:r.invite_method||"email"}).select().single();if(a)throw a;return n},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["client-portal",n.deal_id]})}})}function vL(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("client_portals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function zht(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function $ht(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function Uht(){const s=Xt();return Ct({mutationFn:async({id:t,dealId:r})=>{await V.from("portal_updates").delete().eq("portal_id",t);const{error:n}=await V.from("client_portals").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function X5s(s){return mt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function qht(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.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(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["portal-updates",r.portal_id]})}})}function Q5s(){const s=sa();return mt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function J5s(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("portal_custom_questions").insert({owner_user_id:s,question_text:r.question_text,field_type:r.field_type,options:r.options||[],is_required:r.is_required||!1,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function eTs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("portal_custom_questions").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function tTs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function yv(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function sTs({contactId:s}){const t=br(),r=Xt(),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(null),w=vL(),b=qht(),{data:N,isLoading:S}=mt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:$,error:F}=await V.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(F)throw F;if(!$||$.length===0)return[];const z=$.map(X=>X.id),{data:Q,error:K}=await V.from("client_portals").select("*").in("deal_id",z).is("archived_at",null);if(K)throw K;return(Q||[]).map(X=>({...X,deal:$.find(Z=>Z.id===X.deal_id)}))},enabled:!!s}),T=(N==null?void 0:N.map($=>$.id))||[],{data:A}=mt({queryKey:["contact-portal-updates",T],queryFn:async()=>{if(T.length===0)return{};const{data:$,error:F}=await V.from("portal_updates").select("*").in("portal_id",T).order("created_at",{ascending:!1});if(F)throw F;const z={};return($||[]).forEach(Q=>{z[Q.portal_id]||(z[Q.portal_id]=Q)}),z},enabled:T.length>0}),I=$=>{navigator.clipboard.writeText(yv($)),a($),ue.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},D=async $=>{d.trim()&&(await b.mutateAsync({portal_id:$,title:d,content:m||void 0}),c(!1),h(""),x(""),r.invalidateQueries({queryKey:["contact-portal-updates"]}),ue.success("Portal update posted!"))},R=async()=>{y&&(await w.mutateAsync({id:y.id,welcome_message:y.welcome_message,next_step_text:y.next_step_text,is_enabled:y.is_enabled,show_post_close_tips:y.show_post_close_tips,review_url:y.review_url}),l(!1),v(null),r.invalidateQueries({queryKey:["contact-portals",s]}),ue.success("Portal settings updated!"))};return S||!N||N.length===0?null:e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(fc,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Pe,{className:"space-y-3",children:N.map($=>{var K,X,Z;const F=((K=$.stage_mapping)==null?void 0:K.length)>0?$.stage_mapping:Efe(((X=$.deal)==null?void 0:X.deal_type)||"buyer"),z=F==null?void 0:F[$.current_stage_index??0],Q=A==null?void 0:A[$.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:((Z=$.deal)==null?void 0:Z.deal_name)||"Portal"}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",z.label||z.name]})]}),e.jsx(Ge,{variant:$.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:$.is_enabled?"Active":"Disabled"})]}),Q&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:Q.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:_s(new Date(Q.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>I($.slug),children:[n===$.slug?e.jsx(Kn,{className:"h-3 w-3 mr-1"}):e.jsx(Ra,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(yv($.slug),"_blank"),children:[e.jsx(Qr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(fs,{open:o,onOpenChange:c,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(xi,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(Ne,{value:d,onChange:re=>h(re.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Details (optional)"}),e.jsx(or,{value:m,onChange:re=>x(re.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(G,{onClick:()=>D($.id),disabled:!d.trim()||b.isPending,className:"w-full",children:[e.jsx(en,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(fs,{open:i,onOpenChange:l,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{v({...$}),l(!0)},children:[e.jsx(oo,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Portal Settings"})}),y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Portal Enabled"}),e.jsx(_r,{checked:y.is_enabled,onCheckedChange:re=>v({...y,is_enabled:re})})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Welcome Message"}),e.jsx(or,{value:y.welcome_message||"",onChange:re=>v({...y,welcome_message:re.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Next Step"}),e.jsx(Ne,{value:y.next_step_text||"",onChange:re=>v({...y,next_step_text:re.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Review URL"}),e.jsx(Ne,{value:y.review_url||"",onChange:re=>v({...y,review_url:re.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Show Post-Close Tips"}),e.jsx(_r,{checked:y.show_post_close_tips,onCheckedChange:re=>v({...y,show_post_close_tips:re})})]}),e.jsx(fo,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{onClick:R,disabled:w.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(G,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${$.deal_id}`),children:[e.jsx(Ha,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),N.length>1&&e.jsx(fo,{})]},$.id)})})]})}function rTs({contactId:s}){const{data:t}=mt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await V.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}),r=t&&t.size>0,{data:n,isLoading:a}=mt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await V.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!r});if(!r||a||!n||n.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(ke,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{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(bn,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Ge,{variant:"secondary",className:"text-xs ml-auto",children:[n.length," ",n.length===1?"property":"properties"]})]})}),e.jsx(Pe,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:n.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(En,{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(fn,{className:"h-3 w-3"}),e.jsx("span",{title:_s(new Date(l.viewed_at),"PPp"),children:rl(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Qr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const nTs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function CUe({value:s,onChange:t,onAdd:r,suggestions:n,placeholder:a,icon:i}){const[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(null);k.useEffect(()=>{const m=x=>{d.current&&!d.current.contains(x.target)&&c.current&&!c.current.contains(x.target)&&o(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]);const h=n.filter(m=>m.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(Ne,{ref:c,value:s,onChange:m=>{t(m.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),h.length>0?r(h[0]):r(s))}}),n.length>0&&e.jsx(Wi,{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(G,{type:"button",variant:"outline",size:"sm",onClick:()=>r(s),children:e.jsx($s,{className:"h-4 w-4"})})]}),l&&h.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:h.map(m=>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:()=>{r(m),o(!1)},children:[i||e.jsx(Ca,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),m]},m))})]})}function aTs({contactId:s,contactName:t}){var F,z,Q;const{user:r}=js(),n=sa(),{hasLeadSite:a}=_g(),i=Xt(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState(""),{data:x}=mt({queryKey:["agent-lead-site-config",n],queryFn:async()=>{const{data:K,error:X}=await V.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",n).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(X||!K)return{cities:[],zipCodes:[]};const Z=K.theme_config||{},re=Array.isArray(Z.searchCities)?Z.searchCities:[];K.mls_market_area&&!re.includes(K.mls_market_area)&&re.unshift(K.mls_market_area);const le=Array.isArray(Z.searchZipCodes)?Z.searchZipCodes:[];return{cities:re,zipCodes:le}},enabled:!!n}),{data:y,isLoading:v}=mt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:K,error:X}=await V.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(X)throw X;return K},enabled:!!s&&!!r}),[w,b]=k.useState({}),N=()=>{b({is_active:(y==null?void 0:y.is_active)??!0,min_price:(y==null?void 0:y.min_price)??null,max_price:(y==null?void 0:y.max_price)??null,min_beds:(y==null?void 0:y.min_beds)??null,min_baths:(y==null?void 0:y.min_baths)??null,min_sqft:(y==null?void 0:y.min_sqft)??null,max_sqft:(y==null?void 0:y.max_sqft)??null,cities:(y==null?void 0:y.cities)??[],zip_codes:(y==null?void 0:y.zip_codes)??[],property_types:(y==null?void 0:y.property_types)??[],frequency:(y==null?void 0:y.frequency)??"daily"}),o(!0)},S=Ct({mutationFn:async()=>{const K={contact_id:s,owner_user_id:n,is_active:w.is_active??!0,min_price:w.min_price||null,max_price:w.max_price||null,min_beds:w.min_beds||null,min_baths:w.min_baths||null,min_sqft:w.min_sqft||null,max_sqft:w.max_sqft||null,cities:w.cities||[],zip_codes:w.zip_codes||[],property_types:w.property_types||[],frequency:w.frequency||"daily"};if(y!=null&&y.id){const{error:X}=await V.from("contact_property_alerts").update(K).eq("id",y.id);if(X)throw X}else{const{error:X}=await V.from("contact_property_alerts").insert(K);if(X)throw X}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ue.success("Property alert saved!")},onError:K=>{ue.error(K.message||"Failed to save alert")}}),T=Ct({mutationFn:async()=>{if(!(y!=null&&y.id))return;const{error:K}=await V.from("contact_property_alerts").delete().eq("id",y.id);if(K)throw K},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ue.success("Property alert removed")}}),A=K=>{var Z;const X=K.trim();X&&!((Z=w.cities)!=null&&Z.includes(X))&&b(re=>({...re,cities:[...re.cities||[],X]})),d("")},I=K=>{var Z;const X=K.trim();X&&!((Z=w.zip_codes)!=null&&Z.includes(X))&&b(re=>({...re,zip_codes:[...re.zip_codes||[],X]})),m("")},D=K=>{b(X=>{const Z=X.property_types||[];return{...X,property_types:Z.includes(K)?Z.filter(re=>re!==K):[...Z,K]}})};if(!a||v)return null;if(y&&!l)return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${y.is_active?"bg-green-500/10":"bg-muted"}`,children:y.is_active?e.jsx(_m,{className:"h-4 w-4 text-green-600"}):e.jsx(ev,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(Ge,{variant:y.is_active?"default":"secondary",className:"text-xs ml-auto",children:[y.is_active?"Active":"Paused"," · ",y.frequency]})]})}),e.jsxs(Pe,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[y.min_price||y.max_price?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(wl,{className:"h-3 w-3"}),y.min_price?`$${(y.min_price/1e3).toFixed(0)}k`:"$0"," - ",y.max_price?`$${(y.max_price/1e3).toFixed(0)}k`:"Any"]}):null,y.min_beds?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(M4,{className:"h-3 w-3"}),y.min_beds,"+ beds"]}):null,y.min_baths?e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Xf,{className:"h-3 w-3"}),y.min_baths,"+ baths"]}):null,(F=y.cities)==null?void 0:F.map(K=>e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),K]},K)),(z=y.zip_codes)==null?void 0:z.map(K=>e.jsx(Ge,{variant:"outline",children:K},K)),(Q=y.property_types)==null?void 0:Q.map(K=>e.jsx(Ge,{variant:"outline",children:K},K))]}),y.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(y.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:N,className:"flex-1",children:"Manage Alert"}),e.jsxs(G,{variant:"destructive",size:"sm",onClick:()=>T.mutate(),disabled:T.isPending,className:"flex-1",children:[T.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(vr,{className:"h-4 w-4 mr-1"}),"Remove Alert"]})]})]})]});const R=((x==null?void 0:x.cities)||[]).filter(K=>{var X;return!((X=w.cities)!=null&&X.includes(K))}),$=((x==null?void 0:x.zipCodes)||[]).filter(K=>{var X;return!((X=w.zip_codes)!=null&&X.includes(K))});return l?e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(_m,{className:"h-4 w-4 text-primary"}),y?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Alert Active"}),e.jsx(_r,{checked:w.is_active??!0,onCheckedChange:K=>b(X=>({...X,is_active:K}))})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(wl,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{type:"number",placeholder:"Min price",value:w.min_price??"",onChange:K=>b(X=>({...X,min_price:K.target.value?Number(K.target.value):null}))}),e.jsx(Ne,{type:"number",placeholder:"Max price",value:w.max_price??"",onChange:K=>b(X=>({...X,max_price:K.target.value?Number(K.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(M4,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(Is,{value:w.min_beds?String(w.min_beds):"any",onValueChange:K=>b(X=>({...X,min_beds:K==="any"?null:Number(K)})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Any"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"any",children:"Any"}),[1,2,3,4,5].map(K=>e.jsxs(ct,{value:String(K),children:[K,"+"]},K))]})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(Is,{value:w.min_baths?String(w.min_baths):"any",onValueChange:K=>b(X=>({...X,min_baths:K==="any"?null:Number(K)})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Any"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(K=>e.jsxs(ct,{value:String(K),children:[K,"+"]},K))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(J4,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{type:"number",placeholder:"Min sqft",value:w.min_sqft??"",onChange:K=>b(X=>({...X,min_sqft:K.target.value?Number(K.target.value):null}))}),e.jsx(Ne,{type:"number",placeholder:"Max sqft",value:w.max_sqft??"",onChange:K=>b(X=>({...X,max_sqft:K.target.value?Number(K.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(CUe,{value:c,onChange:d,onAdd:A,suggestions:R,placeholder:"Type to search cities..."}),w.cities&&w.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:w.cities.map(K=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[K,e.jsx("button",{onClick:()=>b(X=>{var Z;return{...X,cities:(Z=X.cities)==null?void 0:Z.filter(re=>re!==K)}}),children:e.jsx(vr,{className:"h-3 w-3"})})]},K))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(CUe,{value:h,onChange:m,onAdd:I,suggestions:$,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),w.zip_codes&&w.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:w.zip_codes.map(K=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[K,e.jsx("button",{onClick:()=>b(X=>{var Z;return{...X,zip_codes:(Z=X.zip_codes)==null?void 0:Z.filter(re=>re!==K)}}),children:e.jsx(vr,{className:"h-3 w-3"})})]},K))})]}),e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(En,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:nTs.map(K=>{var X;return e.jsx(Ge,{variant:(X=w.property_types)!=null&&X.includes(K)?"default":"outline",className:"cursor-pointer",onClick:()=>D(K),children:K},K)})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"mb-1.5",children:"Frequency"}),e.jsxs(Is,{value:w.frequency||"daily",onValueChange:K=>b(X=>({...X,frequency:K})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"daily",children:"Daily"}),e.jsx(ct,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{onClick:()=>S.mutate(),disabled:S.isPending,className:"flex-1",children:[S.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bl,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),y&&e.jsx(G,{variant:"destructive",size:"icon",onClick:()=>T.mutate(),disabled:T.isPending,children:e.jsx(vr,{className:"h-4 w-4"})})]})]})]}):e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("button",{onClick:N,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(_m,{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 iTs({contactId:s,contactName:t}){var le;const{user:r}=js(),n=sa(),{hasLeadSite:a}=_g(),i=Xt(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState([]),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(""),A=k.useRef(null),I=k.useRef(null),{data:D}=mt({queryKey:["agent-lead-site-cities",n],queryFn:async()=>{const{data:oe,error:ne}=await V.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",n).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ne||!oe)return[];const ie=oe.theme_config||{},ye=Array.isArray(ie.searchCities)?ie.searchCities:[];return oe.mls_market_area&&!ye.includes(oe.mls_market_area)&&ye.unshift(oe.mls_market_area),ye},enabled:!!n}),{data:R,isLoading:$}=mt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:oe,error:ne}=await V.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ne)throw ne;return oe},enabled:!!s&&!!r});k.useEffect(()=>{const oe=ne=>{I.current&&!I.current.contains(ne.target)&&A.current&&!A.current.contains(ne.target)&&w(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]);const F=()=>{y((R==null?void 0:R.market_report_enabled)??!1),m((R==null?void 0:R.market_report_cities)??[]),o(!0)},z=oe=>{const ne=(oe||c).trim();ne&&!h.includes(ne)&&m([...h,ne]),d(""),w(!1)},Q=(D||[]).filter(oe=>!h.includes(oe)&&oe.toLowerCase().includes(c.toLowerCase())),K=Ct({mutationFn:async()=>{const{data:oe,error:ne}=await V.functions.invoke("send-market-report",{body:{action:"preview",agentId:n,cities:(R==null?void 0:R.market_report_cities)??[]}});if(ne)throw new Error(ne.message||"Failed to generate preview");if(oe&&!oe.ok&&oe.error)throw new Error(oe.error);return oe},onSuccess:oe=>{T(oe.html),N(!0)},onError:oe=>{ue.error(oe.message||"Failed to generate preview")}}),X=Ct({mutationFn:async()=>{const{data:oe,error:ne}=await V.functions.invoke("send-market-report",{body:{action:"send",agentId:n,cities:(R==null?void 0:R.market_report_cities)??[],contactIds:[s]}});if(ne)throw new Error(ne.message||"Failed to send report");if(oe&&!oe.ok&&oe.error)throw new Error(oe.error);return oe},onSuccess:()=>{ue.success(`Market report sent to ${t}!`)},onError:oe=>{ue.error(oe.message||"Failed to send report")}}),Z=Ct({mutationFn:async()=>{const{error:oe}=await V.from("innercircle_contacts").update({market_report_enabled:x,market_report_cities:h}).eq("id",s);if(oe)throw oe},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ue.success(x?"Monthly market report enabled!":"Market report disabled")},onError:oe=>{ue.error(oe.message||"Failed to save")}}),re=Ct({mutationFn:async()=>{const{error:oe}=await V.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(oe)throw oe},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),y(!1),m([]),ue.success("Market report removed")},onError:oe=>{ue.error(oe.message||"Failed to remove market report")}});return!a||$?null:R!=null&&R.market_report_enabled&&!l?e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{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(ro,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Ge,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Pe,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((le=R.market_report_cities)==null?void 0:le.length)>0?R.market_report_cities.map(oe=>e.jsxs(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),oe]},oe)):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(G,{variant:"outline",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(bn,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(G,{variant:"default",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,className:"flex-1",children:[X.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(en,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:F,className:"flex-1",children:"Manage"}),e.jsxs(G,{variant:"destructive",size:"sm",onClick:()=>re.mutate(),disabled:re.isPending,className:"flex-1",children:[re.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(vr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(fs,{open:b,onOpenChange:N,children:e.jsxs(ms,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(ro,{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:S}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(G,{onClick:()=>{N(!1),X.mutate()},disabled:X.isPending,className:"flex-1",children:[X.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(en,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(G,{variant:"outline",onClick:()=>N(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(ro,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Send Monthly Report"}),e.jsx(_r,{checked:x,onCheckedChange:y})]}),x&&e.jsxs("div",{children:[e.jsxs(he,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Ca,{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(Ne,{ref:A,value:c,onChange:oe=>{d(oe.target.value),w(!0)},onFocus:()=>w(!0),placeholder:"Type to search cities...",onKeyDown:oe=>{oe.key==="Enter"&&(oe.preventDefault(),Q.length>0?z(Q[0]):z())}}),e.jsx(Wi,{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(G,{type:"button",variant:"outline",size:"sm",onClick:()=>z(),children:e.jsx($s,{className:"h-4 w-4"})})]}),v&&Q.length>0&&e.jsx("div",{ref:I,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:Q.map(oe=>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(oe),children:[e.jsx(Ca,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),oe]},oe))})]}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:h.map(oe=>e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[oe,e.jsx("button",{onClick:()=>m(h.filter(ne=>ne!==oe)),children:e.jsx(vr,{className:"h-3 w-3"})})]},oe))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{onClick:()=>Z.mutate(),disabled:Z.isPending,className:"flex-1",children:[Z.isPending?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bl,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Pe,{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(ro,{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 oTs(s){return mt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:r}=await V.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(r)throw console.error("[ContactDripActivity] enrollments error",r),r;const n=(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 V.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(n.length>0){const{data:c,error:d}=await V.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",n).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(h=>{var m;return{...h,campaign:{name:((m=i.get(h.campaign_id))==null?void 0:m.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function lTs(s){switch(s){case"active":return e.jsx(Ge,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Ge,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Ge,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Ge,{variant:"outline",children:"Exited"});default:return e.jsx(Ge,{variant:"outline",children:s})}}function TUe(s){return s==="sent"?e.jsx(In,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(id,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(tm,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(fn,{className:"h-4 w-4 text-muted-foreground"})}function cTs({contactId:s}){const t=br(),{data:r,isLoading:n}=oTs(s),[a,i]=k.useState(null);if(n)return null;const l=(r==null?void 0:r.enrollments)||[],o=(r==null?void 0:r.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(r3,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Pe,{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(r3,{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"}),lTs(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: ",rl(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",rl(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",rl(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(va,{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,h;return e.jsxs(fs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:m=>!m&&i(null),children:[e.jsx(vi,{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:TUe(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(xi,{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"," · ",_s(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(ms,{className:"max-w-lg",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[TUe(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:((h=c.campaign)==null?void 0:h.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:_s(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(G,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function Vht({contactId:s}={}){const{user:t}=js();return mt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const r=t.id;let n=V.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",r).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(n=n.eq("contact_id",s));let a=V.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source").eq("user_id",r).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await V.from("email_campaigns").select("id, subject").eq("user_id",r),l=(i.data||[]).map(w=>w.id),o=new Map((i.data||[]).map(w=>[w.id,w.subject]));let c=[];if(l.length>0){let w=V.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&&(w=w.eq("contact_id",s)),c=(await w).data||[]}const[d,h]=await Promise.all([n,a]),m=(d.data||[]).map(w=>({id:`g-${w.id}`,channel:w.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:w.subject,to_email:w.to_email,contact_id:w.contact_id,sent_at:w.sent_at,source:w.source})),x=(h.data||[]).map(w=>({id:`b-${w.id}`,channel:"Mass Email",subject:w.subject,to_email:w.contact_email,contact_id:w.contact_id,sent_at:w.sent_at,source:w.source})),y=c.map(w=>({id:`c-${w.id}`,channel:"Campaign",subject:o.get(w.campaign_id)||"(campaign)",to_email:w.email,contact_id:w.contact_id,sent_at:w.sent_at,source:null,campaign_id:w.campaign_id,opened_at:w.opened_at,clicked_at:w.clicked_at})),v=[...m,...x,...y];return v.sort((w,b)=>w.sent_at0&&e.jsx(Ge,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Pe,{children:r?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(Ge,{variant:"outline",className:`text-xs ${dTs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_s(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(G,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!n),children:n?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(Yn,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function hTs({videoId:s}){var l;const{data:t,isLoading:r,error:n}=C5s(s);if(r)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fs,{className:"w-full aspect-video rounded-lg"}),e.jsx(Fs,{className:"h-4 w-1/3"})]});if(n||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(id,{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 mTs({contactId:s}){const t=br(),[r,n]=k.useState(!1),{data:a,isLoading:i}=mt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:x}=await V.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(x)throw x;return m},enabled:!!s}),l=async(m,x)=>{const y=x==="done"?"todo":"done";await V.from("deal_tasks").update({status:y,completed_at:y==="done"?new Date().toISOString():null}).eq("id",m),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=mt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:m,error:x}=await V.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(x)throw x;return m},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(m=>m.status!=="done"))||[],h=(a==null?void 0:a.filter(m=>m.status==="done"))||[];return e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Kn,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>n(!0),children:e.jsx($s,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Pe,{className:"space-y-1",children:i?e.jsx(Fs,{className:"h-8 w-full"}):d.length===0&&h.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(m=>e.jsxs("button",{onClick:async()=>{await l(m.id,m.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[m.priority]," ",m.title]}),m.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:_s(new Date(m.due_date),"MMM d")})]},m.id)),h.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:[h.length," completed"]})})]})}),r&&e.jsx(fTs,{contactId:s,open:r,onOpenChange:m=>{n(m),m||o()}})]})}function fTs({contactId:s,open:t,onOpenChange:r}){const[n,a]=k.useState(""),[i,l]=k.useState("medium"),[o,c]=k.useState(),{data:d}=mt({queryKey:["session"],queryFn:async()=>{const{data:m}=await V.auth.getSession();return m.session}}),h=async()=>{var x;if(!n.trim()||!((x=d==null?void 0:d.user)!=null&&x.id))return;const{error:m}=await V.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:n.trim(),priority:i,status:"todo",due_date:o?_s(o,"yyyy-MM-dd"):null}]);if(m){console.error("Task create error:",m);return}r(!1)};return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"sm:max-w-[400px]",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(Ne,{value:n,onChange:m=>a(m.target.value),placeholder:"Task title...",onKeyDown:m=>m.key==="Enter"&&h()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Priority"}),e.jsxs("select",{value:i,onChange:m=>l(m.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(he,{children:"Due Date"}),e.jsx(Ne,{type:"date",value:o?_s(o,"yyyy-MM-dd"):"",onChange:m=>c(m.target.value?new Date(m.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(G,{onClick:h,disabled:!n.trim(),children:"Create Task"})]})]})]})})}function pTs({contactId:s}){const t=br(),{data:r,isLoading:n}=mt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await V.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 n||!r||r.length===0?null:e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Gu,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Pe,{className:"space-y-2",children:r.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(Ge,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Ge,{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(Ha,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function xTs(){var Ke,Ze,lt,xt,Xe;const{contactId:s}=Ki(),t=br(),[r]=Ac(),n=r.get("search")||"",a=r.get("type")||"all",i=r.get("status")||"all",{data:l,isLoading:o}=G9t(s||""),{data:c}=fx(),{data:d}=uB(),{data:h}=hB(3650),{data:m}=yxe(365),{data:x}=Y5s(s),{contactsWithScores:y}=Gfe(),v=a3e(),w=i3e(),b=qfe(),N=Xrt(),[S,T]=k.useState(!1),[A,I]=k.useState({}),[D,R]=k.useState(!1),[$,F]=k.useState(null),[z,Q]=k.useState(""),[K,X]=k.useState(void 0),[Z,re]=k.useState(""),[le,oe]=k.useState(null),[ne,ie]=k.useState(!1),[ye,ce]=k.useState(null),[ve,be]=k.useState(!1),{isGmailConnected:Ue,gmailEmail:Be}=Eh(),{data:De}=mt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Je,error:jt}=await V.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(jt)throw jt;return Je},enabled:!!s}),Ae=Je=>{if(!Je)return null;const jt=Je.match(/Video ID:\s*([a-f0-9-]+)/i);return jt?jt[1]:null},He=k.useMemo(()=>{if(!y)return[];let Je=y.filter(jt=>{var Ys,rs,bt;const ns=n===""||`${jt.first_name} ${jt.last_name}`.toLowerCase().includes(n.toLowerCase())||((Ys=jt.email)==null?void 0:Ys.toLowerCase().includes(n.toLowerCase()))||((rs=jt.phone)==null?void 0:rs.includes(n)),Ns=a==="all"||((bt=jt.tags)==null?void 0:bt.some(cs=>cs.relationship_type_id===a));return ns&&Ns});return i==="not-touched-90"?Je=Je.filter(jt=>{const ns=jt.relationshipScore.daysSinceTouch;return ns===null||ns>90}):i==="at-risk"?Je=Je.filter(jt=>jt.relationshipScore.status==="at-risk"):i==="cooling"?Je=Je.filter(jt=>jt.relationshipScore.status==="cooling"):i==="warm"&&(Je=Je.filter(jt=>jt.relationshipScore.status==="warm")),Je.map(jt=>jt.id)},[y,n,a,i]),Le=He.indexOf(s||""),Ie=Le>0?He[Le-1]:null,Te=Le1&&Le!==-1,et=Je=>{const jt=new URLSearchParams;n&&jt.set("search",n),a!=="all"&&jt.set("type",a),i!=="all"&&jt.set("status",i);const ns=jt.toString();return`/mission-control/contacts/${Je}${ns?`?${ns}`:""}`},fe=k.useMemo(()=>{const Je=((h==null?void 0:h.filter(ns=>ns.contact_id===s))||[]).map(ns=>{var bt,cs,yt;const Ns=Ae(ns.notes);let Ys=((bt=ns.action_type)==null?void 0:bt.name)||"Touch",rs=ns.notes;if(Ys==="Other"&&((cs=ns.notes)!=null&&cs.startsWith("["))){const is=ns.notes.indexOf("]");is>0&&(Ys=ns.notes.substring(1,is),rs=ns.notes.substring(is+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:ns.id,type:"touch",completed_at:ns.completed_at,name:Ys,color:((yt=ns.action_type)==null?void 0:yt.color)||"#3B82F6",notes:rs,videoId:Ns}}),jt=((m==null?void 0:m.filter(ns=>ns.contact_id===s))||[]).map(ns=>({id:ns.id,type:"popby",completed_at:ns.completed_at,name:"Pop-by",color:"#F97316",notes:ns.notes,videoId:null}));return[...Je,...jt].sort((ns,Ns)=>new Date(Ns.completed_at).getTime()-new Date(ns.completed_at).getTime())},[h,m,s]),it=()=>{var Je;l&&(I({first_name:l.first_name||"",last_name:l.last_name||"",email:l.email||"",phone:l.phone||"",address:l.address||"",city:l.city||"",state:l.state||"",zip_code:l.zip_code||"",birthday:l.birthday||"",home_anniversary:l.home_anniversary||"",spouse_name:l.spouse_name||"",spouse_email:l.spouse_email||"",company_name:l.company_name||"",job_title:l.job_title||"",lead_source_id:l.lead_source_id||"",notes:l.notes||"",tagIds:((Je=l.tags)==null?void 0:Je.map(jt=>jt.relationship_type_id))||[]}),T(!0))},Oe=async()=>{await v.mutateAsync({id:s,...A,lead_source_id:A.lead_source_id||null}),T(!1)},Ye=async()=>{confirm("Are you sure you want to delete this contact?")&&(await w.mutateAsync(s),t("/mission-control/contacts"))},_e=((Ke=d==null?void 0:d.find(Je=>Je.id===$))==null?void 0:Ke.name)==="Other",Re=async()=>{if(!$||_e&&!Z.trim())return;const Je=K?new Date(K.getFullYear(),K.getMonth(),K.getDate(),12,0,0).toISOString():void 0,jt=_e?`[${Z.trim()}]${z?" — "+z:""}`:z;await b.mutateAsync({contactId:s,actionTypeId:$,notes:jt,completedAt:Je}),R(!1),F(null),Q(""),X(void 0),re("")},tt=(Je,jt)=>{Ue&&l?(ce({email:Je,name:jt||`${l.first_name} ${l.last_name||""}`.trim()}),ie(!0)):window.location.href=`mailto:${Je}`};return o?e.jsx(ws,{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"})})}):l?e.jsxs(e.Fragment,{children:[e.jsx(ws,{title:`${l.first_name} ${l.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(G,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx($o,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),xe&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>Ie&&t(et(Ie)),disabled:!Ie,className:"px-2",children:[e.jsx($o,{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:[Le+1," of ",He.length]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>Te&&t(et(Te)),disabled:!Te,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(va,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[l.email&&e.jsxs(G,{variant:"outline",onClick:()=>tt(l.email,`${l.first_name} ${l.last_name||""}`.trim()),children:[e.jsx(Vs,{className:"h-4 w-4 mr-1"}),"Email"]}),l.email&&e.jsxs(G,{variant:"outline",onClick:()=>be(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(jr,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(G,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Jr,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(fs,{open:D,onOpenChange:R,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(ms,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:d==null?void 0:d.filter(Je=>Je.active).map(Je=>e.jsxs("button",{onClick:()=>F(Je.id),className:` p-3 rounded-lg border text-left transition-all ${$===Je.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:Je.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Je.description})]},Je.id))}),_e&&e.jsxs("div",{className:"mt-3",children:[e.jsx(he,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(Ne,{id:"custom-action-name",value:Z,onChange:Je=>re(Je.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Date (optional — backdate if needed)"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal mt-2",!K&&"text-muted-foreground"),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),K?_s(K,"PPP"):"Today (default)"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:K,onSelect:X,disabled:Je=>Je>new Date,initialFocus:!0,className:It("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(or,{id:"action-notes",value:z,onChange:Je=>Q(Je.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(G,{onClick:Re,disabled:!$||_e&&!Z.trim()||b.isPending,className:"w-full",children:[e.jsx(Kn,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(G,{variant:"outline",onClick:it,children:[e.jsx(sd,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(G,{variant:"destructive",size:"icon",onClick:Ye,children:e.jsx(yr,{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.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:[l.first_name," ",l.last_name||""]}),(((Ze=l.lead_source_ref)==null?void 0:Ze.name)||l.lead_source)&&e.jsx(Ge,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((lt=l.lead_source_ref)==null?void 0:lt.name)||l.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[l.email&&e.jsxs("button",{onClick:()=>tt(l.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:l.email})]}),l.phone&&e.jsxs("a",{href:`tel:${l.phone}`,className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Cn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:l.phone})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(uke,{contact:l}),(xt=l.tags)==null?void 0:xt.map(Je=>{const jt=c==null?void 0:c.find(ns=>ns.id===Je.relationship_type_id);return jt?e.jsx(Ge,{variant:"secondary",className:"text-xs",children:jt.name},Je.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(q5s,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(ke,{className:"md:col-span-2",children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Contact Information"})}),e.jsx(Pe,{children:S?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(he,{htmlFor:"first_name",children:"First Name"}),e.jsx(Ne,{id:"first_name",value:A.first_name,onChange:Je=>I({...A,first_name:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"last_name",children:"Last Name"}),e.jsx(Ne,{id:"last_name",value:A.last_name,onChange:Je=>I({...A,last_name:Je.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"email",children:"Email"}),e.jsx(Ne,{id:"email",type:"email",value:A.email,onChange:Je=>I({...A,email:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"phone",children:"Phone"}),e.jsx(Ne,{id:"phone",value:A.phone,onChange:Je=>I({...A,phone:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"address",children:"Street Address"}),e.jsx(Ne,{id:"address",value:A.address,onChange:Je=>I({...A,address:Je.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(he,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:A.city,onChange:Je=>I({...A,city:Je.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:A.state,onChange:Je=>I({...A,state:Je.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(Ne,{id:"zip_code",value:A.zip_code,onChange:Je=>I({...A,zip_code:Je.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(he,{htmlFor:"birthday",children:"Birthday"}),e.jsx(Ne,{id:"birthday",type:"date",value:A.birthday,onChange:Je=>I({...A,birthday:Je.target.value})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(Ne,{id:"home_anniversary",type:"date",value:A.home_anniversary,onChange:Je=>I({...A,home_anniversary:Je.target.value})})]})]}),e.jsx(fo,{}),e.jsx(hke,{contactId:s,currentSpouseContactId:(l==null?void 0:l.spouse_contact_id)||null,currentSpouseName:(l==null?void 0:l.spouse_name)||null,currentSpouseEmail:(l==null?void 0:l.spouse_email)||null,onLink:Je=>N.mutate({contactId:s,spouseContactId:Je}),onUnlink:()=>N.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(he,{htmlFor:"company_name",children:"Company"}),e.jsx(Ne,{id:"company_name",value:A.company_name,onChange:Je=>I({...A,company_name:Je.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"job_title",children:"Job Title"}),e.jsx(Ne,{id:"job_title",value:A.job_title,onChange:Je=>I({...A,job_title:Je.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(Bht,{value:A.lead_source_id||"",onChange:Je=>I({...A,lead_source_id:Je})}),e.jsxs("div",{children:[e.jsx(he,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:c==null?void 0:c.filter(Je=>Je.active).map(Je=>{var jt;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Si,{checked:(jt=A.tagIds)==null?void 0:jt.includes(Je.id),onCheckedChange:ns=>{var Ns;I(ns?{...A,tagIds:[...A.tagIds||[],Je.id]}:{...A,tagIds:(Ns=A.tagIds)==null?void 0:Ns.filter(Ys=>Ys!==Je.id)})}}),e.jsx("span",{className:"text-sm",children:Je.name})]},Je.id)})})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"notes",children:"Notes"}),e.jsx(or,{id:"notes",value:A.notes,onChange:Je=>I({...A,notes:Je.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{onClick:Oe,disabled:v.isPending,children:"Save Changes"}),e.jsx(G,{variant:"outline",onClick:()=>T(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[fe.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",_s(new Date(fe[0].completed_at),"MMM d, yyyy")," ","(",fe[0].name,")"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[l.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:()=>tt(l.email),className:"text-primary hover:underline truncate text-left",children:l.email})]}),l.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cn,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("a",{href:`tel:${l.phone}`,className:"text-primary hover:underline",children:l.phone})]})]}),(l.address||l.city||l.state||l.zip_code)&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[l.address&&e.jsx("span",{children:l.address}),(l.city||l.state||l.zip_code)&&e.jsxs("span",{className:"text-muted-foreground",children:[[l.city,l.state].filter(Boolean).join(", "),l.zip_code&&` ${l.zip_code}`]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[l.birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",_s(Fl(l.birthday),"MMMM d")]})]}),l.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",_s(Fl(l.home_anniversary),"MMMM d")]})]}),l.created_at&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",_s(new Date(l.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(fo,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(hke,{contactId:s,currentSpouseContactId:(l==null?void 0:l.spouse_contact_id)||null,currentSpouseName:l.spouse_name||null,currentSpouseEmail:l.spouse_email||null,onLink:Je=>N.mutate({contactId:s,spouseContactId:Je}),onUnlink:()=>N.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),(l.company_name||l.job_title)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:l.job_title&&l.company_name?`${l.job_title} at ${l.company_name}`:l.job_title||l.company_name})]})]}),e.jsx(fo,{}),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:(Xe=l.tags)!=null&&Xe.length?l.tags.map(Je=>{var jt;return e.jsx(Ge,{variant:"secondary",children:(jt=Je.relationship_type)==null?void 0:jt.name},Je.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),l.notes&&e.jsxs(e.Fragment,{children:[e.jsx(fo,{}),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:l.notes})]})]})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(Z3s,{contact:l,onLogTouch:()=>R(!0)}),e.jsx(pTs,{contactId:s}),e.jsx(sTs,{contactId:s}),e.jsx(rTs,{contactId:s}),e.jsx(aTs,{contactId:s,contactName:l.first_name}),e.jsx(iTs,{contactId:s,contactName:l.first_name}),e.jsx(mTs,{contactId:s}),e.jsx(cTs,{contactId:s}),e.jsx(uTs,{contactId:s}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Activity Log"})}),e.jsx(Pe,{children:fe.length>0?e.jsx("div",{className:"space-y-4",children:fe.map(Je=>{var jt;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:Je.color},children:Je.type==="popby"?e.jsx(ii,{className:"h-4 w-4"}):(jt=Je.name)==null?void 0:jt.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:Je.name}),Je.videoId&&e.jsxs(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>oe(Je.videoId),children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_s(new Date(Je.completed_at),"MMM d, yyyy h:mm a")}),Je.notes&&!Je.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Je.notes})]})]},Je.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),x&&x.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(xi,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-4",children:x.map(Je=>{var jt,ns;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(jt=Je.video)!=null&&jt.thumbnail_url?e.jsx("img",{src:Je.video.thumbnail_url,alt:Je.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>oe(Je.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:()=>oe(Je.video_id),children:e.jsx(Jr,{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: ",((ns=Je.video)==null?void 0:ns.title)||"Untitled Video"]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>oe(Je.video_id),children:[e.jsx(Uo,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_s(new Date(Je.created_at),"MMM d, yyyy h:mm a")}),Je.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',Je.message,'"']})]})]},Je.id)})})})]}),De&&De.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-3",children:De.map(Je=>e.jsxs(fs,{children:[e.jsx(vi,{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:Je.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Je.to_email," · ",_s(new Date(Je.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-sky-500"}),Je.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Je.to_email," · ",_s(new Date(Je.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:Je.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${Je.subject}`})})]})]},Je.id))})})]})]}),e.jsx(fs,{open:!!le,onOpenChange:Je=>!Je&&oe(null),children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Video Preview"})}),le&&e.jsx(hTs,{videoId:le})]})})]})]})}),Ue&&l&&ye&&e.jsx($v,{open:ne,onOpenChange:ie,contact:{id:l.id,first_name:l.first_name,last_name:l.last_name,email:ye.email},gmailEmail:Be}),l&&l.email&&e.jsx(K5s,{open:ve,onOpenChange:be,contact:{id:l.id,first_name:l.first_name,last_name:l.last_name,email:l.email}})]}):e.jsx(ws,{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(G,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function gTs({rangeDays:s}){const{user:t}=js(),r=Xt(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),{data:d=[],isLoading:h}=mt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let y=V.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 b=new Date(Date.now()-s*864e5).toISOString();y=y.gte("created_at",b)}const{data:v,error:w}=await y;if(w)throw w;return v||[]}}),{data:m}=mt({queryKey:["newsletter-campaign-recipients",n],enabled:!!n,queryFn:async()=>{const{data:y,error:v}=await V.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",n).order("sent_at",{ascending:!1}).limit(2e3);if(v)throw v;return y||[]}}),x=async()=>{if(!(!i||!t)){c(!0);try{const{data:y,error:v}=await V.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(v)throw v;if(!y||y.length===0){ue.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:w}=await V.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!w)throw new Error("Original campaign not found");const{data:b,error:N}=await V.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:w.subject,body_html:w.body_html,from_email:w.from_email,reply_to_email:w.reply_to_email,total_recipients:y.length,status:"draft"}).select("id").single();if(N)throw N;const S=y.map(A=>({campaign_id:b.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A{const v=y.sent_count||0,w=v>0?y.open_count/v*100:0,b=v>0?y.click_count/v*100:0,N=y.sent_at?pg(new Date,new Date(y.sent_at)):0,S=y.status==="sent"&&N>=3&&v>0&&y.open_counta(y.id),children:[e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),S&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>l(y),children:[e.jsx(Q4,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),y.status==="sent"&&v>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(O$,{icon:e.jsx(en,{className:"h-3.5 w-3.5"}),label:"Sent",value:v,sub:`of ${y.total_recipients}`}),e.jsx(O$,{icon:e.jsx(bn,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:y.open_count,sub:`${w.toFixed(1)}%`,children:e.jsx(ei,{value:w,className:"h-1 mt-1"})}),e.jsx(O$,{icon:e.jsx(qc,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:y.click_count,sub:`${b.toFixed(1)}%`,children:e.jsx(ei,{value:b,className:"h-1 mt-1"})}),e.jsx(O$,{icon:e.jsx(_A,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:y.bounce_count,sub:y.bounce_count>0?"review":"none"})]})]},y.id)})})]})}),e.jsx(Jj,{open:!!n,onOpenChange:y=>!y&&a(null),children:e.jsxs(Vb,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(e2,{children:e.jsx(t2,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:m?m.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:m.map(y=>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:y.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:y.email})]}),e.jsx("td",{className:"py-2 text-xs",children:y.opened_at?e.jsx(Ge,{variant:"default",className:"text-xs",children:_s(new Date(y.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:y.clicked_at?e.jsx(Ge,{variant:"default",className:"text-xs bg-purple-600",children:_s(new Date(y.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[y.status==="sent"&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"sent"}),y.status==="pending"&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"queued"}),y.status==="failed"&&e.jsx(Ge,{variant:"destructive",className:"text-xs",title:y.error_message||"",children:"failed"}),y.status==="suppressed"&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},y.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Ko,{open:!!i,onOpenChange:y=>!y&&l(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Resend to non-openers?"}),e.jsxs(Bo,{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(Oo,{children:[e.jsx(zo,{disabled:o,children:"Cancel"}),e.jsx(Co,{onClick:x,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Q4,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function O$({icon:s,label:t,value:r,sub:n,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:r.toLocaleString()}),n&&e.jsx("span",{className:"text-xs text-muted-foreground",children:n})]}),a]})}const EUe=["Gmail","Mass Email","Campaign","Client Portal Invite"],yTs={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 vTs(){const{user:s}=js(),{data:t=[],isLoading:r}=Vht(),[n,a]=k.useState(""),[i,l]=k.useState("all"),[o,c]=k.useState("30"),[d,h]=k.useState(!1),{gmailEmail:m}=Eh(),x=k.useMemo(()=>Array.from(new Set(t.map(b=>b.contact_id).filter(Boolean))),[t]),{data:y}=mt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,x.length],enabled:x.length>0,queryFn:async()=>{const{data:b}=await V.from("innercircle_contacts").select("id, first_name, last_name").in("id",x),N=new Map;return(b||[]).forEach(S=>{N.set(S.id,[S.first_name,S.last_name].filter(Boolean).join(" ")||"Contact")}),N}}),v=k.useMemo(()=>{const b=o==="all"?null:Date.now()-parseInt(o)*864e5,N=n.trim().toLowerCase();return t.filter(S=>{if(i!=="all"&&S.channel!==i||b&&new Date(S.sent_at).getTime(){const b={};return v.forEach(N=>{b[N.channel]=(b[N.channel]||0)+1}),b},[v]);return e.jsx(ws,{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(en,{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(G,{onClick:()=>h(!0),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"})," Send Email"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Total"}),e.jsx("p",{className:"text-2xl font-bold",children:v.length})]})}),EUe.map(b=>e.jsx(ke,{children:e.jsxs(Pe,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase truncate",children:b}),e.jsx("p",{className:"text-2xl font-bold",children:w[b]||0})]})},b))]}),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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search subject, recipient, contact...",value:n,onChange:b=>a(b.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:i,onValueChange:l,children:[e.jsx(As,{className:"w-[200px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Channels"}),EUe.map(b=>e.jsx(ct,{value:b,children:b},b))]})]}),e.jsxs(Is,{value:o,onValueChange:c,children:[e.jsx(As,{className:"w-[160px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"7",children:"Last 7 days"}),e.jsx(ct,{value:"30",children:"Last 30 days"}),e.jsx(ct,{value:"90",children:"Last 90 days"}),e.jsx(ct,{value:"365",children:"Last year"}),e.jsx(ct,{value:"all",children:"All time"})]})]})]}),e.jsx(gTs,{rangeDays:o==="all"?null:parseInt(o)}),r?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):v.length===0?e.jsx(ke,{children:e.jsxs(Pe,{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(ke,{children:e.jsx(Pe,{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("tbody",{children:v.slice(0,500).map(b=>{const N=b.contact_id?y==null?void 0:y.get(b.contact_id):null;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:_s(new Date(b.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Ge,{variant:"outline",className:yTs[b.channel],children:b.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:b.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:b.to_email}),e.jsx("td",{className:"py-3 px-4",children:b.contact_id&&N?e.jsx(Yn,{to:`/mission-control/contacts/${b.contact_id}`,className:"text-primary hover:underline",children:N}):e.jsx("span",{className:"text-muted-foreground",children:"—"})})]},b.id)})})]}),v.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",v.length," — narrow your filters to see more."]})]})})}),e.jsx($v,{open:d,onOpenChange:h,gmailEmail:m})]})})}const AUe={Crown:Zh,FileText:ln,Users:pr,Globe:fc,Star:Xn,Phone:Cn,MessageSquare:xi,PenTool:aj,Video:Jr,Gift:ii},mbe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function bTs(){var lt,xt;const s=br(),{user:t}=js(),{data:r}=fx(),{data:n}=K9t(),{data:a}=t$t(),{data:i}=Zrt(),{data:l}=uB(),{data:o}=W9t(),c=s$t(),d=Y9t(),h=X9t(),m=Q9t(),x=J9t(),y=e$t(),v=Z9t(),[w,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState(null),[I,D]=k.useState(""),[R,$]=k.useState(""),[F,z]=k.useState([]),[Q,K]=k.useState(null),[X,Z]=k.useState(null),[re,le]=k.useState(!1),[oe,ne]=k.useState(""),[ie,ye]=k.useState(""),[ce,ve]=k.useState(""),[be,Ue]=k.useState(""),Be=(Xe,Je)=>a==null?void 0:a.some(jt=>jt.plan_id===Xe&&jt.relationship_type_id===Je&&jt.active),De=Xe=>a==null?void 0:a.find(Je=>Je.relationship_type_id===Xe&&Je.active),Ae=async(Xe,Je)=>{const jt=Be(Xe,Je);await c.mutateAsync({planId:Xe,relationshipTypeId:Je,active:!jt})},He=(n==null?void 0:n.filter(Xe=>Xe.active&&!Xe.owner_user_id))||[],Le=(n==null?void 0:n.filter(Xe=>Xe.owner_user_id===(t==null?void 0:t.id)))||[],Ie=r==null?void 0:r.find(Xe=>Xe.id===w),Te=w?De(w):null,xe=n==null?void 0:n.find(Xe=>Xe.id===(Te==null?void 0:Te.plan_id)),et=async()=>{if(!I.trim())return;const Xe=await d.mutateAsync({name:I,description:R});Xe&&F.length>0&&await x.mutateAsync({planId:Xe.id,items:F}),Oe()},fe=async()=>{!I.trim()||!T||(await h.mutateAsync({id:T,name:I,description:R}),await x.mutateAsync({planId:T,items:F}),Oe())},it=Xe=>{var Je;A(Xe.id),D(Xe.name),$(Xe.description||""),z(((Je=Xe.items)==null?void 0:Je.map(jt=>({month_number:jt.month_number,action_type_id:jt.action_type_id,default_script_id:jt.default_script_id||void 0,notes:jt.notes||void 0})))||[]),S(!0)},Oe=()=>{S(!1),A(null),D(""),$(""),z([])},Ye=(Xe,Je)=>{Z(Je)},We=(Xe,Je,jt)=>{z(ns=>[...ns.filter(Ys=>Ys.month_number!==Xe),{month_number:Xe,action_type_id:Je,default_script_id:jt}]),K(null),Z(null)},_e=Xe=>{z(Je=>Je.filter(jt=>jt.month_number!==Xe))},Re=async()=>{if(!oe.trim()||!ie.trim()||!X)return;const Xe=await y.mutateAsync({actionTypeId:X,title:oe,scriptBody:ie,emailSubject:ce||void 0,tone:be||void 0});Xe&&Q!==null&&We(Q,X,Xe.id),le(!1),ne(""),ye(""),ve(""),Ue("")},tt=X?o==null?void 0:o.filter(Xe=>Xe.action_type_id===X&&Xe.active):[],Ke=Xe=>AUe[Xe||"Phone"]||Cn,Ze=Xe=>AUe[Xe||"Users"]||pr;return e.jsxs(ws,{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(G,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx($o,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(G,{onClick:()=>S(!0),className:"w-full sm:w-auto",children:[e.jsx($s,{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"}),r==null?void 0:r.filter(Xe=>Xe.active).map(Xe=>{const Je=Ze(Xe.icon),jt=(i==null?void 0:i[Xe.id])||0,ns=De(Xe.id),Ns=n==null?void 0:n.find(rs=>rs.id===(ns==null?void 0:ns.plan_id)),Ys=w===Xe.id;return e.jsxs("button",{onClick:()=>b(Xe.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Ys?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Je,{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:Xe.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[jt," contacts"]})]}),Ns?e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[e.jsx(di,{className:"h-3 w-3 mr-1"}),Ns.name.split(" ")[0]]}):e.jsx(Ge,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Xe.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:w&&Ie?e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[(()=>{const Xe=Ze(Ie.icon);return e.jsx(Xe,{className:"h-5 w-5"})})(),Ie.name," Touchpoint Plan"]}),e.jsxs(Nr,{children:["Choose a plan for your ",Ie.name," contacts"]})]}),e.jsxs(Pe,{className:"space-y-6",children:[xe&&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(di,{className:"h-4 w-4 text-green-500"}),"Currently using: ",xe.name]}),xe.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:xe.description})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>Ae(xe.id,w),children:"Disable"})]}),xe.items&&xe.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(on,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:mbe.map((Xe,Je)=>{var Ys,rs;const jt=((Ys=xe.items)==null?void 0:Ys.filter(bt=>bt.month_number===Je+1))||[],ns=(rs=jt[0])==null?void 0:rs.action_type,Ns=ns?Ke(ns.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${jt.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Xe}),Ns&&e.jsx(Ns,{className:"h-4 w-4 mx-auto mt-1",style:{color:(ns==null?void 0:ns.color)||"#3B82F6"}})]},Je)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:xe?"Switch to a Different Plan":"Choose a Plan"}),He.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"}),He.map(Xe=>{var jt;const Je=(xe==null?void 0:xe.id)===Xe.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Je?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Xe.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((jt=Xe.items)==null?void 0:jt.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:v.isPending,onClick:()=>{const ns=`${Xe.name} (Copy)`;v.mutate({sourcePlanId:Xe.id,newName:ns})},children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:Je?"outline":"default",disabled:Je||c.isPending,onClick:()=>Ae(Xe.id,w),children:Je?"Active":"Use This"})]})]},Xe.id)})]}),Le.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Le.map(Xe=>{var jt;const Je=(xe==null?void 0:xe.id)===Xe.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Je?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Xe.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((jt=Xe.items)==null?void 0:jt.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>it(Xe),children:e.jsx(R0,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>m.mutate(Xe.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})}),e.jsx(G,{size:"sm",variant:Je?"outline":"default",disabled:Je||c.isPending,onClick:()=>Ae(Xe.id,w),children:Je?"Active":"Use This"})]})]},Xe.id)})]}),He.length===0&&Le.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(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(on,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(ke,{className:"bg-muted/50",children:e.jsx(Pe,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),e.jsx(fs,{open:N,onOpenChange:Xe=>{Xe?S(!0):Oe()},children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:T?"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(he,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(Ne,{id:"plan-name",value:I,onChange:Xe=>D(Xe.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(or,{id:"plan-description",value:R,onChange:Xe=>$(Xe.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(he,{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:mbe.map((Xe,Je)=>{const jt=Je+1,ns=F.find(rs=>rs.month_number===jt),Ns=ns?l==null?void 0:l.find(rs=>rs.id===ns.action_type_id):null,Ys=Ns?Ke(Ns.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>K(Q===jt?null:jt),className:` w-full p-3 rounded-lg border text-center transition-all ${ns?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${Q===jt?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Xe}),Ys?e.jsx(Ys,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Ns==null?void 0:Ns.color)||"#3B82F6"}}):e.jsx($s,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),ns&&e.jsx("button",{type:"button",onClick:rs=>{rs.stopPropagation(),_e(jt)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(vr,{className:"h-3 w-3"})})]},Je)})}),Q!==null&&!X&&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 ",mbe[Q-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Xe=>Xe.active).map(Xe=>{const Je=Ke(Xe.icon);return e.jsxs("button",{type:"button",onClick:()=>Ye(Q,Xe.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Je,{className:"h-4 w-4",style:{color:Xe.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Xe.name})]},Xe.id)})})]}),Q!==null&&X&&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(G,{variant:"ghost",size:"sm",onClick:()=>Z(null),children:[e.jsx($o,{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:()=>We(Q,X),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"})]})}),tt==null?void 0:tt.map(Xe=>e.jsx("button",{type:"button",onClick:()=>We(Q,X,Xe.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:Xe.title}),Xe.tone&&e.jsx(Ge,{variant:"secondary",className:"text-xs mt-1",children:Xe.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Xe.script_body.substring(0,100),"..."]})]})},Xe.id)),e.jsxs("button",{type:"button",onClick:()=>le(!0),className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed bg-background hover:bg-accent transition-colors text-left",children:[e.jsx($s,{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(an,{children:[e.jsx(G,{variant:"outline",onClick:Oe,children:"Cancel"}),e.jsxs(G,{onClick:T?fe:et,disabled:!I.trim()||d.isPending||h.isPending,children:[e.jsx(Bl,{className:"h-4 w-4 mr-2"}),T?"Save Changes":"Create Plan"]})]})]})}),e.jsx(fs,{open:re,onOpenChange:le,children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-title",children:"Script Title"}),e.jsx(Ne,{id:"script-title",value:oe,onChange:Xe=>ne(Xe.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(Is,{value:be,onValueChange:Ue,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select tone..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"friendly",children:"Friendly"}),e.jsx(ct,{value:"professional",children:"Professional"}),e.jsx(ct,{value:"casual",children:"Casual"}),e.jsx(ct,{value:"formal",children:"Formal"})]})]})]}),((xt=(lt=l==null?void 0:l.find(Xe=>Xe.id===X))==null?void 0:lt.name)==null?void 0:xt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(Ne,{id:"script-email-subject",value:ce,onChange:Xe=>ve(Xe.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(he,{htmlFor:"script-body",children:"Script Content"}),e.jsx(or,{id:"script-body",value:ie,onChange:Xe=>ye(Xe.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(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsxs(G,{onClick:Re,disabled:!oe.trim()||!ie.trim()||y.isPending,children:[e.jsx(Bl,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})})]})}function _Ts(s,t,r,n){const a=d=>d*Math.PI/180,l=a(r-s),o=a(n-t),c=Math.sin(l/2)**2+Math.cos(a(s))*Math.cos(a(r))*Math.sin(o/2)**2;return 2*3958.8*Math.asin(Math.sqrt(c))}const Hht="popby_geocode_cache_v1";function wTs(){try{return JSON.parse(localStorage.getItem(Hht)||"{}")}catch{return{}}}function jTs(s){try{localStorage.setItem(Hht,JSON.stringify(s))}catch{}}function NTs({contacts:s,onLogPopby:t}){const[r,n]=k.useState(null),[a,i]=k.useState("idle"),[l,o]=k.useState(5),[c,d]=k.useState(""),[h,m]=k.useState(new Map),[x,y]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:S}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S!=null&&S.value&&d(S.value)})()},[]);const v=k.useMemo(()=>s.filter(S=>S.isDue&&(S.address||S.city&&S.state||S.zip)),[s]),w=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(S=>{n({lat:S.coords.latitude,lng:S.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};k.useEffect(()=>{if(!c||!r||v.length===0)return;let S=!1;const T=wTs(),A=new Map;v.forEach(D=>{const R=[D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase();T[R]&&A.set(D.id,T[R])}),m(new Map(A));const I=v.filter(D=>!([D.address,D.city,D.state,D.zip].filter(Boolean).join("|").toLowerCase()in T));if(I.length!==0)return y(!0),(async()=>{const D=[...I],R=async()=>{var $,F;for(;D.length&&!S;){const z=D.shift(),Q=[z.address,z.city,z.state,z.zip].filter(Boolean),K=Q.join("|").toLowerCase(),X=Q.join(", ");try{const re=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(X)}.json?limit=1&access_token=${c}`)).json();if((F=($=re==null?void 0:re.features)==null?void 0:$[0])!=null&&F.center){const[le,oe]=re.features[0].center;T[K]={lat:oe,lng:le},A.set(z.id,{lat:oe,lng:le})}else T[K]=null}catch{}}};await Promise.all([R(),R(),R(),R()]),S||(jTs(T),m(new Map(A)),y(!1))})(),()=>{S=!0}},[c,r,v]);const b=k.useMemo(()=>{if(!r)return[];const S=[];return v.forEach(T=>{const A=h.get(T.id);if(!A)return;const I=_Ts(r.lat,r.lng,A.lat,A.lng);I<=l&&S.push({...T,distanceMiles:I,lat:A.lat,lng:A.lng})}),S.sort((T,A)=>T.distanceMiles-A.distanceMiles)},[r,v,h,l]),N=S=>{const A=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${S.lat},${S.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${S.lat},${S.lng}`;window.open(A,"_blank","noopener")};return e.jsxs(ke,{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(Dt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(vA,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Is,{value:String(l),onValueChange:S=>o(Number(S)),children:[e.jsx(As,{className:"w-[110px] h-9",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"2",children:"2 miles"}),e.jsx(ct,{value:"5",children:"5 miles"}),e.jsx(ct,{value:"10",children:"10 miles"}),e.jsx(ct,{value:"25",children:"25 miles"})]})]}),e.jsxs(G,{size:"sm",variant:a==="ok"?"outline":"default",onClick:w,disabled:a==="loading",children:[a==="loading"?e.jsx(Mi,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(vA,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Ca,{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(Oi,{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&&v.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&&v.length>0&&x&&b.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{className:"h-14 w-full"}),e.jsx(Fs,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!x&&b.length===0&&v.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."]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ge,{variant:"secondary",className:"font-medium",children:[b.length," nearby"]}),x&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Mi,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:b.map(S=>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:[S.first_name," ",S.last_name]}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:S.distanceMiles<1?`${(S.distanceMiles*5280).toFixed(0)} ft`:`${S.distanceMiles.toFixed(1)} mi`}),S.daysOverdue>0&&e.jsxs(Ge,{variant:"destructive",className:"text-xs",children:[S.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[S.address,S.city,S.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S.phone&&e.jsx(G,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${S.phone}`,children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsx(G,{size:"icon",variant:"ghost",onClick:()=>N(S),className:"h-9 w-9",title:"Directions",children:e.jsx(MR,{className:"h-4 w-4"})}),e.jsxs(G,{size:"sm",onClick:()=>t(S),children:[e.jsx(ii,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},S.id))})]})]})]})}const kTs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",STs=[{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 CTs(){const s=br(),t=Cht(),{data:r}=q3s(),{data:n}=fx(),{data:a}=PTe(),{data:i}=yxe(90),{data:l}=Sm(),o=K3s(),c=G3s(),d=H3s(),h=W3s(),{data:m=[],isLoading:x}=mt({queryKey:["popby-templates"],queryFn:async()=>{const{data:re,error:le}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",kTs).order("publish_date",{ascending:!1});if(le)throw le;const{data:oe}=await V.from("template_likes").select("template_id"),{data:ne}=await V.from("template_comments").select("template_id"),ie=new Map;oe==null||oe.forEach(ce=>{ie.set(ce.template_id,(ie.get(ce.template_id)||0)+1)});const ye=new Map;return ne==null||ne.forEach(ce=>{ye.set(ce.template_id,(ye.get(ce.template_id)||0)+1)}),(re||[]).map(ce=>({...ce,likesCount:ie.get(ce.id)||0,commentsCount:ye.get(ce.id)||0}))}}),y=re=>{const le=l==null?void 0:l.find(oe=>oe.id===re);return le?`${le.first_name} ${le.last_name||""}`.trim():"Unknown"},v=re=>{if(!re)return null;const le=r==null?void 0:r.find(oe=>oe.id===re);return(le==null?void 0:le.name)||null},[w,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[I,D]=k.useState(!1),[R,$]=k.useState({popby_item_id:"",notes:""}),[F,z]=k.useState({name:"",description:""}),Q=async()=>{w&&(await c.mutateAsync({contact_id:w.id,popby_item_id:R.popby_item_id||void 0,notes:R.notes||void 0}),S(!1),b(null),$({popby_item_id:"",notes:""}))},K=async()=>{F.name.trim()&&(await d.mutateAsync({name:F.name.trim(),description:F.description.trim()||void 0}),D(!1),z({name:"",description:""}))},X=async(re,le)=>{await h.mutateAsync({relationship_type_id:re,frequency_days:parseInt(le)})},Z=re=>{var oe;const le=a==null?void 0:a.find(ne=>ne.relationship_type_id===re);return((oe=le==null?void 0:le.frequency_days)==null?void 0:oe.toString())||"90"};return e.jsx(ws,{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(ke,{children:e.jsxs(Pe,{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(ke,{children:e.jsxs(Pe,{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(ke,{children:e.jsxs(Pe,{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(G,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(G,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(oo,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(G,{variant:"outline",onClick:()=>D(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(On,{defaultValue:"due",children:[e.jsxs(Rn,{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(ts,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(NTs,{contacts:t||[],onLogPopby:re=>{b(re),S(!0)}}),!t||t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(ii,{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(re=>e.jsx(ke,{className:"hover:shadow-md transition-shadow",children:e.jsx(Pe,{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:[re.first_name," ",re.last_name]}),re.daysOverdue>0&&e.jsxs(Ge,{variant:"destructive",className:"text-xs",children:[re.daysOverdue,"+ days overdue"]}),re.daysSinceLastPopby===null&&e.jsx(Ge,{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:[re.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),re.city||re.address]}),re.tags&&re.tags.length>0&&e.jsx("span",{children:re.tags.map(le=>{var oe;return(oe=le.relationship_type)==null?void 0:oe.name}).join(", ")})]}),re.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",_s(new Date(re.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[re.phone&&e.jsx(G,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${re.phone}`,children:e.jsx(Cn,{className:"h-4 w-4"})})}),e.jsxs(G,{size:"sm",onClick:()=>{b(re),S(!0)},children:[e.jsx(di,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},re.id))})]}),e.jsx(ts,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(fn,{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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Pe,{className:"space-y-3",children:i.map(re=>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(ii,{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:y(re.contact_id)}),v(re.popby_item_id)&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:v(re.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:_s(new Date(re.completed_at),"MMM d, yyyy h:mm a")}),re.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:re.notes})]})]},re.id))})]})}),e.jsx(ts,{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:[r==null?void 0:r.map(re=>e.jsx(ke,{children:e.jsx(Pe,{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(ii,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:re.name}),re.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:re.description}),!re.owner_user_id&&e.jsx(Ge,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},re.id)),e.jsx(ke,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>D(!0),children:e.jsx(Pe,{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($s,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(ts,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[m.length," template",m.length!==1?"s":""," found"]}),x&&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((re,le)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx(Fs,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Fs,{className:"h-5 w-3/4 mb-2"}),e.jsx(Fs,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Fs,{className:"h-5 w-16"}),e.jsx(Fs,{className:"h-5 w-20"})]})]})},le))}),!x&&m.length===0&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Il,{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."})]})}),!x&&m.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:m.map(re=>e.jsxs(ke,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${re.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:re.preview_image_url?e.jsx("img",{src:re.preview_image_url,alt:re.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(Pe,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:re.name}),re.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:r8(re.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Ge,{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(jh,{className:"h-3.5 w-3.5"}),re.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),re.commentsCount]})]}),e.jsxs(G,{size:"sm",className:"w-full gap-2",onClick:le=>{le.stopPropagation(),s(`/templates/${re.id}`)},children:[e.jsx(Qr,{className:"h-4 w-4"}),"View Template"]})]})]},re.id))})]})]}),e.jsx(fs,{open:N,onOpenChange:S,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Log Popby for ",w==null?void 0:w.first_name," ",w==null?void 0:w.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Popby Item (optional)"}),e.jsxs(Is,{value:R.popby_item_id,onValueChange:re=>$(le=>({...le,popby_item_id:re})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a popby item..."})}),e.jsx(Ms,{children:r==null?void 0:r.map(re=>e.jsx(ct,{value:re.id,children:re.name},re.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Notes (optional)"}),e.jsx(or,{placeholder:"Any notes about this popby...",value:R.notes,onChange:re=>$(le=>({...le,notes:re.target.value}))})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx(G,{onClick:Q,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(fs,{open:T,onOpenChange:A,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{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."}),n==null?void 0:n.map(re=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(he,{className:"font-medium",children:re.name}),e.jsxs(Is,{value:Z(re.id),onValueChange:le=>X(re.id,le),children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:STs.map(le=>e.jsx(ct,{value:le.value,children:le.label},le.value))})]})]},re.id))]}),e.jsx(an,{children:e.jsx(G,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(fs,{open:I,onOpenChange:D,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Name *"}),e.jsx(Ne,{placeholder:"e.g., Homemade cookies",value:F.name,onChange:re=>z(le=>({...le,name:re.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(or,{placeholder:"Optional description...",value:F.description,onChange:re=>z(le=>({...le,description:re.target.value}))})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(G,{onClick:K,disabled:!F.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const TTs=qb({property_address:io().min(1,"Property address is required"),city:io().optional(),state:io().optional(),zip:io().optional(),transaction_type:cet(["buyer","seller"]),close_date:io().min(1,"Close date is required"),sale_price:aO().min(0,"Sale price must be positive"),commission_amount:aO().optional(),lead_source_id:io().optional(),client_type_id:io().optional(),contact_id:io().optional(),notes:io().optional(),is_win:t6t()});function Ght({open:s,onOpenChange:t,transaction:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(""),m=Vfe(),x=q$t(),{data:y}=WI(),{data:v}=fx(),{data:w}=Sm(),b=Ufe(),N=l3e(),{data:S}=Hfe(),T=(S==null?void 0:S.show_commission)??!0,A=Lfe({resolver:Pfe(TTs),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}});k.useEffect(()=>{r?A.reset({property_address:r.property_address,city:r.city||"",state:r.state||"",zip:r.zip||"",transaction_type:r.transaction_type,close_date:r.close_date,sale_price:Number(r.sale_price),commission_amount:r.commission_amount?Number(r.commission_amount):void 0,lead_source_id:r.lead_source_id||void 0,client_type_id:r.client_type_id||void 0,contact_id:r.contact_id||void 0,notes:r.notes||"",is_win:r.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})},[r,A]);const I=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};r?await x.mutateAsync({id:r.id,...z}):await m.mutateAsync(z),t(!1)},D=async()=>{if(!i.trim())return;const[F,...z]=i.trim().split(" "),Q=z.join(" ")||null,K=await b.mutateAsync({first_name:F,last_name:Q,tagIds:[]});K&&(A.setValue("contact_id",K.id),l(""),c(!1),a(!1))},R=async()=>{if(!d.trim())return;const F=await N.mutateAsync(d.trim());F&&(A.setValue("lead_source_id",F.id),h(""))},$=w==null?void 0:w.find(F=>F.id===A.watch("contact_id"));return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(ys,{children:e.jsx(gs,{children:r?"Edit Transaction":"Add Transaction"})}),e.jsx(Qa,{className:"max-h-[70vh] pr-4",children:e.jsx(Dfe,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(I),className:"space-y-4",children:[e.jsx(td,{control:A.control,name:"property_address",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Property Address *"}),e.jsx(Bc,{children:e.jsx(Ne,{placeholder:"123 Main St",...F})}),e.jsx(lf,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(td,{control:A.control,name:"city",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"City"}),e.jsx(Bc,{children:e.jsx(Ne,{placeholder:"City",...F})})]})}),e.jsx(td,{control:A.control,name:"state",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"State"}),e.jsx(Bc,{children:e.jsx(Ne,{placeholder:"TX",...F})})]})}),e.jsx(td,{control:A.control,name:"zip",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Zip"}),e.jsx(Bc,{children:e.jsx(Ne,{placeholder:"75001",...F})})]})})]}),e.jsx(td,{control:A.control,name:"transaction_type",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Transaction Type *"}),e.jsxs(Is,{onValueChange:F.onChange,value:F.value,children:[e.jsx(Bc,{children:e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select type"})})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"buyer",children:"Buyer"}),e.jsx(ct,{value:"seller",children:"Seller"})]})]}),e.jsx(lf,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(td,{control:A.control,name:"close_date",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Close Date *"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"date",...F})}),e.jsx(lf,{})]})}),e.jsx(td,{control:A.control,name:"sale_price",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Sale Price *"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"number",placeholder:"0",...F,onChange:z=>F.onChange(Number(z.target.value))})}),e.jsx(lf,{})]})})]}),T&&e.jsx(td,{control:A.control,name:"commission_amount",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Commission"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"number",placeholder:"0",...F,value:F.value??"",onChange:z=>F.onChange(z.target.value?Number(z.target.value):void 0)})})]})}),e.jsx(td,{control:A.control,name:"lead_source_id",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Lead Source"}),e.jsxs(Is,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(Bc,{children:e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select source"})})}),e.jsx(Ms,{children:y==null?void 0:y.map(z=>e.jsx(ct,{value:z.id,children:z.name},z.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Add custom source...",value:d,onChange:F=>h(F.target.value),className:"flex-1"}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:R,disabled:!d.trim(),children:e.jsx($s,{className:"h-4 w-4"})})]}),e.jsx(td,{control:A.control,name:"client_type_id",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Client Type"}),e.jsxs(Is,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(Bc,{children:e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select client type"})})}),e.jsx(Ms,{children:v==null?void 0:v.map(z=>e.jsx(ct,{value:z.id,children:z.name},z.id))})]})]})}),e.jsx(td,{control:A.control,name:"contact_id",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Client Contact"}),e.jsxs(To,{open:n,onOpenChange:a,children:[e.jsx(Eo,{asChild:!0,children:e.jsx(Bc,{children:e.jsxs(G,{variant:"outline",role:"combobox",className:It("w-full justify-between",!F.value&&"text-muted-foreground"),children:[$?`${$.first_name} ${$.last_name||""}`.trim():"Select contact",e.jsx(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(_o,{className:"w-full p-0",align:"start",children:[e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search contacts..."}),e.jsxs(ax,{children:[e.jsx(ix,{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(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(ox,{children:w==null?void 0:w.map(z=>e.jsxs(cf,{value:`${z.first_name} ${z.last_name||""}`,onSelect:()=>{F.onChange(z.id),a(!1)},children:[e.jsx(Kn,{className:It("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(Ne,{placeholder:"Enter contact name...",value:i,onChange:z=>l(z.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",onClick:D,disabled:!i.trim()||b.isPending,children:"Add Contact"}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(td,{control:A.control,name:"notes",render:({field:F})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Notes"}),e.jsx(Bc,{children:e.jsx(or,{placeholder:"Any notes about this transaction...",...F})})]})}),e.jsx(td,{control:A.control,name:"is_win",render:({field:F})=>e.jsxs(Oc,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Fc,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Bc,{children:e.jsx(_r,{checked:F.value,onCheckedChange:F.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:m.isPending||x.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}function OTe({transactions:s,showCommission:t,isLoading:r,agentNameMap:n,readOnly:a}){const[i,l]=k.useState(null),[o,c]=k.useState(null),[d,h]=k.useState(""),[m,x]=k.useState("all"),[y,v]=k.useState("all"),[w,b]=k.useState("all"),[N,S]=k.useState(!1),T=V$t(),A=Vfe(),{data:I}=WI();fx();const D=gL(),R=z=>{const{id:Q,created_at:K,updated_at:X,lead_source:Z,client_type:re,contact:le,...oe}=z;A.mutate(oe)},$=()=>{o&&(T.mutate(o),c(null))},F=s.filter(z=>{var le,oe,ne,ie;const Q=d===""||z.property_address.toLowerCase().includes(d.toLowerCase())||((oe=(le=z.contact)==null?void 0:le.first_name)==null?void 0:oe.toLowerCase().includes(d.toLowerCase()))||((ie=(ne=z.contact)==null?void 0:ne.last_name)==null?void 0:ie.toLowerCase().includes(d.toLowerCase())),K=m==="all"||z.transaction_type===m,X=y==="all"||z.lead_source_id===y,Z=w==="all"||z.client_type_id===w,re=!N||z.is_win;return Q&&K&&X&&Z&&re});return r?e.jsx(ke,{children:e.jsx(Pe,{className:"p-6 space-y-4",children:[1,2,3].map(z=>e.jsx(Fs,{className:"h-16 w-full"},z))})}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{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(Dt,{children:["Transactions (",F.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search...",value:d,onChange:z=>h(z.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(Is,{value:m,onValueChange:x,children:[e.jsx(As,{className:"w-[100px]",children:e.jsx(Ls,{placeholder:"Type"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),e.jsx(ct,{value:"buyer",children:"Buyer"}),e.jsx(ct,{value:"seller",children:"Seller"})]})]}),e.jsxs(Is,{value:y,onValueChange:v,children:[e.jsx(As,{className:"w-[130px]",children:e.jsx(Ls,{placeholder:"Lead Source"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Sources"}),I==null?void 0:I.map(z=>e.jsx(ct,{value:z.id,children:z.name},z.id))]})]}),e.jsxs(G,{variant:N?"default":"outline",size:"sm",onClick:()=>S(!N),children:[e.jsx(Yl,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Pe,{children:F.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):D?e.jsx("div",{className:"space-y-3",children:F.map(z=>e.jsxs(ke,{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(Yl,{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(Ge,{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: "}),aDe(z.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),lc(z.sale_price)]}),t&&z.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),lc(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]}),n&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[z.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>l(z),children:e.jsx(sd,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>R(z),children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(z.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})]},z.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[n&&e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Property"}),e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Close Date"}),e.jsx(Nt,{children:"Sale Price"}),t&&e.jsx(Nt,{children:"Commission"}),e.jsx(Nt,{children:"Lead Source"}),e.jsx(Nt,{children:"Client"}),!a&&e.jsx(Nt,{className:"w-[50px]"})]})}),e.jsx($n,{children:F.map(z=>{var Q;return e.jsxs(Ds,{children:[n&&e.jsx(dt,{className:"font-medium text-sm",children:n[z.owner_user_id]||"Unknown"}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[z.is_win&&e.jsx(Yl,{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(dt,{children:e.jsx(Ge,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})}),e.jsx(dt,{children:aDe(z.close_date)}),e.jsx(dt,{children:lc(z.sale_price)}),t&&e.jsx(dt,{children:z.commission_amount?lc(z.commission_amount):"-"}),e.jsx(dt,{children:((Q=z.lead_source)==null?void 0:Q.name)||"-"}),e.jsx(dt,{children:z.contact?`${z.contact.first_name} ${z.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(dt,{children:e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",children:e.jsx(Yx,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(Pa,{onClick:()=>l(z),children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Pa,{onClick:()=>R(z),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Pa,{onClick:()=>c(z.id),className:"text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},z.id)})})]})})})]}),e.jsx(Ght,{open:!!i,onOpenChange:z=>!z&&l(null),transaction:i||void 0}),e.jsx(Ko,{open:!!o,onOpenChange:z=>!z&&c(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Transaction?"}),e.jsx(Bo,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:$,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Wht({goals:s,stats:t,year:r,showCommission:n}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===r?a:12,l=12-i,o=(x,y)=>{if(!y||y===0)return null;const v=Math.min(x/y*100,100),w=Math.max(y-x,0),b=l>0?w/l:0,N=i/12*100,S=v>=N?"ahead":v>=N*.8?"on-track":"behind";return{percent:v,remaining:w,pace:b,status:S}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),h=n?o(t.totalCommission,s.gci_goal):null,m=x=>{switch(x){case"ahead":return e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(bo,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Ge,{variant:"secondary",children:[e.jsx(av,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Ge,{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(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pd,{className:"h-5 w-5 text-primary"}),e.jsxs(Dt,{children:[r," Goals Progress"]})]})}),e.jsx(Pe,{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"}),m(c.status)]}),e.jsx(ei,{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"}),m(d.status)]}),e.jsx(ei,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[lc(t.totalVolume,!0)," of ",lc(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 ",lc(d.pace,!0),"/month"]})]}),n&&s.gci_goal&&h&&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"}),m(h.status)]}),e.jsx(ei,{value:h.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[lc(t.totalCommission,!0)," of ",lc(s.gci_goal,!0)]}),e.jsxs("span",{children:[Math.round(h.percent),"%"]})]}),h.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",lc(h.pace,!0),"/month"]})]})]})})]})}const ETs={light:"",dark:".dark"},Kht=k.createContext(null);function Yht(){const s=k.useContext(Kht);if(!s)throw new Error("useChart must be used within a ");return s}const Zht=k.forwardRef(({id:s,className:t,children:r,config:n,...a},i)=>{const l=k.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(Kht.Provider,{value:{config:n},children:e.jsxs("div",{"data-chart":o,ref:i,className:It("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(ATs,{id:o,config:n}),e.jsx(HA,{children:r})]})})});Zht.displayName="Chart";const ATs=({id:s,config:t})=>{const r=Object.entries(t).filter(([n,a])=>a.theme||a.color);return r.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(ETs).map(([n,a])=>` ${a} [data-chart=${s}] { ${r.map(([i,l])=>{var c;const o=((c=l.theme)==null?void 0:c[n])||l.color;return o?` --color-${i}: ${o};`:null}).join(` `)} } `).join(` `)}}):null},Xht=k.forwardRef(({active:s,payload:t,className:r,indicator:n="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:h,nameKey:m,labelKey:x},y)=>{const{config:v}=Yht(),w=k.useMemo(()=>{var I;if(a||!(t!=null&&t.length))return null;const[N]=t,S=`${x||N.dataKey||N.name||"value"}`,T=mke(v,N,S),A=!x&&typeof l=="string"?((I=v[l])==null?void 0:I.label)||l:T==null?void 0:T.label;return o?e.jsx("div",{className:It("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:It("font-medium",c),children:A}):null},[l,o,t,a,c,v,x]);if(!s||!(t!=null&&t.length))return null;const b=t.length===1&&n!=="dot";return e.jsxs("div",{ref:y,className:It("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",r),children:[b?null:w,e.jsx("div",{className:"grid gap-1.5",children:t.map((N,S)=>{const T=`${m||N.name||N.dataKey||"value"}`,A=mke(v,N,T),I=h||N.payload.fill||N.color;return e.jsx("div",{className:It("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",n==="dot"&&"items-center"),children:d&&(N==null?void 0:N.value)!==void 0&&N.name?d(N.value,N.name,N,S,N.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.icon,{}):!i&&e.jsx("div",{className:It("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":n==="dot","w-1":n==="line","w-0 border-[1.5px] border-dashed bg-transparent":n==="dashed","my-0.5":b&&n==="dashed"}),style:{"--color-bg":I,"--color-border":I}}),e.jsxs("div",{className:It("flex flex-1 justify-between leading-none",b?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[b?w:null,e.jsx("span",{className:"text-muted-foreground",children:(A==null?void 0:A.label)||N.name})]}),N.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:N.value.toLocaleString()})]})]})},N.dataKey)})})]})});Xht.displayName="ChartTooltip";const MTs=k.forwardRef(({className:s,hideIcon:t=!1,payload:r,verticalAlign:n="bottom",nameKey:a},i)=>{const{config:l}=Yht();return r!=null&&r.length?e.jsx("div",{ref:i,className:It("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",s),children:r.map(o=>{const c=`${a||o.dataKey||"value"}`,d=mke(l,o,c);return e.jsxs("div",{className:It("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});MTs.displayName="ChartLegend";function mke(s,t,r){if(typeof t!="object"||t===null)return;const n="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let a=r;return r in t&&typeof t[r]=="string"?a=t[r]:n&&r in n&&typeof n[r]=="string"&&(a=n[r]),a in s?s[a]:s[r]}const F$=["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 FTe({stats:s,year:t}){const r=s.transactionsByMonth.some(a=>a.count>0),n=s.leadSourceBreakdown.length>0;return!r&&!n?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[r&&e.jsxs(ke,{className:"overflow-hidden",children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Pe,{className:"overflow-hidden",children:e.jsx(Zht,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(HA,{width:"100%",height:"100%",children:e.jsxs(oht,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(Vut,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(K3,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Y3,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Bf,{content:e.jsx(Xht,{})}),e.jsx(Rb,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Pe,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(HA,{width:"100%",height:"100%",children:e.jsxs(lht,{children:[e.jsx(zv,{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(EB,{fill:F$[i%F$.length]},`cell-${i}`))}),e.jsx(Bf,{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:F$[i%F$.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function ITs(s){if(!s||!s.trim())return null;const t=s.trim(),r=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const n of r)try{const a=r4e(t,n,new Date);if(tje(a))return _s(a,"yyyy-MM-dd")}catch{}try{const n=new Date(t);if(tje(n))return _s(n,"yyyy-MM-dd")}catch{}return null}const LTs=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function PTs({open:s,onOpenChange:t}){const[r,n]=k.useState([]),[a,i]=k.useState(!1),[l,o]=k.useState(0),{data:c}=WI(),{data:d}=fx(),h=Vfe(),m=()=>{const N=LTs.join(","),S=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),T=`${N} ${S}`,A=new Blob([T],{type:"text/csv"}),I=URL.createObjectURL(A),D=document.createElement("a");D.href=I,D.download="transaction-import-template.csv",D.click(),URL.revokeObjectURL(I)},x=N=>{const S=N.split(` `).filter(A=>A.trim());if(S.length<2)return[];const T=S[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return S.slice(1).map((A,I)=>{var oe,ne,ie,ye;const D=[];let R="",$=!1;for(const ce of A)ce==='"'?$=!$:ce===","&&!$?(D.push(R.trim()),R=""):R+=ce;D.push(R.trim());const F=ce=>{var be;const ve=T.indexOf(ce);return ve>=0?(be=D[ve])==null?void 0:be.replace(/^["']|["']$/g,"").trim():""},z=(oe=F("transaction_type"))==null?void 0:oe.toLowerCase(),Q=(ne=F("sale_price"))==null?void 0:ne.replace(/[$,]/g,""),K=(ie=F("commission_amount"))==null?void 0:ie.replace(/[$,]/g,""),X=(ye=F("is_win"))==null?void 0:ye.toLowerCase(),Z=F("close_date"),re=ITs(Z);let le;return F("property_address")?["buyer","seller"].includes(z)?re?(!Q||isNaN(Number(Q)))&&(le="Invalid sale price"):le=`Invalid date format: "${Z}" - use MM/DD/YYYY or YYYY-MM-DD`:le='Transaction type must be "buyer" or "seller"':le="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:re||"",sale_price:Number(Q)||0,commission_amount:K?Number(K):null,lead_source_name:F("lead_source"),client_type_name:F("client_type"),is_win:["yes","true","1"].includes(X),notes:F("notes"),error:le}})},y=N=>{var A;const S=(A=N.target.files)==null?void 0:A[0];if(!S)return;const T=new FileReader;T.onload=I=>{var $;const D=($=I.target)==null?void 0:$.result,R=x(D);n(R)},T.readAsText(S)},v=async()=>{const N=r.filter(A=>!A.error);if(N.length===0){ue.error("No valid transactions to import");return}i(!0),o(0);let S=0,T=0;for(let A=0;A$.name.toLowerCase()===I.lead_source_name.toLowerCase()),R=d==null?void 0:d.find($=>$.name.toLowerCase()===I.client_type_name.toLowerCase());await h.mutateAsync({property_address:I.property_address,city:I.city||null,state:I.state||null,zip:I.zip||null,transaction_type:I.transaction_type,close_date:I.close_date,sale_price:I.sale_price,commission_amount:I.commission_amount,lead_source_id:(D==null?void 0:D.id)||null,client_type_id:(R==null?void 0:R.id)||null,contact_id:null,notes:I.notes||null,is_win:I.is_win}),S++}catch(D){T++,console.error("Failed to import transaction:",D)}o(Math.round((A+1)/N.length*100))}i(!1),S>0&&ue.success(`Imported ${S} transaction${S>1?"s":""}`),T>0&&ue.error(`Failed to import ${T} transaction${T>1?"s":""}`),n([]),t(!1)},w=r.filter(N=>!N.error).length,b=r.filter(N=>N.error).length;return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Import Transactions"}),e.jsx(Hr,{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(G,{variant:"outline",onClick:m,children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(Ne,{id:"csv-file",type:"file",accept:".csv",onChange:y})]}),r.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ge,{variant:"outline",children:[r.length," rows found"]}),w>0&&e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(Kn,{className:"h-3 w-3 mr-1"}),w," valid"]}),b>0&&e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"}),b," errors"]})]}),e.jsx(Qa,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((N,S)=>e.jsxs("div",{className:`p-2 rounded text-sm ${N.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:N.property_address||"(no address)"}),e.jsx(Ge,{variant:N.transaction_type==="buyer"?"default":"secondary",children:N.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[N.close_date," • $",N.sale_price.toLocaleString()]}),N.error&&e.jsx(c5e,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(d5e,{className:"text-xs",children:N.error})})]},S)),r.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.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(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:v,disabled:w===0||a,children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Import ",w," Transaction",w!==1?"s":""]})]})]})]})})}const DTs=qb({transactions_goal:aO().min(0).optional(),volume_goal:aO().min(0).optional(),gci_goal:aO().min(0).optional()});function RTs({open:s,onOpenChange:t,year:r,existingGoals:n}){const a=H$t(),{data:i}=Hfe(),l=(i==null?void 0:i.show_commission)??!0,o=Lfe({resolver:Pfe(DTs),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});k.useEffect(()=>{n?o.reset({transactions_goal:n.transactions_goal??void 0,volume_goal:n.volume_goal?Number(n.volume_goal):void 0,gci_goal:n.gci_goal?Number(n.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,o,s]);const c=async d=>{await a.mutateAsync({year:r,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:[r," Goals"]}),e.jsx(Hr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(Dfe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(td,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Transactions Goal"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(pce,{children:"Total number of deals you want to close"}),e.jsx(lf,{})]})}),e.jsx(td,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"Volume Goal ($)"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(pce,{children:"Total sales volume you want to achieve"}),e.jsx(lf,{})]})}),l&&e.jsx(td,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Oc,{children:[e.jsx(Fc,{children:"GCI Goal ($)"}),e.jsx(Bc,{children:e.jsx(Ne,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:h=>d.onChange(h.target.value?Number(h.target.value):void 0)})}),e.jsx(pce,{children:"Gross commission income target"}),e.jsx(lf,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function BTe({transactions:s,isLoading:t}){const r=k.useRef(null),n=k.useRef(null),a=k.useRef([]),i=k.useRef(null),{isAdmin:l}=js(),[o,c]=k.useState(""),[d,h]=k.useState(!0),[m,x]=k.useState(0),[y,v]=k.useState(!1),w=s.filter(N=>N.latitude!=null&&N.longitude!=null),b=s.filter(N=>N.latitude==null||N.longitude==null);return k.useEffect(()=>{(async()=>{h(!0);try{const{data:S}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S!=null&&S.value&&c(S.value)}catch(S){console.error("Error fetching mapbox token:",S)}h(!1)})()},[]),k.useEffect(()=>{if(!o||b.length===0||y)return;(async()=>{var T;v(!0);let S=0;for(const A of b){const I=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(I)try{const R=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(I)}.json?access_token=${o}&limit=1`)).json();if((T=R.features)!=null&&T[0]){const[$,F]=R.features[0].center;await V.from("scorecard_transactions").update({latitude:F,longitude:$}).eq("id",A.id),A.latitude=F,A.longitude=$,S++}}catch(D){console.error("Geocode error:",D)}}x(S),v(!1)})()},[o,s]),k.useEffect(()=>{if(!r.current||!o||n.current)return;Tl.accessToken=o;const N=s.filter(A=>A.latitude!=null&&A.longitude!=null);let S=[-98.5795,39.8283],T=4;if(N.length>0){const A=N.reduce((D,R)=>D+R.longitude,0)/N.length,I=N.reduce((D,R)=>D+R.latitude,0)/N.length;S=[A,I],T=N.length===1?12:10}return n.current=new Tl.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:T,center:S}),n.current.addControl(new Tl.NavigationControl,"top-right"),()=>{var A;(A=n.current)==null||A.remove(),n.current=null}},[o]),k.useEffect(()=>{var S;if(!n.current||!o)return;a.current.forEach(T=>T.remove()),a.current=[],(S=i.current)==null||S.remove();const N=s.filter(T=>T.latitude!=null&&T.longitude!=null);if(N.forEach(T=>{var F;const A=T.transaction_type==="buyer",I=A?"#3B82F6":"#10B981",D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
${A?'':''}
`;const R=new Tl.Popup({offset:25,closeButton:!0}).setHTML(`
${T.property_address}
${T.city?`
${T.city}${T.state?", "+T.state:""} ${T.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(T.sale_price).toLocaleString()}
Closed: ${Fl(T.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(F=T.lead_source)!=null&&F.name?" · "+T.lead_source.name:""}
${T.contact?`
Client: ${T.contact.first_name} ${T.contact.last_name||""}
`:""}
`),$=new Tl.Marker(D).setLngLat([T.longitude,T.latitude]).setPopup(R).addTo(n.current);a.current.push($)}),N.length>1){const T=new Tl.LngLatBounds;N.forEach(A=>T.extend([A.longitude,A.latitude])),n.current.fitBounds(T,{padding:60,maxZoom:13})}else N.length===1&&n.current.flyTo({center:[N[0].longitude,N[0].latitude],zoom:12})},[s,o,y]),d||t?e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Ca,{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:[w.length," of ",s.length," mapped",y&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Oi,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"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 Qht=()=>{const{data:s}=yg();return mt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:r}=await V.from("team_members").select("user_id").eq("team_id",s.teamId);if(r)throw r;const n=t.map(l=>l.user_id),{data:a,error:i}=await V.from("profiles").select("id, name, email, avatar_url").in("id",n);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},OTs=s=>{const{data:t}=yg(),{data:r}=Qht();return mt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const n=r.map(l=>l.id),{data:a,error:i}=await V.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",n).gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r&&r.length>0})};function FTs(s,t){const r=t.filter(i=>i.owner_user_id===s.id),n=r.reduce((i,l)=>i+Number(l.sale_price),0),a=r.reduce((i,l)=>i+(Number(l.commission_amount)||0),0);return{member:s,totalTransactions:r.length,buyerCount:r.filter(i=>i.transaction_type==="buyer").length,sellerCount:r.filter(i=>i.transaction_type==="seller").length,totalVolume:n,averagePrice:r.length>0?n/r.length:0,totalGCI:a}}function BTs(s,t){return s?s.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function zTs({year:s}){var x;const{data:t,isLoading:r}=Qht(),{data:n,isLoading:a}=OTs(s),i=br(),l=r||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:h,teamChartStats:m}=k.useMemo(()=>{if(!t||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const y=t.map(z=>FTs(z,n));y.sort((z,Q)=>Q.totalVolume-z.totalVolume);const v={};t.forEach(z=>{v[z.id]=z.name||z.email});const w=n.length,b=n.reduce((z,Q)=>z+Number(Q.sale_price),0),N=n.reduce((z,Q)=>z+(Number(Q.commission_amount)||0),0),S=n.filter(z=>z.transaction_type==="buyer").length,T=n.filter(z=>z.transaction_type==="seller").length,A={};n.forEach(z=>{var K;const Q=((K=z.lead_source)==null?void 0:K.name)||"Unknown";A[Q]=(A[Q]||0)+1});const I=Object.entries(A).sort((z,Q)=>Q[1]-z[1])[0],D={};n.forEach(z=>{const Q=Fl(z.close_date).toLocaleString("default",{month:"short"});D[Q]=(D[Q]||0)+1});const $=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(z=>({month:z,count:D[z]||0})),F=Object.entries(A).map(([z,Q])=>({name:z,count:Q})).sort((z,Q)=>Q.count-z.count);return{aggregate:{totalTxns:w,buyerCount:S,sellerCount:T,totalVolume:b,avgPrice:w>0?b/w:0,totalGCI:N,topSource:I?{name:I[0],count:I[1]}:null,memberCount:t.length},memberStats:y,topPerformer:y[0]||null,agentNameMap:v,teamChartStats:{transactionsByMonth:$,leadSourceBreakdown:F}}},[t,n]);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(y=>e.jsx(Fs,{className:"h-24"},y))}),e.jsx(Fs,{className:"h-64"})]}):!o||c.length===0?e.jsx(ke,{className:"py-12",children:e.jsxs(Pe,{className:"text-center space-y-2",children:[e.jsx(pr,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pr,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(En,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lc(o.totalVolume,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bo,{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:lc(o.avgPrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lc(o.totalGCI,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:((x=o.topSource)==null?void 0:x.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(ke,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Pe,{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(Gi,{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:lc(d.totalVolume,!0)})]})]})}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Member Performance"})}),e.jsx(Pe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{className:"text-center",children:"Transactions"}),e.jsx(Nt,{className:"text-center",children:"B / S"}),e.jsx(Nt,{className:"text-right",children:"Volume"}),e.jsx(Nt,{className:"text-right",children:"Avg Price"}),e.jsx(Nt,{className:"text-right",children:"GCI"}),e.jsx(Nt,{className:"text-right"})]})}),e.jsx($n,{children:c.map((y,v)=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[v===0&&y.totalTransactions>0&&e.jsx(Gi,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:y.member.avatar_url||void 0}),e.jsx(kn,{className:"text-xs",children:BTs(y.member.name,y.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:y.member.name||y.member.email}),y.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:y.member.email})]})]})}),e.jsx(dt,{className:"text-center font-semibold",children:y.totalTransactions}),e.jsxs(dt,{className:"text-center text-sm",children:[y.buyerCount," / ",y.sellerCount]}),e.jsx(dt,{className:"text-right font-medium",children:lc(y.totalVolume,!0)}),e.jsx(dt,{className:"text-right text-sm",children:lc(y.averagePrice,!0)}),e.jsx(dt,{className:"text-right font-medium",children:lc(y.totalGCI,!0)}),e.jsx(dt,{className:"text-right",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${y.member.id}`),children:e.jsx(bn,{className:"h-4 w-4"})})})]},y.member.id))})]})})})]}),e.jsxs(On,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"transactions",children:[e.jsx(em,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Kt,{value:"charts",children:[e.jsx(ro,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Kt,{value:"map",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ts,{value:"transactions",children:e.jsx(OTe,{transactions:n||[],showCommission:!0,isLoading:a,agentNameMap:h,readOnly:!0})}),e.jsx(ts,{value:"charts",children:m&&e.jsx(FTe,{stats:m,year:s})}),e.jsx(ts,{value:"map",children:e.jsx(BTe,{transactions:n||[],isLoading:a})})]})]})}const Jht=new Date().getFullYear(),MUe=Array.from({length:10},(s,t)=>Jht-t);function $Ts(){var z;const[s,t]=k.useState(Jht),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState("my"),{data:x}=yg(),y=(x==null?void 0:x.role)==="team_leader",{data:v,isLoading:w}=c3e(s),{yearStats:b,lifetimeStats:N,isLoading:S,showCommission:T}=pnt(s),{data:A,isLoading:I}=fnt(s),{data:D}=Hfe(),R=G$t(),$=()=>{if(!v||v.length===0)return;const Q=["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(oe=>{var ne,ie;return[oe.property_address,oe.city||"",oe.state||"",oe.zip||"",oe.transaction_type,oe.close_date,oe.sale_price,...T?[oe.commission_amount||""]:[],((ne=oe.lead_source)==null?void 0:ne.name)||"",((ie=oe.client_type)==null?void 0:ie.name)||"",oe.contact?`${oe.contact.first_name} ${oe.contact.last_name||""}`.trim():"",oe.is_win?"Yes":"No",oe.notes||""]}),X=[Q,...K].map(oe=>oe.map(ne=>`"${String(ne).replace(/"/g,'""')}"`).join(",")).join(` `),Z=new Blob([X],{type:"text/csv"}),re=URL.createObjectURL(Z),le=document.createElement("a");le.href=re,le.download=`transactions-${s}.csv`,le.click(),URL.revokeObjectURL(re)},F=!v||v.length===0;return e.jsxs(ws,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),y&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(G,{variant:h==="my"?"default":"ghost",size:"sm",onClick:()=>m("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(G,{variant:h==="team"?"default":"ghost",size:"sm",onClick:()=>m("team"),className:"h-8",children:[e.jsx(pr,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),h==="team"&&y?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),e.jsxs(Is,{value:String(s),onValueChange:Q=>t(Number(Q)),children:[e.jsx(As,{className:"w-[120px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:MUe.map(Q=>e.jsx(ct,{value:String(Q),children:Q},Q))})]})]}),e.jsx(zTs,{year:s})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Is,{value:String(s),onValueChange:Q=>t(Number(Q)),children:[e.jsx(As,{className:"w-[120px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:MUe.map(Q=>e.jsx(ct,{value:String(Q),children:Q},Q))})]}),e.jsx(G,{variant:"outline",size:"icon",onClick:()=>d(!c),children:e.jsx(oo,{className:"h-4 w-4"})})]})]}),c&&e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Dt,{className:"text-lg",children:"Settings"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(he,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(_r,{checked:(D==null?void 0:D.show_commission)??!0,onCheckedChange:Q=>R.mutate({show_commission:Q})})]})})]}),F&&!w?e.jsx(ke,{className:"py-12",children:e.jsxs(Pe,{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(ro,{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(G,{onClick:()=>n(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(G,{variant:"outline",onClick:()=>i(!0),children:[e.jsx(da,{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(G,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Ya,{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(G,{onClick:()=>n(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(G,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Pd,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(G,{variant:"outline",onClick:()=>i(!0),children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(G,{variant:"outline",onClick:$,disabled:F,children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(G,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Ya,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(En,{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:[N.totalTransactions," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pr,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lc(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[lc(N.totalVolume,!0)," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bo,{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:lc(b.averagePrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:((z=b.topLeadSource)==null?void 0:z.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),T&&e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lc(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[lc(N.totalCommission,!0)," lifetime"]})]})}),T&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(ke,{children:e.jsxs(Pe,{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(wl,{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:lc(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[lc(N.totalNetToAgent,!0)," lifetime"]})]})})]}),A&&e.jsx(Wht,{goals:A,stats:b,year:s,showCommission:T}),e.jsxs(On,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Rn,{children:[e.jsx(Kt,{value:"transactions",children:"Transactions"}),e.jsx(Kt,{value:"charts",children:"Charts"}),e.jsxs(Kt,{value:"map",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ts,{value:"transactions",children:e.jsx(OTe,{transactions:v||[],showCommission:T,isLoading:w})}),e.jsx(ts,{value:"charts",children:e.jsx(FTe,{stats:b,year:s})}),e.jsx(ts,{value:"map",children:e.jsx(BTe,{transactions:v||[],isLoading:w})})]})]})]})]}),e.jsx(Ght,{open:r,onOpenChange:n}),e.jsx(PTs,{open:a,onOpenChange:i}),e.jsx(RTs,{open:l,onOpenChange:o,year:s,existingGoals:A})]})}function emt({open:s,onOpenChange:t,listingId:r,listingSlug:n,listingTitle:a}){const{user:i}=js(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(!1);k.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:b,error:N}=await V.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",r).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(N)throw N;if(b&&b.share_token)o(b);else if(b&&!b.share_token){const{data:S,error:T}=await V.from("listing_shares").update({share_type:"referral_link"}).eq("id",b.id).select("id, share_token, click_count, lead_count").single();if(T)throw T;o(S)}else{const{data:S,error:T}=await V.from("listing_shares").insert({listing_id:r,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(T)throw T;o(S)}}catch(b){console.error("Error creating share link:",b),ue.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,r]);const x=l!=null&&l.share_token?`https://listings.relevelup.com/${n||r}?ref=${l.share_token}`:"",y=async()=>{try{await navigator.clipboard.writeText(x),m(!0),ue.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{ue.error("Failed to copy link")}},v=w=>{const b=encodeURIComponent(x),N=encodeURIComponent(`Check out this listing: ${a}`);switch(w){case"email":window.open(`mailto:?subject=${N}&body=${b}`);break;case"text":window.open(`sms:?body=${N}%20${b}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${b}`,"_blank");break}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Hr,{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(he,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:c?"Generating...":x,readOnly:!0,className:"font-mono text-sm"}),e.jsx(G,{onClick:y,disabled:c||!x,variant:h?"default":"outline",children:h?e.jsx(Kn,{className:"h-4 w-4"}):e.jsx(Ra,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>v("email"),disabled:c,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>v("text"),disabled:c,children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(G,{variant:"outline",className:"flex-1",onClick:()=>v("facebook"),disabled:c,children:[e.jsx(yu,{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(he,{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(bn,{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(pr,{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 UTs={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"},qTs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},VTs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function B$({listing:s,onClick:t,onEdit:r,onDelete:n,showActions:a}){var w,b;const{user:i}=js(),{data:l}=lnt(s.id),o=ont(),[c,d]=k.useState(!1),h=N=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(N),m=((w=s.photos)==null?void 0:w.find(N=>N.is_primary))||((b=s.photos)==null?void 0:b[0]),x=(i==null?void 0:i.id)===s.agent_id,y=async N=>{N.stopPropagation();try{const S=await o.mutateAsync(s.id);ue.success(S.saved?"Listing saved!":"Listing removed from saved")}catch{ue.error("Failed to save listing")}},v=N=>{if(N.stopPropagation(),i)d(!0);else{const S=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(S),ue.success("Link copied to clipboard!")}};return e.jsxs(ke,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[m?e.jsx("img",{src:m.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(og,{className:"h-12 w-12"})}),e.jsx(Ge,{className:`absolute top-2 left-2 ${UTs[s.status]} text-white border-0`,children:qTs[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(Xn,{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(G,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y,children:e.jsx(ci,{className:`h-4 w-4 ${l?"fill-pink-500 text-pink-500":""}`})}),e.jsx(G,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:v,title:x?"Copy link":"Share & earn leads",children:x?e.jsx(Ec,{className:"h-4 w-4"}):e.jsx(jr,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(emt,{open:c,onOpenChange:d,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Pe,{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(Ge,{variant:"outline",className:"text-xs",children:[e.jsx(pr,{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(Ca,{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(Ny,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xf,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(og,{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(Ge,{variant:"secondary",className:"text-xs",children:VTs[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(bn,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ec,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),s.save_count]})]}),a&&(r||n)&&e.jsxs("div",{className:"flex gap-2",children:[r&&e.jsxs(G,{variant:"outline",size:"sm",className:"flex-1",onClick:N=>{N.stopPropagation(),r()},children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Edit"]}),n&&e.jsx(G,{variant:"destructive",size:"sm",onClick:N=>{N.stopPropagation(),n()},children:e.jsx(yr,{className:"h-4 w-4"})})]})]})]})}const HTs=[{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"}],GTs=[{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 WTs({filters:s,onFiltersChange:t,onClose:r}){const n=()=>{t({sortBy:"newest"})};return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Dt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:n,children:"Clear All"}),e.jsx(G,{variant:"ghost",size:"icon",onClick:r,children:e.jsx(vr,{className:"h-4 w-4"})})]})]}),e.jsxs(Pe,{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(he,{children:"Status"}),e.jsxs(Is,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"All statuses"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Statuses"}),HTs.map(a=>e.jsx(ct,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Type"}),e.jsxs(Is,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"All types"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),GTs.map(a=>e.jsx(ct,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Min Price"}),e.jsx(Ne,{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(he,{children:"Max Price"}),e.jsx(Ne,{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(he,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(_r,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function KTs({leaderboard:s}){const t=n=>{switch(n){case 0:return e.jsx(Gi,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(xb,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Yl,{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:n+1})}},r=(n,a)=>!n||n.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:n.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(Ge,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Pe,{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(Ec,{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(En,{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(xb,{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(Gi,{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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Community Leaderboard"})}),e.jsx(Pe,{children:e.jsxs(On,{defaultValue:"sharers",children:[e.jsxs(Rn,{className:"w-full",children:[e.jsxs(Kt,{value:"sharers",className:"flex-1",children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Kt,{value:"listers",className:"flex-1",children:[e.jsx(En,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(ts,{value:"sharers",className:"mt-4",children:r(s==null?void 0:s.topSharers,"shares")}),e.jsx(ts,{value:"listers",className:"mt-4",children:r(s==null?void 0:s.topListers,"listings")})]})})]})]})}const IUe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},LUe={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 YTs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function ZTs({listings:s,isLoading:t}){const r=br(),n=k.useRef(null),a=k.useRef(null),i=k.useRef([]),{isAdmin:l}=js(),[o,c]=k.useState(""),[d,h]=k.useState(!0),[m,x]=k.useState(!1),y=s.filter(w=>w.latitude!=null&&w.longitude!=null),v=s.filter(w=>(w.latitude==null||w.longitude==null)&&(w.property_address||w.city));return k.useEffect(()=>{(async()=>{h(!0);try{const{data:b}=await V.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)}h(!1)})()},[]),k.useEffect(()=>{if(!o||v.length===0||m)return;(async()=>{var b;x(!0);for(const N of v){const S=[N.property_address,N.city,N.state].filter(Boolean).join(", ");if(S)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(S)}.json?access_token=${o}&limit=1`)).json();if((b=A.features)!=null&&b[0]){const[I,D]=A.features[0].center;await V.from("listings").update({latitude:D,longitude:I}).eq("id",N.id),N.latitude=D,N.longitude=I}}catch(T){console.error("Geocode error:",T)}}x(!1)})()},[o,s]),k.useEffect(()=>{if(!n.current||!o||a.current)return;Tl.accessToken=o;const w=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],N=4;if(w.length>0){const S=w.reduce((A,I)=>A+I.longitude,0)/w.length,T=w.reduce((A,I)=>A+I.latitude,0)/w.length;b=[S,T],N=w.length===1?12:10}return a.current=new Tl.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:N,center:b}),a.current.addControl(new Tl.NavigationControl,"top-right"),()=>{var S;(S=a.current)==null||S.remove(),a.current=null}},[o]),k.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(b=>b.remove()),i.current=[];const w=s.filter(b=>b.latitude!=null&&b.longitude!=null);if(w.forEach(b=>{var D,R,$;const N=IUe[b.status]||"#10B981",S=((D=b.photos)==null?void 0:D.find(F=>F.is_primary))||((R=b.photos)==null?void 0:R[0]),T=document.createElement("div");T.className="cursor-pointer",T.innerHTML=`
`;const A=new Tl.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${S!=null&&S.photo_url?``:""}
${YTs(b.price)}
${b.property_address||""}
${b.city}, ${b.state}
${LUe[b.status]||b.status} ${b.bedrooms?`${b.bedrooms} bed`:""} ${b.bathrooms?`${b.bathrooms} bath`:""}
${($=b.agent)!=null&&$.name?`
Listed by ${b.agent.name}
`:""}
Click to view details →
`),I=new Tl.Marker(T).setLngLat([b.longitude,b.latitude]).setPopup(A).addTo(a.current);i.current.push(I)}),w.length>1){const b=new Tl.LngLatBounds;w.forEach(N=>b.extend([N.longitude,N.latitude])),a.current.fitBounds(b,{padding:60,maxZoom:13})}else w.length===1&&a.current.flyTo({center:[w[0].longitude,w[0].latitude],zoom:12})},[s,o,m]),k.useEffect(()=>(window.__navigateToListing__=w=>{r(`/mission-control/listings/${w}`)},()=>{delete window.__navigateToListing__}),[r]),d||t?e.jsx(ke,{children:e.jsx(Pe,{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(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Ca,{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(IUe).map(([w,b])=>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:b}}),e.jsx("span",{className:"text-xs",children:LUe[w]})]},w)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[y.length," of ",s.length," mapped",m&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Oi,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"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."})]})]})})}function XTs(){var F,z,Q,K,X,Z,re,le;const s=br(),{brokerageId:t}=js(),{data:r,isLoading:n}=snt(),[a,i]=k.useState("feed"),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState({sortBy:"newest"}),{data:x,isLoading:y}=rnt({...h,city:c||h.city}),{data:v,isLoading:w}=T$t(),{data:b,isLoading:N}=nnt(),{data:S,isLoading:T}=I$t(),{data:A,isLoading:I}=D$t(),{data:D}=P$t(),R=int(),$=async oe=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await R.mutateAsync(oe),ue.success("Listing deleted successfully")}catch{ue.error("Failed to delete listing")}};return n?e.jsx(ws,{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"})})}):r?e.jsx(ws,{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(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx($s,{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(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(En,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(x==null?void 0:x.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(ci,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(I4,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(pr,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((F=S==null?void 0:S.sent)==null?void 0:F.length)||0)+(((z=S==null?void 0:S.received)==null?void 0:z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(On,{value:a,onValueChange:i,children:[e.jsxs(Rn,{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(ts,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by city or neighborhood...",value:c,onChange:oe=>d(oe.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:h.sortBy,onValueChange:oe=>m({...h,sortBy:oe}),children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"Sort by"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"newest",children:"Newest First"}),e.jsx(ct,{value:"updated",children:"Recently Updated"}),e.jsx(ct,{value:"price_asc",children:"Price: Low to High"}),e.jsx(ct,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(G,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Sy,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(WTs,{filters:h,onFiltersChange:m,onClose:()=>o(!1)}),y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((oe,ne)=>e.jsxs(ke,{children:[e.jsx(Fs,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(Fs,{className:"h-5 w-3/4"}),e.jsx(Fs,{className:"h-4 w-1/2"}),e.jsx(Fs,{className:"h-4 w-1/4"})]})]},ne))}):(x==null?void 0:x.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(En,{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(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx($s,{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:x==null?void 0:x.map(oe=>e.jsx(B$,{listing:oe,onClick:()=>s(`/mission-control/listings/${oe.id}`)},oe.id))})]}),e.jsx(ts,{value:"my-listings",className:"space-y-4",children:N?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,ne)=>e.jsxs(ke,{children:[e.jsx(Fs,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(Fs,{className:"h-5 w-3/4"}),e.jsx(Fs,{className:"h-4 w-1/2"})]})]},ne))}):(b==null?void 0:b.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(I4,{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(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(oe=>e.jsx(B$,{listing:oe,showActions:!0,onClick:()=>s(`/mission-control/listings/${oe.id}`),onEdit:()=>s(`/mission-control/listings/${oe.id}/edit`),onDelete:()=>$(oe.id)},oe.id))})}),e.jsx(ts,{value:"saved",className:"space-y-4",children:w?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,ne)=>e.jsxs(ke,{children:[e.jsx(Fs,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(Fs,{className:"h-5 w-3/4"}),e.jsx(Fs,{className:"h-4 w-1/2"})]})]},ne))}):(v==null?void 0:v.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(ci,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v==null?void 0:v.map(oe=>e.jsx(B$,{listing:oe.listing,onClick:()=>s(`/mission-control/listings/${oe.listing.id}`)},oe.id))})}),e.jsx(ts,{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(Ec,{className:"h-4 w-4"}),"Referrals Sent (",((Q=S==null?void 0:S.sent)==null?void 0:Q.length)||0,")"]}),((K=S==null?void 0:S.sent)==null?void 0:K.length)===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(X=S==null?void 0:S.sent)==null?void 0:X.map(oe=>{var ne,ie;return e.jsx(ke,{children:e.jsx(Pe,{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:oe.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ne=oe.listing)==null?void 0:ne.property_address)||((ie=oe.listing)==null?void 0:ie.city)})]}),e.jsx(Ge,{variant:oe.status==="closed"?"default":"secondary",children:oe.status.replace("_"," ")})]})})},oe.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(pr,{className:"h-4 w-4"}),"Referrals Received (",((Z=S==null?void 0:S.received)==null?void 0:Z.length)||0,")"]}),((re=S==null?void 0:S.received)==null?void 0:re.length)===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(le=S==null?void 0:S.received)==null?void 0:le.map(oe=>{var ne;return e.jsx(ke,{children:e.jsxs(Pe,{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:oe.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ne=oe.sender)==null?void 0:ne.name]})]}),e.jsx(Ge,{variant:oe.status==="closed"?"default":"secondary",children:oe.status.replace("_"," ")})]}),e.jsx(G,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${oe.listing_id}`),children:"View Listing"})]})},oe.id)})})]})]})}),t&&e.jsx(ts,{value:"brokerage",className:"space-y-4",children:I?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,ne)=>e.jsxs(ke,{children:[e.jsx(Fs,{className:"h-48 w-full"}),e.jsxs(Pe,{className:"p-4 space-y-2",children:[e.jsx(Fs,{className:"h-5 w-3/4"}),e.jsx(Fs,{className:"h-4 w-1/2"})]})]},ne))}):(A==null?void 0:A.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(I4,{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(G,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx($s,{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(oe=>e.jsx(B$,{listing:oe,onClick:()=>s(`/mission-control/listings/${oe.id}`)},oe.id))})}),e.jsx(ts,{value:"map",children:e.jsx(ZTs,{listings:x||[],isLoading:y})}),e.jsx(ts,{value:"leaderboard",children:e.jsx(KTs,{leaderboard:D})})]})]})}):e.jsx(ws,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(En,{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 tmt(s){return mt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:r}=await V.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function QTs(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async({listingId:r,file:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=n.name.split(".").pop(),i=`${s.id}/${r}/${crypto.randomUUID()}.${a}`,{error:l}=await V.storage.from("listing-documents").upload(i,n,{contentType:n.type||void 0});if(l)throw l;const{data:o,error:c}=await V.from("listing_documents").insert({listing_id:r,owner_user_id:s.id,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["listing-documents",n.listingId]})}})}function JTs(){const s=Xt();return Ct({mutationFn:async({id:t,storage_path:r,listingId:n})=>{await V.storage.from("listing-documents").remove([r]);const{error:a}=await V.from("listing_documents").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function eEs(){const s=Xt();return Ct({mutationFn:async({id:t,visible:r,listingId:n})=>{const{error:a}=await V.from("listing_documents").update({visible_on_exchange:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function smt(s){const{data:t,error:r}=await V.storage.from("listing-documents").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const tEs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function sEs({listingId:s,ownerOnly:t=!1}){const{data:r=[]}=tmt(s),n=t?r:r.filter(i=>i.visible_on_exchange);if(n.length===0)return null;const a=async i=>{try{const l=await smt(i);window.open(l,"_blank")}catch{ue.error("Failed to open document")}};return e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Documents & Disclosures (",n.length,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2",children:n.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(ln,{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:tEs(i.file_size)})]}),e.jsx(Ya,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function rEs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const nEs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function aEs({open:s,onOpenChange:t,listing:r}){const{user:n}=js(),{data:a=[],isLoading:i}=Sm(),{data:l=[]}=fx(),[o,c]=k.useState(""),[d,h]=k.useState("all"),[m,x]=k.useState(new Set),[y,v]=k.useState(!1),[w,b]=k.useState(null);k.useEffect(()=>{s||(c(""),h("all"),x(new Set),v(!1))},[s]),k.useEffect(()=>{!s||!n||(async()=>{const{data:$}=await V.from("gmail_integrations").select("gmail_email").eq("user_id",n.id).maybeSingle();b(($==null?void 0:$.gmail_email)||null)})()},[s,n]);const N=k.useMemo(()=>a.filter($=>$.email),[a]),S=k.useMemo(()=>{let $=N;if(d!=="all"&&($=$.filter(F=>{var z;return(z=F.tags)==null?void 0:z.some(Q=>Q.relationship_type_id===d)})),o.trim()){const F=o.toLowerCase();$=$.filter(z=>`${z.first_name||""} ${z.last_name||""}`.toLowerCase().includes(F)||(z.email||"").toLowerCase().includes(F))}return $},[N,o,d]),T=()=>{m.size===S.length?x(new Set):x(new Set(S.map($=>$.id)))},A=$=>{const F=new Set(m);F.has($)?F.delete($):F.add($),x(F)},I=k.useMemo(()=>N.filter($=>m.has($.id)).map($=>({id:$.id,first_name:$.first_name||"there",last_name:$.last_name,email:$.email})),[N,m]),{defaultSubject:D,defaultBody:R}=k.useMemo(()=>{var ce,ve,be,Ue;const $=r.property_address||`${r.city}, ${r.state}`,F=rEs(r.price),z=nEs[r.property_type]||"home",Q=r.bedrooms?`${r.bedrooms} bed`:"",K=r.bathrooms?`${r.bathrooms} bath`:"",X=r.square_footage?`${r.square_footage.toLocaleString()} sqft`:"",Z=[Q,K,X].filter(Boolean).join(" • "),re=`https://listings.relevelup.com/${r.slug||r.id}`,le=((ve=(ce=r.photos)==null?void 0:ce.find(Be=>Be.is_primary))==null?void 0:ve.photo_url)||((Ue=(be=r.photos)==null?void 0:be[0])==null?void 0:Ue.photo_url)||"",ne={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[r.status]||"New Listing",ie=`${ne}: ${$} — ${F}`,ye=`

Hi {{first_name}},

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

${le?` ${$} `:""}
${ne}

${F}

${$}

${r.city}, ${r.state}

${Z?`

${Z} • ${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:ie,defaultBody:ye}},[r]);return y?e.jsx($v,{open:y,onOpenChange:$=>{v($),$||t(!1)},bulkContacts:I,defaultSubject:D,defaultBody:R,gmailEmail:w}):e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Hr,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search contacts...",value:o,onChange:$=>c($.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:d,onValueChange:h,children:[e.jsx(As,{className:"sm:w-[180px]",children:e.jsx(Ls,{placeholder:"Filter by tag"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All contacts"}),l.map($=>e.jsx(ct,{value:$.id,children:$.name},$.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:T,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Si,{checked:S.length>0&&m.size===S.length,className:"pointer-events-none"}),e.jsx("span",{children:m.size===S.length&&S.length>0?"Deselect all":`Select all (${S.length})`})]}),e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),m.size," selected"]})]}),e.jsx(Qa,{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(es,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):S.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:N.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:S.map($=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(Si,{checked:m.has($.id),onCheckedChange:()=>A($.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[$.first_name," ",$.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:$.email})]}),$.tags&&$.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:$.tags.slice(0,2).map(F=>{var z;return e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(z=F.relationship_type)==null?void 0:z.name},F.id)})})]},$.id))})}),e.jsx(fo,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:w?`Sending from ${w}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>v(!0),disabled:m.size===0,className:"gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"}),"Compose Email (",m.size,")"]})]})]})]})})}function Jx(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 n=t;return s.brokerage_split_pct&&(n-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(n-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(n-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(n-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(n-=s.transaction_fee),Math.max(0,n)}function _xe(){const s=sa();return mt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function rmt(){const s=sa(),t=Xt();return Ct({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:r}=await V.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function wxe(){const s=sa();return mt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})}function nmt(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("deal_pipeline").insert({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||null,contact_id:r.contact_id||null,listing_id:r.listing_id||null,property_address:r.property_address||null,city:r.city||null,state:r.state||null,zip_code:r.zip_code||null,expected_price:r.expected_price||null,expected_commission:r.expected_commission||null,commission_percentage:r.commission_percentage||3,target_close_date:r.target_close_date||null,contract_date:r.contract_date||null,listing_date:r.listing_date||null,priority:r.priority||"medium",probability:r.probability||50,notes:r.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await V.from("deal_activities").insert([{deal_id:n.id,activity_type:"system",title:"Deal created",description:`Deal "${r.deal_name}" was created`}]),n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function amt(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("deal_pipeline").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function iEs(){const s=Xt();return Ct({mutationFn:async({dealId:t,stageId:r,stageName:n})=>{const{data:a,error:i}=await V.from("deal_pipeline").update({stage_id:r}).eq("id",t).select().single();if(i)throw i;return await V.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${n}`,metadata:{new_stage_id:r,new_stage_name:n}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function oEs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("deal_pipeline").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function lEs(s){return mt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function cEs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-activities",r.deal_id]})}})}function dEs(s){return mt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function uEs(){const s=Xt();return Ct({mutationFn:async({id:t,is_completed:r,deal_id:n})=>{const{data:a,error:i}=await V.from("deal_checklist_items").update({is_completed:r,completed_at:r?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function hEs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.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(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function mEs(){const s=sa();return mt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(r)throw r;const n=(t==null?void 0:t.filter(o=>{var c,d,h;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((h=o.deal_pipeline_stages)==null?void 0:h.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:n.length,wonDeals:a.length,pipelineValue:n.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:n.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:n.reduce((o,c)=>o+(Jx(c)||0),0),wonValue:a.reduce((o,c)=>o+(c.expected_price||0),0),weightedGCI:n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c.expected_commission||0)*d},0),weightedNet:n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Jx(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Jx(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Jx(c)||0),0)+n.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Jx(c)||0)*d},0)}},enabled:!!s})}function fEs(s){const t=sa();return mt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:r,error:n}=await V.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(n)throw n;return r},enabled:!!t&&!!s})}function pEs(){const s=Xt();return Ct({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await V.from("deal_pipeline").update({listing_id:r}).eq("id",t).select().single();if(a)throw a;return await V.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:r}}),n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",r.listingId]})}})}function xEs(){const s=Xt();return Ct({mutationFn:async({dealId:t,listingId:r})=>{const{data:n,error:a}=await V.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:n,listingId:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function gEs({listing:s}){const t=br(),[r,n]=k.useState(""),[a,i]=k.useState(!1),{data:l,isLoading:o}=fEs(s.id),{data:c,isLoading:d}=_xe(),{data:h,isLoading:m}=wxe(),x=rmt(),y=pEs(),v=xEs(),w=nmt(),b=(h==null?void 0:h.filter(I=>!I.listing_id))||[],N=I=>{if(!(c!=null&&c.length))return null;switch(I){case"coming_soon":case"active":case"price_improvement":return c.find(D=>D.name==="Active");case"under_contract":return c.find(D=>D.name==="Under Contract");case"sold":return c.find(D=>D.is_won_stage);default:return c.find(D=>D.name==="Active")}},S=async()=>{i(!0);try{c!=null&&c.length||await x.mutateAsync();const I=N(s.status);await w.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(I==null?void 0:I.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}),ue.success("Deal created and linked to listing!")}catch(I){console.error("Failed to create deal:",I),ue.error("Failed to create deal")}finally{i(!1)}},T=async()=>{if(!r){ue.error("Please select a deal");return}try{await y.mutateAsync({dealId:r,listingId:s.id}),ue.success("Listing linked to deal!"),n("")}catch{ue.error("Failed to link listing")}},A=async()=>{if(l)try{await v.mutateAsync({dealId:l.id,listingId:s.id}),ue.success("Listing unlinked from deal")}catch{ue.error("Failed to unlink listing")}};return o||d?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(nv,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(ke,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(tl,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Pe,{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(Ge,{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(G,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(Ha,{className:"h-3 w-3 ml-1"})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:A,disabled:v.isPending,children:v.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(n3,{className:"h-4 w-4"})})]})]})]}):e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsxs(Dt,{className:"flex items-center gap-2 text-base",children:[e.jsx(nv,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Pe,{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(G,{onClick:S,disabled:a||w.isPending,className:"w-full",size:"sm",children:[a||w.isPending?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Is,{value:r,onValueChange:n,children:[e.jsx(As,{className:"flex-1 text-sm",children:e.jsx(Ls,{placeholder:"Link to existing deal..."})}),e.jsx(Ms,{children:b.map(I=>e.jsx(ct,{value:I.id,children:I.deal_name},I.id))})]}),e.jsx(G,{variant:"secondary",size:"icon",onClick:T,disabled:!r||y.isPending,children:y.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(tl,{className:"h-4 w-4"})})]})]})]})]})}const yEs={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"},vEs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},PUe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function bEs(){var re,le,oe,ne,ie,ye,ce,ve,be;const{listingId:s}=Ki(),t=br(),{user:r}=js(),{data:n,isLoading:a}=ant(s||""),{data:i}=lnt(s||""),{data:l}=A$t(s||""),o=ont(),c=E$t(),d=M$t(),h=int(),m=L$t(),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(!1),[A,I]=k.useState(null),[D,R]=k.useState({buyerName:"",buyerType:"",notes:""}),$=(r==null?void 0:r.id)===(n==null?void 0:n.agent_id),F=Ue=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ue),z=async Ue=>{const Be=`https://listings.relevelup.com/${(n==null?void 0:n.slug)||(n==null?void 0:n.id)}`,De=`Check out this listing: ${(n==null?void 0:n.property_address)||(n==null?void 0:n.city)}`;d.mutate({listingId:n.id,shareType:Ue});try{switch(Ue){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Be)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Be),ue.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${De} ${Be}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(De)}&body=${encodeURIComponent(`Check out this listing: ${Be}`)}`);break}}catch(Ae){console.error("Share error:",Ae),ue.error("Failed to share")}},Q=async()=>{try{await h.mutateAsync(n.id),ue.success("Listing deleted"),t("/mission-control/listings")}catch{ue.error("Failed to delete listing")}},K=async()=>{if(!D.buyerName.trim()){ue.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:n.id,listingAgentId:n.agent_id,buyerName:D.buyerName,buyerType:D.buyerType||void 0,notes:D.notes||void 0}),ue.success("Referral sent successfully!"),w(!1),R({buyerName:"",buyerType:"",notes:""})}catch{ue.error("Failed to send referral")}},X=Ue=>{var Te,xe;const Be=(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`,De=F((n==null?void 0:n.price)||0),Ae=n!=null&&n.bedrooms?`${n.bedrooms}BD`:"",He=n!=null&&n.bathrooms?`${n.bathrooms}BA`:"",Le=n!=null&&n.square_footage?`${n.square_footage.toLocaleString()}SF`:"",Ie=[Ae,He,Le].filter(Boolean).join(" | ");switch(Ue){case"just_listed":return`🏡 JUST LISTED! ${Be} ${De} ${Ie} ${(n==null?void 0:n.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Te=n==null?void 0:n.city)==null?void 0:Te.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Be} Now ${De}! ${Ie} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${PUe[(n==null?void 0:n.property_type)||"single_family"].toLowerCase()} in ${n==null?void 0:n.city}? 👀 I've got just the one for you! ${Ie} DM me for details! 📩 #ComingSoon #RealEstate #${(xe=n==null?void 0:n.city)==null?void 0:xe.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(ws,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{className:"h-10 w-32"}),e.jsx(Fs,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(Fs,{className:"h-48"}),e.jsx(Fs,{className:"h-48"}),e.jsx(Fs,{className:"h-48"})]})]})});if(!n)return e.jsx(ws,{title:"Listing Not Found",description:"",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(G,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const Z=((re=n.photos)==null?void 0:re.find(Ue=>Ue.is_primary))||((le=n.photos)==null?void 0:le[0]);return e.jsxs(ws,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(G,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>Z&&I(Z.photo_url),children:Z?e.jsx("img",{src:Z.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:(oe=n.photos)==null?void 0:oe.slice(1,5).map((Ue,Be)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>I(Ue.photo_url),children:e.jsx("img",{src:Ue.photo_url,alt:`Photo ${Be+2}`,className:"w-full h-full object-cover"})},Ue.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(ke,{children:e.jsxs(Pe,{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(Ge,{className:`${yEs[n.status]} text-white border-0`,children:vEs[n.status]}),n.is_featured&&e.jsxs(Ge,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),n.open_to_referrals&&e.jsxs(Ge,{variant:"outline",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:F(n.price)}),n.property_address&&e.jsx("p",{className:"text-xl font-medium",children:n.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(Ca,{className:"h-4 w-4"}),n.city,", ",n.state,n.neighborhood&&` • ${n.neighborhood}`]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>o.mutate(n.id),children:e.jsx(ci,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(G,{variant:"outline",size:"icon",onClick:()=>c.mutate(n.id),children:l?e.jsx(ev,{className:"h-4 w-4"}):e.jsx(_m,{className:"h-4 w-4"})}),!$&&e.jsxs(G,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>N(!0),children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"outline",children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(xd,{children:[e.jsxs(Pa,{onClick:()=>z("copy"),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Pa,{onClick:()=>z("facebook"),children:[e.jsx(yu,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Pa,{onClick:()=>z("text"),children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Pa,{onClick:()=>z("email"),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),$&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",onClick:()=>T(!0),className:"gap-2",children:[e.jsx(Vs,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(G,{variant:"outline",onClick:()=>t(`/mission-control/listings/${n.id}/edit`),children:[e.jsx(sd,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(G,{variant:"destructive",size:"icon",onClick:()=>y(!0),children:e.jsx(yr,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[n.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Ny,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),n.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Xf,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),n.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(og,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),n.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(on,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:n.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(Ge,{variant:"secondary",children:[e.jsx(Sa,{className:"h-3 w-3 mr-1"}),PUe[n.property_type]]}),n.lot_size&&e.jsxs(Ge,{variant:"secondary",children:["Lot: ",n.lot_size]}),n.has_hoa&&e.jsx(Ge,{variant:"secondary",children:"HOA"})]}),n.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:n.description})]}),n.agent_notes&&n.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:n.agent_notes})]}),n.mls_link&&e.jsx(G,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:n.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{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(bn,{className:"h-4 w-4"}),n.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ec,{className:"h-4 w-4"}),n.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-4 w-4"}),n.save_count," saves"]})]})]})}),n.allow_sharing&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Share Content"})}),e.jsx(Pe,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ue=>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:[Ue.replace("_"," ")," Caption"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(X(Ue)),ue.success("Caption copied!")},children:e.jsx(Ra,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:X(Ue)})]},Ue))})]}),e.jsx(sEs,{listingId:n.id,ownerOnly:$})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Pe,{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:((ie=(ne=n.agent)==null?void 0:ne.name)==null?void 0:ie.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ye=n.agent)==null?void 0:ye.name)||"Unknown"}),((ve=(ce=n.agent)==null?void 0:ce.brokerage)==null?void 0:ve.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n.agent.brokerage.name})]})]}),!$&&e.jsx("div",{className:"space-y-2",children:((be=n.agent)==null?void 0:be.email)&&e.jsx(G,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${n.agent.email}`,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),$&&e.jsx(gEs,{listing:n}),!$&&n.open_to_referrals&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Pe,{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(G,{className:"w-full",onClick:()=>w(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(fs,{open:!!A,onOpenChange:()=>I(null),children:e.jsx(ms,{className:"max-w-4xl",children:e.jsx("img",{src:A||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(fs,{open:x,onOpenChange:y,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Delete Listing"}),e.jsx(Hr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:Q,disabled:h.isPending,children:h.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(fs,{open:v,onOpenChange:w,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Send Buyer Referral"}),e.jsx(Hr,{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(he,{children:"Buyer Name *"}),e.jsx(Ne,{value:D.buyerName,onChange:Ue=>R({...D,buyerName:Ue.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Buyer Type"}),e.jsxs(Is,{value:D.buyerType,onValueChange:Ue=>R({...D,buyerType:Ue}),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select type"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"first_time",children:"First-Time Buyer"}),e.jsx(ct,{value:"investor",children:"Investor"}),e.jsx(ct,{value:"relocating",children:"Relocating"}),e.jsx(ct,{value:"upgrade",children:"Upgrading"}),e.jsx(ct,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Notes"}),e.jsx(or,{value:D.notes,onChange:Ue=>R({...D,notes:Ue.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>w(!1),children:"Cancel"}),e.jsx(G,{onClick:K,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(emt,{open:b,onOpenChange:N,listingId:(n==null?void 0:n.id)||"",listingSlug:(n==null?void 0:n.slug)||null,listingTitle:(n==null?void 0:n.property_address)||`${n==null?void 0:n.city}, ${n==null?void 0:n.state}`}),n&&e.jsx(aEs,{open:S,onOpenChange:T,listing:n})]})}function _Es({onImport:s}){const[t,r]=k.useState(""),[n,a]=k.useState([]),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(null),m=k.useRef(),x=k.useRef(null);k.useEffect(()=>{const S=T=>{x.current&&!x.current.contains(T.target)&&c(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const y=async S=>{if(S.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:T,error:A}=await V.functions.invoke("mls-listing-search",{body:{query:S}});if(A)throw A;a((T==null?void 0:T.listings)||[]),c(!0)}catch(T){console.error("MLS search error:",T),a([])}finally{l(!1)}},v=S=>{r(S),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>y(S),400)},w=S=>{h(S.mlsNumber),s(S),c(!1),r(`${S.address}, ${S.city}`),ue.success(`Imported: ${S.address}`,{description:"Property details and photos have been auto-filled."}),h(null)},b=S=>S?`$${S.toLocaleString()}`:"",N=S=>{const T=(S||"").toLowerCase();return T.includes("single")||T.includes("detached")?"Single Family":T.includes("condo")?"Condo":T.includes("town")?"Townhouse":T.includes("land")||T.includes("lot")?"Land":T.includes("multi")?"Multi-Family":T.includes("commercial")?"Commercial":S||"Other"};return e.jsxs(ke,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ya,{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(Pe,{children:e.jsxs("div",{ref:x,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:t,onChange:S=>v(S.target.value),onFocus:()=>n.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(es,{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:()=>{r(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(vr,{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:n.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):n.map(S=>e.jsxs("button",{type:"button",onClick:()=>w(S),disabled:d===S.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:[S.photos[0]?e.jsx("img",{src:S.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(Ca,{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:S.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[S.city,", ",S.state," ",S.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:b(S.price)}),S.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Ny,{className:"h-3 w-3"})," ",S.bedrooms]}),S.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Xf,{className:"h-3 w-3"})," ",S.bathrooms]}),S.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(J4,{className:"h-3 w-3"})," ",S.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:N(S.propertyType)}),S.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[S.photos.length," photos"]})]})]},S.mlsNumber))})]})})]})}function wEs({photo:s,onRemove:t,onSetPrimary:r}){const{attributes:n,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=jpe({id:s.id}),d={transform:Oj.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:It("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",...n,...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(vu,{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(vr,{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(Xn,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>r(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function jEs({photos:s,uploading:t,onUpload:r,onRemove:n,onReorder:a,onSetPrimary:i}){const l=fpe($M(tL,{activationConstraint:{distance:5}})),o=[...s].sort((d,h)=>(d.sort_order??0)-(h.sort_order??0)),c=d=>{const{active:h,over:m}=d;if(!m||h.id===m.id)return;const x=o.findIndex(N=>N.id===h.id),y=o.findIndex(N=>N.id===m.id),v=[...o],[w]=v.splice(x,1);v.splice(y,0,w);const b=v.map((N,S)=>({...N,sort_order:S}));a(b)};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(bpe,{sensors:l,collisionDetection:ppe,onDragEnd:c,children:e.jsx(wpe,{items:o.map(d=>d.id),strategy:kB,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(wEs,{photo:d,onRemove:n,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(es,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(da,{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=>r(d.target.files),disabled:t})]})]})})})]})}function NEs({selectedVideoId:s,onVideoSelect:t,listingId:r}){const n=br(),{user:a}=js(),[i,l]=k.useState(!1),[o,c]=k.useState([]),[d,h]=k.useState(!1),[m,x]=k.useState(null),[y,v]=k.useState({});k.useEffect(()=>{s&&a?w():x(null)},[s,a]);const w=async()=>{if(!s)return;const{data:F,error:z}=await V.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&&(x(F),b(F))},b=async F=>{try{const{data:z,error:Q}=await V.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:F.bunny_video_id,isAgentVideo:!0}});!Q&&(z!=null&&z.thumbnailUrl)&&v(K=>({...K,[F.id]:{thumbnailUrl:z.thumbnailUrl}}))}catch(z){console.warn("Failed to get signed URL",z)}},N=async()=>{if(a){h(!0);try{const{data:F,error:z}=await V.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&&S(F)}catch(F){console.error("Error fetching videos:",F),ue.error("Failed to load videos")}finally{h(!1)}}},S=async F=>{var z;try{const Q=F.map(le=>le.bunny_video_id),{data:K,error:X}=await V.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Q,isAgentVideo:!0}});if(X)throw X;const Z=(K==null?void 0:K.assets)||{},re={};for(const le of F)(z=Z[le.bunny_video_id])!=null&&z.thumbnailUrl&&(re[le.id]={thumbnailUrl:Z[le.bunny_video_id].thumbnailUrl});v(le=>({...le,...re}))}catch(Q){console.warn("Failed to bulk-fetch signed URLs",Q)}},T=()=>{l(!0),N()},A=F=>{t(F.id),x(F),l(!1),ue.success("Video selected")},I=()=>{t(null),x(null)},D=()=>{const F=r?`/mission-control/listings/${r}/edit`:"/mission-control/listings/new";n(`/mission-control/video?returnUrl=${encodeURIComponent(F)}`)},R=F=>{if(!F)return"0:00";const z=Math.floor(F/60),Q=F%60;return`${z}:${Q.toString().padStart(2,"0")}`},$=F=>{var z;return((z=y[F.id])==null?void 0:z.thumbnailUrl)||F.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[m?e.jsx(ke,{className:"overflow-hidden",children:e.jsx(Pe,{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)?e.jsx("img",{src:$(m),alt:m.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(Jr,{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(Uo,{className:"h-6 w-6 text-white fill-white"})}),m.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:R(m.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:m.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(G,{type:"button",variant:"outline",size:"sm",onClick:T,children:"Change"}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:I,className:"text-destructive hover:text-destructive",children:e.jsx(vr,{className:"h-4 w-4"})})]})]})})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Pe,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Jr,{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(G,{type:"button",variant:"outline",onClick:T,className:"gap-2",children:[e.jsx(q4,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(G,{type:"button",variant:"outline",onClick:D,className:"gap-2",children:[e.jsx(Qf,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(q4,{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(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Jr,{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(G,{onClick:D,className:"gap-2",children:[e.jsx(Qf,{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:[$(F)?e.jsx("img",{src:$(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(Jr,{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(Uo,{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:R(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(G,{type:"button",variant:"ghost",onClick:D,className:"gap-2",children:[e.jsx(Qf,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const kEs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function SEs({listingId:s}){const t=k.useRef(null),{data:r=[],isLoading:n}=tmt(s),a=QTs(),i=JTs(),l=eEs(),o=async d=>{if(!(!d||d.length===0)){for(const h of Array.from(d)){if(h.size>25*1024*1024){ue.error(`${h.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:h})}catch(m){ue.error(`Failed to upload ${h.name}: ${m.message}`)}}t.current&&(t.current.value=""),ue.success("Documents uploaded")}},c=async d=>{try{const h=await smt(d);window.open(h,"_blank")}catch{ue.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(G,{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(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):r.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:r.map(d=>e.jsxs(ke,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ln,{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:kEs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(bn,{className:"h-3 w-3"}):e.jsx(Xh,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(_r,{checked:d.visible_on_exchange,onCheckedChange:h=>l.mutate({id:d.id,visible:h,listingId:s}),className:"ml-1"})]}),e.jsx(G,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(G,{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(vr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const CEs=[{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"}],TEs=[{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 EEs({id:s,url:t,index:r,onRemove:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=jpe({id:s}),h={transform:Oj.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:h,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(vu,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>n(r),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(vr,{className:"h-3 w-3"})}),r===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(Xn,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function AEs({photoUrls:s,pendingPhotos:t,onRemove:r,onReorder:n,uploading:a,onUpload:i}){const l=fpe($M(tL,{activationConstraint:{distance:5}})),o=s.map((d,h)=>`pending-${h}`),c=d=>{const{active:h,over:m}=d;if(!m||h.id===m.id)return;const x=o.indexOf(h.id),y=o.indexOf(m.id),v=[...s],w=[...t],[b]=v.splice(x,1),[N]=w.splice(x,1);v.splice(y,0,b),w.splice(y,0,N),n(v,w)};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(bpe,{sensors:l,collisionDetection:ppe,onDragEnd:c,children:e.jsx(wpe,{items:o,strategy:kB,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,h)=>e.jsx(EEs,{id:o[h],url:d,index:h,onRemove:r},o[h])),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(es,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(da,{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 DUe(){const{listingId:s}=Ki(),[t]=Ac(),r=t.get("brokerage"),n=br(),{user:a}=js(),{hasLeadSite:i}=_g(),l=!!s&&s!=="new",o=!!r&&!l,[c,d]=k.useState([]),{data:h,isLoading:m}=ant(l?s:""),x=_$t(),y=w$t(),v=j$t(),w=N$t(),b=k$t(),N=S$t(),S=C$t(),{data:T=[]}=mt({queryKey:["brokerage-agents",r],queryFn:async()=>{if(!r)return[];const{data:ce,error:ve}=await V.from("profiles").select("id, name, email").eq("brokerage_id",r).order("name");if(ve)throw ve;return ce||[]},enabled:o}),[A,I]=k.useState(""),[D,R]=k.useState(!1),[$,F]=k.useState([]),[z,Q]=k.useState([]),[K,X]=k.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});k.useEffect(()=>{var ce,ve,be,Ue,Be;h&&l&&X({property_address:h.property_address||"",city:h.city||"",state:h.state||"",neighborhood:h.neighborhood||"",price:((ce=h.price)==null?void 0:ce.toString())||"",property_type:h.property_type,status:h.status,bedrooms:((ve=h.bedrooms)==null?void 0:ve.toString())||"",bathrooms:((be=h.bathrooms)==null?void 0:be.toString())||"",square_footage:((Ue=h.square_footage)==null?void 0:Ue.toString())||"",lot_size:h.lot_size||"",year_built:((Be=h.year_built)==null?void 0:Be.toString())||"",has_hoa:h.has_hoa,description:h.description||"",agent_notes:h.agent_notes||"",agent_notes_public:h.agent_notes_public,mls_link:h.mls_link||"",video_link:h.video_link||"",video_id:h.video_id||null,allow_sharing:h.allow_sharing,open_to_referrals:h.open_to_referrals,open_to_social_promotion:h.open_to_social_promotion,share_with_brokerage:h.share_with_brokerage??!1,is_public:h.is_public})},[h,l]);const Z=ce=>{var Be,De;const ve={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},be=(ce.propertyType||"").toLowerCase(),Ue=((Be=Object.entries(ve).find(([Ae])=>be.includes(Ae)))==null?void 0:Be[1])||"other";X(Ae=>({...Ae,property_address:ce.address||Ae.property_address,city:ce.city||Ae.city,state:ce.state||Ae.state,price:ce.price?String(ce.price):Ae.price,property_type:Ue,bedrooms:ce.bedrooms?String(ce.bedrooms):Ae.bedrooms,bathrooms:ce.bathrooms?String(ce.bathrooms):Ae.bathrooms,square_footage:ce.sqft?String(ce.sqft):Ae.square_footage,lot_size:ce.lotSize?String(ce.lotSize):Ae.lot_size,year_built:ce.yearBuilt?String(ce.yearBuilt):Ae.year_built,description:ce.description||Ae.description})),((De=ce.photos)==null?void 0:De.length)>0&&(d(ce.photos),z.forEach(Ae=>URL.revokeObjectURL(Ae)),F([]),Q([]))},re=ce=>{if(!ce)return;const ve=Array.from(ce);F(Ue=>[...Ue,...ve]);const be=ve.map(Ue=>URL.createObjectURL(Ue));Q(Ue=>[...Ue,...be])},le=ce=>{URL.revokeObjectURL(z[ce]),F(ve=>ve.filter((be,Ue)=>Ue!==ce)),Q(ve=>ve.filter((be,Ue)=>Ue!==ce))},oe=async ce=>{var ve;if(!(!ce||!h)){R(!0);try{for(const be of Array.from(ce)){const Ue=be.name.split(".").pop(),Be=`${a==null?void 0:a.id}/${h.id}/${Date.now()}.${Ue}`,{error:De}=await V.storage.from("listing-photos").upload(Be,be);if(De)throw De;const{data:{publicUrl:Ae}}=V.storage.from("listing-photos").getPublicUrl(Be);await w.mutateAsync({listingId:h.id,photoUrl:Ae,isPrimary:!((ve=h.photos)!=null&&ve.length)})}ue.success("Photos uploaded!")}catch(be){console.error("Upload error:",be),ue.error("Failed to upload photos")}finally{R(!1)}}},ne=async ce=>{for(let ve=0;ve<$.length;ve++){const be=$[ve],Ue=be.name.split(".").pop(),Be=`${a==null?void 0:a.id}/${ce}/${Date.now()}-${ve}.${Ue}`,{error:De}=await V.storage.from("listing-photos").upload(Be,be);if(De)throw De;const{data:{publicUrl:Ae}}=V.storage.from("listing-photos").getPublicUrl(Be);await w.mutateAsync({listingId:ce,photoUrl:Ae,isPrimary:ve===0})}},ie=async ce=>{if(h)try{await b.mutateAsync({photoId:ce,listingId:h.id}),ue.success("Photo removed")}catch{ue.error("Failed to remove photo")}},ye=async ce=>{if(ce.preventDefault(),!K.city.trim()||!K.state.trim()||!K.price){ue.error("Please fill in required fields (City, State, Price)");return}if(o&&!A){ue.error("Please select an agent to assign this listing to");return}try{const ve={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,...ve}),ue.success("Listing updated!"),n(`/mission-control/listings/${s}`);else{R(!0);let be;if(o&&A?be=await y.mutateAsync({agentId:A,...ve}):be=await x.mutateAsync(ve),$.length>0)try{await ne(be.id),z.forEach(Ue=>URL.revokeObjectURL(Ue)),F([]),Q([])}catch(Ue){console.error("Photo upload error:",Ue),ue.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Ue=0;Uen(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),o?"Back to Brokerage":"Back to Listings"]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[o&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Assign to Agent *"})}),e.jsxs(Pe,{children:[e.jsxs(Is,{value:A,onValueChange:I,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select an agent..."})}),e.jsx(Ms,{children:T.map(ce=>e.jsx(ct,{value:ce.id,children:ce.name||ce.email},ce.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(_Es,{onImport:Z}),c.length>0&&e.jsxs(ke,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Mt,{className:"pb-3",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ya,{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(Pe,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((ce,ve)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:ce,alt:"",className:"w-full h-full object-cover"})},ve)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(vr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Property Details"})}),e.jsx(Pe,{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(he,{children:"Property Address"}),e.jsx(Ne,{value:K.property_address,onChange:ce=>X({...K,property_address:ce.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"City *"}),e.jsx(Ne,{value:K.city,onChange:ce=>X({...K,city:ce.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"State *"}),e.jsx(Ne,{value:K.state,onChange:ce=>X({...K,state:ce.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Neighborhood"}),e.jsx(Ne,{value:K.neighborhood,onChange:ce=>X({...K,neighborhood:ce.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Price *"}),e.jsx(Ne,{type:"number",value:K.price,onChange:ce=>X({...K,price:ce.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Type"}),e.jsxs(Is,{value:K.property_type,onValueChange:ce=>X({...K,property_type:ce}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:TEs.map(ce=>e.jsx(ct,{value:ce.value,children:ce.label},ce.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Status"}),e.jsxs(Is,{value:K.status,onValueChange:ce=>X({...K,status:ce}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:CEs.map(ce=>e.jsx(ct,{value:ce.value,children:ce.label},ce.value))})]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Property Specs (Optional)"})}),e.jsx(Pe,{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(he,{children:"Bedrooms"}),e.jsx(Ne,{type:"number",value:K.bedrooms,onChange:ce=>X({...K,bedrooms:ce.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Bathrooms"}),e.jsx(Ne,{type:"number",step:"0.5",value:K.bathrooms,onChange:ce=>X({...K,bathrooms:ce.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Sq Ft"}),e.jsx(Ne,{type:"number",value:K.square_footage,onChange:ce=>X({...K,square_footage:ce.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Lot Size"}),e.jsx(Ne,{value:K.lot_size,onChange:ce=>X({...K,lot_size:ce.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Year Built"}),e.jsx(Ne,{type:"number",value:K.year_built,onChange:ce=>X({...K,year_built:ce.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(_r,{checked:K.has_hoa,onCheckedChange:ce=>X({...K,has_hoa:ce})}),e.jsx(he,{children:"Has HOA"})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Description & Links"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:K.description,onChange:ce=>X({...K,description:ce.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Agent Notes"}),e.jsx(or,{value:K.agent_notes,onChange:ce=>X({...K,agent_notes:ce.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{checked:K.agent_notes_public,onCheckedChange:ce=>X({...K,agent_notes_public:ce})}),e.jsx(he,{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(he,{children:"MLS Link"}),e.jsx(Ne,{value:K.mls_link,onChange:ce=>X({...K,mls_link:ce.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Video Link"}),e.jsx(Ne,{value:K.video_link,onChange:ce=>X({...K,video_link:ce.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Pe,{children:e.jsx(NEs,{selectedVideoId:K.video_id,onVideoSelect:ce=>X({...K,video_id:ce}),listingId:l?s:void 0})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Photos"})}),e.jsx(Pe,{children:l&&(h!=null&&h.photos)?e.jsx(jEs,{photos:h.photos,uploading:D,onUpload:ce=>oe(ce),onRemove:ce=>ie(ce),onReorder:ce=>{N.mutate({photos:ce.map(ve=>({id:ve.id,sort_order:ve.sort_order,is_primary:ve.is_primary}))})},onSetPrimary:ce=>{h&&S.mutate({photoId:ce,listingId:h.id})}}):e.jsx(AEs,{photoUrls:z,onRemove:le,onReorder:(ce,ve)=>{Q(ce),F(ve)},pendingPhotos:$,uploading:D,onUpload:re})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Pe,{children:l&&s?e.jsx(SEs,{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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Sharing & Collaboration"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(_r,{checked:K.allow_sharing,onCheckedChange:ce=>X({...K,allow_sharing:ce})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(_r,{checked:K.open_to_referrals,onCheckedChange:ce=>X({...K,open_to_referrals:ce})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(_r,{checked:K.open_to_social_promotion,onCheckedChange:ce=>X({...K,open_to_social_promotion:ce})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(_r,{checked:K.share_with_brokerage,onCheckedChange:ce=>X({...K,share_with_brokerage:ce})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(_r,{checked:K.is_public,onCheckedChange:ce=>X({...K,is_public:ce})})]})]})]}),e.jsx(G,{type:"submit",className:"w-full",size:"lg",disabled:x.isPending||v.isPending,children:x.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]})})}let Lf=null;function MEs(){if(Lf)return Lf;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Lf={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Lf;const r=t.getExtension("WEBGL_debug_renderer_info"),n=r?t.getParameter(r.UNMASKED_RENDERER_WEBGL):"Unknown",a=["swiftshader","llvmpipe","software","microsoft basic render"],i=(n||"").toLowerCase();if(a.some(c=>i.includes(c)))return Lf={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:n},Lf;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Lf={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:n},Lf):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Lf={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:n},Lf):(Lf={canRunVirtualBg:!0,renderer:n},Lf)}catch{return Lf={canRunVirtualBg:!0},Lf}}const IEs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function LEs({value:s,onChange:t,isLoading:r=!1,disabled:n=!1,className:a}){const i=k.useRef(null),[l,o]=k.useState(!1),[c]=k.useState(()=>MEs()),d=!c.canRunVirtualBg,{data:h=[],refetch:m}=mt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:b}}=await V.auth.getUser();if(!b)return[];const{data:N,error:S}=await V.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return S?(console.error("Failed to load backgrounds:",S),[]):N||[]}}),x=h.map(b=>({type:"image",label:b.name,imageUrl:b.image_url,thumbnail:b.thumbnail_url||b.image_url})),y=[...IEs,...x],v=b=>b.type!==s.type?!1:b.type==="image"?b.imageUrl===s.imageUrl:!0,w=async b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];if(N){if(!N.type.startsWith("image/")){ue.error("Please select an image file");return}if(N.size>5*1024*1024){ue.error("Image must be under 5MB");return}o(!0);try{const{data:{user:T}}=await V.auth.getUser();if(!T)throw new Error("Not authenticated");const A=N.name.split(".").pop()||"jpg",I=`${T.id}/${crypto.randomUUID()}.${A}`,{error:D}=await V.storage.from("video-backgrounds").upload(I,N,{contentType:N.type});if(D)throw D;const{data:R}=V.storage.from("video-backgrounds").getPublicUrl(I),$=R.publicUrl,{error:F}=await V.from("video_backgrounds").insert({name:N.name.replace(/\.[^.]+$/,""),image_url:$,thumbnail_url:$,category:"custom",is_stock:!1,user_id:T.id});if(F)throw F;await m(),t({type:"image",imageUrl:$,blurRadius:15}),ue.success("Background uploaded!")}catch(T){console.error("Upload error:",T),ue.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:It("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(id,{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:"}),r&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(es,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),y.map((b,N)=>{const S=v(b);return e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({type:b.type,imageUrl:b.imageUrl,blurRadius:15}),className:It("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",S?"border-primary bg-primary/10":"border-transparent bg-muted/50",n&&"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:[b.type==="none"&&e.jsx(nR,{className:"h-4 w-4 text-muted-foreground"}),b.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"})}),b.type==="image"&&b.thumbnail&&e.jsx("img",{src:b.thumbnail,alt:b.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:b.label})]},`${b.type}-${b.imageUrl||N}`)}),e.jsxs("button",{type:"button",disabled:n||l,onClick:()=>{var b;return(b=i.current)==null?void 0:b.click()},className:It("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",(n||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(es,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx($s,{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:w}),e.jsxs("button",{type:"button",disabled:n,onClick:()=>t({...s,mirror:!s.mirror}),className:It("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",n&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(gR,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var mI=typeof self<"u"?self:{};function imt(s,t){e:{for(var r=["CLOSURE_FLAGS"],n=mI,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,n[r++]=t>>18|240,n[r++]=t>>12&63|128,n[r++]=t>>6&63|128,n[r++]=63&t|128;continue}a--}t=65533}n[r++]=t>>12|224,n[r++]=t>>6&63|128}n[r++]=63&t|128}}s=r===n.length?n:n.subarray(0,r)}return s}function lmt(s){mI.setTimeout(()=>{throw s},0)}var fke,OEs=imt(610401301,!1),OUe=imt(748402147,!0);function FUe(){var s=mI.navigator;return s&&(s=s.userAgent)?s:""}const BUe=mI.navigator;function jxe(s){return jxe[" "](s),s}fke=BUe&&BUe.userAgentData||null,jxe[" "]=function(){};const cmt={};let BD=null;function FEs(s){const t=s.length;let r=3*t/4;r%3?r=Math.floor(r):"=.".indexOf(s[t-1])!=-1&&(r="=.".indexOf(s[t-2])!=-1?r-2:r-1);const n=new Uint8Array(r);let a=0;return function(i,l){function o(d){for(;c>4),m!=64&&(l(h<<4&240|m>>2),x!=64&&l(m<<6&192|x))}}(s,function(i){n[a++]=i}),a!==r?n.subarray(0,a):n}function dmt(){if(!BD){BD={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let r=0;r<5;r++){const n=s.concat(t[r].split(""));cmt[r]=n;for(let a=0;a0)&&(FUe().indexOf("Trident")!=-1||FUe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const zUe=/[-_.]/g,zEs={"-":"+",_:"/",".":"="};function $Es(s){return zEs[s]||""}function hmt(s){if(!umt)return FEs(s);s=zUe.test(s)?s.replace(zUe,$Es):s,s=atob(s);const t=new Uint8Array(s.length);for(let r=0;r=t||(r[s]=n+1,fmt(s=Error(),"incident"),lmt(s))}}function bL(){return typeof BigInt=="function"}var _L=typeof Symbol=="function"&&typeof Symbol()=="symbol";function Uv(s,t,r=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?r&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():t}var VEs=Uv("jas",void 0,!0),$Ue=Uv(void 0,"0di"),xD=Uv(void 0,"1oa"),Qp=Uv(void 0,Symbol()),HEs=Uv(void 0,"0ub"),GEs=Uv(void 0,"0ubs"),xke=Uv(void 0,"0ubsb"),WEs=Uv(void 0,"0actk"),xI=Uv("m_m","Pa",!0),UUe=Uv();const pmt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},xmt=Object.defineProperties,Ba=_L?VEs:"Ga";var f5;const qUe=[];function FB(s,t){_L||Ba in s||xmt(s,pmt),s[Ba]|=t}function Qu(s,t){_L||Ba in s||xmt(s,pmt),s[Ba]=t}function BB(s){return FB(s,34),s}function vF(s){return FB(s,8192),s}Qu(qUe,7),f5=Object.freeze(qUe);var gI={};function lx(s,t){return t===void 0?s.h!==X3&&!!(2&(0|s.v[Ba])):!!(2&t)&&s.h!==X3}const X3={};function UTe(s,t){if(s!=null){if(typeof s=="string")s=s?new vv(s,fI):Z3();else if(s.constructor!==vv)if(zTe(s))s=s.length?new vv(new Uint8Array(s),fI):Z3();else{if(!t)throw Error();s=void 0}}return s}class VUe{constructor(t,r,n){this.g=t,this.h=r,this.l=n}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}}var KEs=Object.freeze({});function gmt(s,t,r){const n=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"),HUe=Nxe(s=>typeof s=="string"),ZEs=Nxe(s=>typeof s=="boolean"),kxe=typeof mI.BigInt=="function"&&typeof mI.BigInt(0)=="bigint";function Jp(s){var t=s;if(HUe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(YEs(t)&&!Number.isSafeInteger(t))throw Error(String(t));return kxe?BigInt(s):s=ZEs(s)?s?"1":"0":HUe(s)?s.trim()||"0":String(s)}var gke=Nxe(s=>kxe?s>=QEs&&s<=eAs:s[0]==="-"?GUe(s,XEs):GUe(s,JEs));const XEs=Number.MIN_SAFE_INTEGER.toString(),QEs=kxe?BigInt(Number.MIN_SAFE_INTEGER):void 0,JEs=Number.MAX_SAFE_INTEGER.toString(),eAs=kxe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function GUe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(n>>0;nd=t,fu=(s-t)/4294967296>>>0}function yI(s){if(s<0){WUe(-s);const[t,r]=HTe(nd,fu);nd=t>>>0,fu=r>>>0}else WUe(s)}function qTe(s){const t=sAs||(sAs=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),fu=0,nd=t.getUint32(0,!0)}function vmt(s,t){const r=4294967296*t+(s>>>0);return Number.isSafeInteger(r)?r:bF(s,t)}function rAs(s,t){return Jp(bL()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):bF(s,t))}function bmt(s,t){return bL()?Jp(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var r=""+(4294967296*t+s);else bL()?r=""+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),r+=8147497*t,t*=2,s>=1e7&&(r+=s/1e7>>>0,s%=1e7),r>=1e7&&(t+=r/1e7>>>0,r%=1e7),r=t+KUe(r)+KUe(s));return r}function KUe(s){return s=String(s),"0000000".slice(s.length)+s}function VTe(s,t){if(2147483648&t)if(bL())s=""+(BigInt(0|t)<>>0));else{const[r,n]=HTe(s,t);s="-"+bF(r,n)}else s=bF(s,t);return s}function Sxe(s){if(s.length<16)yI(Number(s));else if(bL())s=BigInt(s),nd=Number(s&BigInt(4294967295))>>>0,fu=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");fu=nd=0;const r=s.length;for(let n=t,a=(r-t)%6+t;a<=r;n=a,a+=6){const i=Number(s.slice(n,a));fu*=1e6,nd=1e6*nd+i,nd>=4294967296&&(fu+=Math.trunc(nd/4294967296),fu>>>=0,nd>>>=0)}if(t){const[n,a]=HTe(nd,fu);nd=n,fu=a}}}function HTe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function Ly(s){return Array.prototype.slice.call(s)}const zB=typeof BigInt=="function"?BigInt.asIntN:void 0,nAs=typeof BigInt=="function"?BigInt.asUintN:void 0,Q3=Number.isSafeInteger,Cxe=Number.isFinite,vI=Math.trunc,aAs=Jp(0);function zD(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 Y0(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function _F(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 _mt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const iAs=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function $B(s){switch(typeof s){case"bigint":return!0;case"number":return Cxe(s);case"string":return iAs.test(s);default:return!1}}function jL(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Cxe(s)?0|s:void 0}function wmt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return Cxe(s)?s>>>0:void 0}function jmt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(Sxe(s),VTe(nd,fu))}function GTe(s){if(s=vI(s),!Q3(s)){yI(s);var t=nd,r=fu;(s=2147483648&r)&&(r=~r>>>0,(t=1+~t>>>0)==0&&(r=r+1>>>0)),s=typeof(t=vmt(t,r))=="number"?s?-t:t:s?"-"+t:t}return s}function Nmt(s){var t=vI(Number(s));return Q3(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),jmt(s))}function kmt(s){var t=vI(Number(s));return Q3(t)?Jp(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),bL()?Jp(zB(64,BigInt(s))):Jp(jmt(s)))}function Smt(s){return Q3(s)?s=Jp(GTe(s)):(s=vI(s),Q3(s)?s=String(s):(yI(s),s=VTe(nd,fu)),s=Jp(s)),s}function Khe(s){const t=typeof s;return s==null?s:t==="bigint"?Jp(zB(64,s)):$B(s)?t==="string"?kmt(s):Smt(s):void 0}function Cmt(s){if(typeof s!="string")throw Error();return s}function UB(s){if(s!=null&&typeof s!="string")throw Error();return s}function sm(s){return s==null||typeof s=="string"?s:void 0}function WTe(s,t,r,n){return s!=null&&s[xI]===gI?s:Array.isArray(s)?((n=(r=0|s[Ba])|32&n|2&n)!==r&&Qu(s,n),new t(s)):(r?2&n?((s=t[$Ue])||(BB((s=new t).v),s=t[$Ue]=s),t=s):t=new t:t=void 0,t)}function oAs(s,t,r){if(t)e:{if(!$B(t=s))throw pke("int64");switch(typeof t){case"string":t=kmt(t);break e;case"bigint":t=Jp(zB(64,t));break e;default:t=Smt(t)}}else t=Khe(s);return(s=t)==null?r?aAs:void 0:s}const lAs={};let cAs=function(){try{return jxe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class pbe{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,r){return this.g.set(t,r),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,r){return this.g.forEach(t,r)}[Symbol.iterator](){return this.entries()}}const dAs=cAs?(Object.setPrototypeOf(pbe.prototype,Map.prototype),Object.defineProperties(pbe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),pbe):class extends Map{constructor(){super()}};function YUe(s){return s}function xbe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var Ob=class extends dAs{constructor(s,t,r=YUe,n=YUe){super(),this.J=0|s[Ba],this.K=t,this.S=r,this.fa=this.K?uAs:n;for(let a=0;a{s.call(t,a.get(n),n,a)}):super.forEach(s,t)}set(s,t){return xbe(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 r=this.K;return r?((r=this.fa(t,!1,!0,r,this.ra,this.J))!==t&&super.set(s,r),r):t}}[Symbol.iterator](){return this.entries()}};function uAs(s,t,r,n,a,i){return s=WTe(s,n,r,i),a&&(s=YTe(s)),s}function hAs(s){return[s,this.get(s)]}let mAs;function ZUe(){return mAs||(mAs=new Ob(BB([]),void 0,void 0,void 0,lAs))}function Txe(s){return Qp?s[Qp]:void 0}function Yhe(s,t){for(const r in s)!isNaN(r)&&t(s,+r,s[r])}Ob.prototype.toJSON=void 0;var yke=class{};const fAs={Ka:!0};function pAs(s,t){t<100||pI(GEs,1)}function Exe(s,t,r,n){const a=n!==void 0;n=!!n;var i,l=Qp;!a&&_L&&l&&(i=s[l])&&Yhe(i,pAs),l=[];var o=s.length;let c;i=4294967295;let d=!1;const h=!!(64&t),m=h?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,!h||128&t||a||(d=!0,i=i-m+m)),t=void 0;for(var x=0;x=i){const v=x-m;(t??(t={}))[v]=y}else l[x]=y}if(c)for(let y in c){if((o=c[y])==null||(o=r(o,n))==null)continue;let v;x=+y,h&&!Number.isNaN(x)&&(v=x+m){v[b]=Ly(N)}),v.da=y.da,v}(s)),l}function xAs(s){return s[0]=wF(s[0]),s[1]=wF(s[1]),s}function wF(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return gke(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Ba];return s.length===0&&1&t?void 0:Exe(s,t,wF)}if(s!=null&&s[xI]===gI)return Tmt(s);if(s instanceof vv){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(umt){for(var r="",n=0,a=t.length-10240;n>2];i=r[(3&i)<<4|l>>4],l=r[(15&l)<<2|o>>6],o=r[63&o],n[h++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=r[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],n[h]=r[t>>2]+r[(3&t)<<4|c>>4]+o+a}t=n.join("")}s=s.g=t}return s}return s instanceof Ob?s=s.size!==0?s.V(xAs):void 0:void 0}return s}let gAs,yAs;function Tmt(s){return Exe(s=s.v,0|s[Ba],wF)}function f3(s,t){return Emt(s,t[0],t[1])}function Emt(s,t,r,n=0){if(s==null){var a=32;r?(s=[r],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[Ba],OUe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(OUe)throw Error("carr");pI(WEs,5)}(),256&a)throw Error("farr");if(64&a)return(a|n)!==a&&Qu(s,a|n),s;if(r&&(a|=128,r!==s[0]))throw Error("mid");e:{a|=64;var i=(r=s).length;if(i){var l=i-1;const c=r[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 Qu(s,64|a|n),s}function vAs(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var r=0|s[Ba];return s.length===0&&1&r?void 0:XUe(s,r,t)}if(s!=null&&s[xI]===gI)return QUe(s);if(s instanceof Ob){if(2&(t=s.J))return s;if(!s.size)return;if(r=BB(s.V()),s.K)for(s=0;s=i)if(l=s[i],l!=null&&typeof l=="object"&&l.constructor===Object)r=l[t],o=!0;else{if(a!==i)return;r=l}else r=s[a];if(n&&r!=null){if((n=n(r))==null)return n;if(!Object.is(n,r))return o?l[t]=n:s[a]=n,n}return r}}function Rl(s,t,r,n){SL(s),Zu(s=s.v,0|s[Ba],t,r,n)}function Zu(s,t,r,n,a){const i=r+(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[r]=n,t}return i<=l?(s[i]=n,t):(n!==void 0&&(r>=(l=(t??(t=0|s[Ba]))>>14&1023||536870912)?n!=null&&(s[l+(a?0:-1)]={[r]:n}):s[i]=n),t)}function m4(){return KEs===void 0?2:4}function f4(s,t,r,n,a){let i=s.v,l=0|i[Ba];n=lx(s,l)?1:n,a=!!a||n===3,n===2&&kL(s)&&(i=s.v,l=0|i[Ba]);let o=(s=XTe(i,t))===f5?7:0|s[Ba],c=QTe(o,l);var d=!(4&c);if(d){4&c&&(s=Ly(s),o=0,c=x3(c,l),l=Zu(i,l,t,s));let h=0,m=0;for(;h{const o=WTe(l,r,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!lx(n)&&p5(s,t),n}function el(s,t,r,n){let a=s.v,i=0|a[Ba];if((t=Dmt(a,i,t,r,n))==null)return t;if(i=0|a[Ba],!lx(s,i)){const l=YTe(t);l!==t&&(kL(s)&&(a=s.v,i=0|a[Ba]),i=Zu(a,i,r,t=l,n),p5(a,i))}return t}function Rmt(s,t,r,n,a,i,l,o){var c=lx(s,r);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&kL(s)&&(r=0|(t=s.v)[Ba]);var d=(s=XTe(t,a))===f5?7:0|s[Ba],h=QTe(d,r);if(o=!(4&h)){var m=s,x=r;const y=!!(2&h);y&&(x|=2);let v=!y,w=!0,b=0,N=0;for(;b32)for(a|=(127&r)>>4,i=3;i<32&&128&r;i+=7)r=l[o++],a|=(127&r)<>>0,a>>>0);throw Error()}function aEe(s){let t=0,r=s.g;const n=r+10,a=s.h;for(;r>>0}function Xhe(s){var t=s.h;const r=s.g;var n=t[r],a=t[r+1];const i=t[r+2];return t=t[r+3],g3(s,s.g+4),s=2*((a=(n<<0|a<<8|i<<16|t<<24)>>>0)>>31)+1,n=a>>>23&255,a&=8388607,n==255?a?NaN:s*(1/0):n==0?1401298464324817e-60*s*a:s*Math.pow(2,n-150)*(a+8388608)}function bAs(s){return Fj(s)}function g3(s,t){if(s.g=t,t>s.l)throw Error()}function Fmt(s,t){if(t<0)throw Error();const r=s.g;if((t=r+t)>s.l)throw Error();return s.g=t,r}function Bmt(s,t){if(t==0)return Z3();var r=Fmt(s,t);return s.Y&&s.j?r=s.h.subarray(r,r+t):(s=s.h,r=r===(t=r+t)?new Uint8Array(0):tAs?s.slice(r,t):new Uint8Array(s.subarray(r,t))),r.length==0?Z3():new vv(r,fI)}var JUe=[];function zmt(s,t,r,n){if(Qhe.length){const a=Qhe.pop();return a.o(n),a.g.init(s,t,r,n),a}return new _As(s,t,r,n)}function $mt(s){s.g.clear(),s.l=-1,s.h=-1,Qhe.length<100&&Qhe.push(s)}function Umt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var r=Av(s.g);if(t=r>>>3,!((r&=7)>=0&&r<=5)||t<1)throw Error();return s.l=t,s.h=r,!0}function Sce(s){switch(s.h){case 0:s.h!=0?Sce(s):aEe(s.g);break;case 1:g3(s=s.g,s.g+8);break;case 2:if(s.h!=2)Sce(s);else{var t=Av(s.g);g3(s=s.g,s.g+t)}break;case 5:g3(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!Umt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}Sce(s)}break;default:throw Error()}}function qB(s,t,r){const n=s.g.l;var a=Av(s.g);let i=(a=s.g.g+a)-n;if(i<=0&&(s.g.l=a,r(t,s,void 0,void 0,void 0),i=a-s.g.g),i)throw Error();return s.g.g=a,s.g.l=n,t}function iEe(s){var t=Av(s.g),r=Fmt(s=s.g,t);if(s=s.h,PEs){var n,a=s;(n=fbe)||(n=fbe=new TextDecoder("utf-8",{fatal:!0})),t=r+t,a=r===0&&t===a.length?a:a.subarray(r,t);try{var i=n.decode(a)}catch(o){if(z$===void 0){try{n.decode(new Uint8Array([128]))}catch{}try{n.decode(new Uint8Array([97])),z$=!0}catch{z$=!1}}throw!z$&&(fbe=void 0),o}}else{t=(i=r)+t,r=[];let o,c=null;for(;i=t?SN():(o=s[i++],l<194||(192&o)!=128?(i--,SN()):r.push((31&l)<<6|63&o)):l<240?i>=t-1?SN():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(n=s[i++]))!=128?(i--,SN()):r.push((15&l)<<12|(63&o)<<6|63&n)):l<=244?i>=t-2?SN():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(n=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,SN()):(l=(7&l)<<18|(63&o)<<12|(63&n)<<6|63&a,l-=65536,r.push(55296+(l>>10&1023),56320+(1023&l)))):SN(),r.length>=8192&&(c=RUe(c,r),r.length=0)}i=RUe(c,r)}return i}function qmt(s){const t=Av(s.g);return Bmt(s.g,t)}function Mxe(s,t,r){var n=Av(s.g);for(n=s.g.g+n;s.g.g>>0,this.g=t>>>0}};let wAs;function tqe(s){return s?/^-?\d+$/.test(s)?(Sxe(s),new bke(nd,fu)):null:jAs||(jAs=new bke(0,0))}var bke=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let jAs;function KA(s,t,r){for(;r>0||t>127;)s.g.push(127&t|128),t=(t>>>7|r<<25)>>>0,r>>>=7;s.g.push(t)}function TL(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function Ixe(s,t){if(t>=0)TL(s,t);else{for(let r=0;r<9;r++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function oEe(s){var t=nd;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 bI(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Ng(s,t,r){TL(s.g,8*t+r)}function lEe(s,t){return Ng(s,t,2),t=s.g.end(),bI(s,t),t.push(s.h),t}function cEe(s,t){var r=t.pop();for(r=s.h+s.g.length()-r;r>127;)t.push(127&r|128),r>>>=7,s.h++;t.push(r),s.h++}function Lxe(s,t,r){Ng(s,t,2),TL(s.g,r.length),bI(s,s.g.end()),bI(s,r)}function Jhe(s,t,r,n){r!=null&&(t=lEe(s,t),n(r,s),cEe(s,t))}function qv(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var dEe=qv(),Vmt=qv(),uEe=qv(),hEe=qv(),mEe=qv(),Hmt=qv(),NAs=qv(),Pxe=qv(),Gmt=qv(),Wmt=qv();function Vv(s,t,r){var n=s.v;Qp&&Qp in n&&(n=n[Qp])&&delete n[t.g],t.h?t.j(s,t.h,t.g,r,t.l):t.j(s,t.g,r,t.l)}var za=class{constructor(s,t){this.v=Emt(s,t,void 0,2048)}toJSON(){return Tmt(this)}j(){var a;var s=aMs,t=this.v,r=s.g,n=Qp;if(_L&&n&&((a=t[n])==null?void 0:a[r])!=null&&pI(HEs,3),t=s.g,UUe&&Qp&&UUe===void 0&&(n=(r=this.v)[Qp])&&(n=n.da))try{n(r,t,fAs)}catch(i){lmt(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[Ba];return ZTe(this,s,t)?KTe(this,s,!0):new this.constructor(NL(s,t,!1))}};za.prototype[xI]=gI,za.prototype.toString=function(){return this.v.toString()};var EL=class{constructor(s,t,r){this.g=s,this.h=t,s=dEe,this.l=!!s&&r===s||!1}};function Dxe(s,t){return new EL(s,t,dEe)}function Kmt(s,t,r,n,a){Jhe(s,r,Qmt(t,n),a)}const kAs=Dxe(function(s,t,r,n,a){return s.h===2&&(qB(s,tEe(t,n,r),a),!0)},Kmt),SAs=Dxe(function(s,t,r,n,a){return s.h===2&&(qB(s,tEe(t,n,r),a),!0)},Kmt);var Rxe=Symbol(),Oxe=Symbol(),_ke=Symbol(),sqe=Symbol(),rqe=Symbol();let Ymt,Zmt;function x5(s,t,r,n){var a=n[s];if(a)return a;(a={}).qa=n,a.T=function(m){switch(typeof m){case"boolean":return gAs||(gAs=[0,void 0,!0]);case"number":return m>0?void 0:m===0?yAs||(yAs=[0,void 0]):[-m,void 0];case"string":return[0,m];case"object":return m}}(n[0]);var i=n[1];let l=1;i&&i.constructor===Object&&(a.ba=i,typeof(i=n[++l])=="function"&&(a.ma=!0,Ymt??(Ymt=i),Zmt??(Zmt=n[l+1]),i=n[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,n):a}function pEe(s,t,r,n,a){const i=r.g;let l,o;s[t]=(c,d,h)=>i(c,d,h,o||(o=x5(Oxe,fEe,pEe,n).T),l||(l=xEe(n)),a)}function xEe(s){let t=s[_ke];if(t!=null)return t;const r=x5(Oxe,fEe,pEe,s);return t=r.ma?(n,a)=>Ymt(n,a,r):(n,a)=>{for(;Umt(a)&&a.h!=4;){var i=a.l,l=r[i];if(l==null){var o=r.ba;o&&(o=o[i])&&(o=TAs(o))!=null&&(l=r[i]=o)}if(l==null||!l(a,n,i)){if(l=(o=a).m,Sce(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=Bmt(o.g,c);l=void 0,o=n,c&&((l=o[Qp]??(o[Qp]=new yke))[i]??(l[i]=[])).push(c)}}return(n=Txe(n))&&(n.da=r.qa[rqe]),!0},s[_ke]=t,s[rqe]=CAs.bind(s),t}function CAs(s,t,r,n){var a=this[Oxe];const i=this[_ke],l=f3(void 0,a.T),o=Txe(s);if(o){var c=!1,d=a.ba;if(d){if(a=(h,m,x)=>{if(x.length!==0)if(d[m])for(const y of x){h=zmt(y);try{c=!0,i(l,h)}finally{$mt(h)}}else n==null||n(s,m,x)},t==null)Yhe(o,a);else if(o!=null){const h=o[t];h&&a(o,t,h)}if(c){let h=0|s[Ba];if(2&h&&2048&h&&!(r!=null&&r.Ka))throw Error();const m=wL(h),x=(y,v)=>{if(Fb(s,y,m)!=null){if((r==null?void 0:r.Qa)===1)return;throw Error()}v!=null&&(h=Zu(s,h,y,v,m)),delete o[y]};t==null?gmt(l,0|l[Ba],(y,v)=>{x(y,v)}):x(t,Fb(l,t,m))}}}}function TAs(s){const t=(s=Xmt(s))[0].g;if(s=s[1]){const r=xEe(s),n=x5(Oxe,fEe,pEe,s).T;return(a,i,l)=>t(a,i,l,n,r)}return t}function Fxe(s,t,r){s[t]=r.h}function Bxe(s,t,r,n){let a,i;const l=r.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=x5(Rxe,Fxe,Bxe,n).T),a||(a=Jmt(n)))}function Jmt(s){let t=s[sqe];if(!t){const r=x5(Rxe,Fxe,Bxe,s);t=(n,a)=>eft(n,a,r),s[sqe]=t}return t}function eft(s,t,r){gmt(s,0|s[Ba],(n,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=Xmt(c))[0].h;if(c=c[1]){const h=Jmt(c),m=x5(Rxe,Fxe,Bxe,c).T;c=l.ma?Zmt(m,h):(x,y,v)=>d(x,y,v,m,h)}else c=d;return l[o]=c}}(r,n);i?i(t,a,n):n<500||pI(xke,3)}}),(s=Txe(s))&&Yhe(s,(n,a,i)=>{for(bI(t,t.g.end()),n=0;n{Jhe(s,r,f3([l,i],n),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),KA(s.g,r.h,r.g);break;default:r=tqe(t),KA(s.g,r.h,r.g)}}function rft(s,t,r){(t=jL(t))!=null&&t!=null&&(Ng(s,r,0),Ixe(s.g,t))}function nft(s,t,r){(t=_mt(t))!=null&&(Ng(s,r,0),s.g.g.push(t?1:0))}function aft(s,t,r){(t=sm(t))!=null&&Lxe(s,r,omt(t))}function ift(s,t,r,n,a){Jhe(s,r,Qmt(t,n),a)}function oft(s,t,r){(t=t==null||typeof t=="string"||t instanceof vv?t:void 0)!=null&&Lxe(s,r,rEe(t,!0).buffer)}function lft(s,t,r){(t=wmt(t))!=null&&t!=null&&(Ng(s,r,0),TL(s.g,t))}function cft(s,t,r){return(s.h===5||s.h===2)&&(t=CL(t,0|t[Ba],r),s.h==2?Mxe(s,Xhe,t):t.push(Xhe(s.g)),!0)}var gu=Am(function(s,t,r){return s.h===5&&(Mm(t,r,Xhe(s.g)),!0)},tft,Pxe),MAs=ML(cft,function(s,t,r){if((t=AL(Y0,t))!=null)for(let l=0;l=0?n=String(a):((a=n.indexOf("."))!==-1&&(n=n.substring(0,a)),(a=n[0]!=="-"&&((a=n.length)<20||a===20&&n<="18446744073709551615"))||(Sxe(n),n=bF(nd,fu))),n;if(a==="number")return(n=vI(n))>=0&&Q3(n)||(yI(n),n=vmt(nd,fu)),n}}(t),t!=null&&(typeof t=="string"&&eqe(t),t!=null))switch(Ng(s,r,0),typeof t){case"number":s=s.g,yI(t),KA(s,nd,fu);break;case"bigint":r=BigInt.asUintN(64,t),r=new vke(Number(r&BigInt(4294967295)),Number(r>>BigInt(32))),KA(s.g,r.h,r.g);break;default:r=eqe(t),KA(s.g,r.h,r.g)}},NAs),Vu=Am(function(s,t,r){return s.h===0&&(Mm(t,r,Fj(s.g)),!0)},rft,hEe),VB=ML(function(s,t,r){return(s.h===0||s.h===2)&&(t=CL(t,0|t[Ba],r),s.h==2?Mxe(s,Fj,t):t.push(Fj(s.g)),!0)},function(s,t,r){if((t=AL(jL,t))!=null&&t.length){r=lEe(s,r);for(let n=0;n{{const i={ea:!0};n&&Object.assign(i,n),r=zmt(r,void 0,void 0,i);try{const l=new s,o=l.v;xEe(t)(o,r);var a=l}finally{$mt(r)}}return a}}function zxe(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}}}};eft(this.v,t,x5(Rxe,Fxe,Bxe,s)),bI(t,t.g.end());const r=new Uint8Array(t.h),n=t.l,a=n.length;let i=0;for(let l=0;la;r=iqe.createPolicy("goog#html",{createHTML:n,createScript:n,createScriptURL:n})}catch{}return r}()),s=(t=vbe)?t.createScriptURL(s):s,new class{constructor(r){this.g=r}toString(){return this.g+""}}(s)}function $$(s,...t){if(t.length===0)return oqe(s[0]);let r=s[0];for(let n=0;n({index:rg(n,1)??0??-1,score:Wd(n,2)??0,categoryName:sm(cd(n,3))??""??"",displayName:sm(cd(n,4))??""??""})),headIndex:t,headName:r}}function cMs(s){const t={classifications:Bb(s,VAs,1).map(r=>{var n;return kEe(((n=el(r,yft,4))==null?void 0:n.g())??[],rg(r,2)??0,sm(cd(r,3))??"")})};return function(r){return r==null?r:typeof r=="bigint"?(gke(r)?r=Number(r):(r=zB(64,r),r=gke(r)?Number(r):String(r)),r):$B(r)?typeof r=="number"?GTe(r):Nmt(r):void 0}(cd(s,2,void 0,void 0,Khe))!=null&&(t.timestampMs=Hft(cd(s,2,void 0,void 0,Khe)??Amt)),t}function Gft(s){var l,o;var t=f4(s,3,Y0,m4()),r=f4(s,2,jL,m4()),n=f4(s,1,sm,m4()),a=f4(s,9,sm,m4());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function vqe(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let r=0,n=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function bqe(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((r,n)=>{t.addEventListener("load",()=>{r()},!1),t.addEventListener("error",a=>{n(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;await self.import(s.toString())}}function Yft(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 Ua(s,t,r){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),r(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function _qe(s,t,r){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(r?s.i._bindTextureToStream(r):s.i._bindTextureToCanvas(),!(r=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&&r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!0),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),s.i.gpuOriginForWebTexturesIsBottomLeft&&r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1);const[n,a]=Yft(t);return!s.l||n===s.i.canvas.width&&a===s.i.canvas.height||(s.i.canvas.width=n,s.i.canvas.height=a),[n,a]}function wqe(s,t,r){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const n=new Uint32Array(t.length);for(let a=0;a>2),r(t);for(const a of n)s.i._free(a);s.i._free(t)}function y0(s,t,r){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=r}function $_(s,t,r){let n=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(r(n,l),n=[]):n.push(a)}}SE.forVisionTasks=function(s,t=!1){return q$("vision",s??$$``,t)},SE.forTextTasks=function(s,t=!1){return q$("text",s??$$``,t)},SE.forGenAiTasks=function(s,t=!1){return q$("genai",s??$$``,t)},SE.forAudioTasks=function(s,t=!1){return q$("audio",s??$$``,t)},SE.isSimdSupported=function(s=!1){return Wft(s)};async function uMs(s,t,r,n){return s=await(async(a,i,l,o,c)=>{if(i&&await bqe(i),!self.ModuleFactory||l&&(await bqe(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,r.wasmLoaderPath,r.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?r.wasmBinaryPath.toString():r.assetBinaryPath&&a.endsWith(".data")?r.assetBinaryPath.toString():a}),await s.o(n),s}function wbe(s,t){const r=el(s.baseOptions,eme,1)||new eme;typeof t=="string"?(Rl(r,2,UB(t)),Rl(r,1)):t instanceof Uint8Array&&(Rl(r,1,UTe(t,!1)),Rl(r,2)),li(s.baseOptions,0,1,r)}function jqe(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(r=>r.message).join(", "))}finally{s.H=[]}}function Na(s,t){s.C=Math.max(s.C,t)}function Vxe(s,t){s.B=new op,cx(s.B,2,"PassThroughCalculator"),Gc(s.B,"free_memory"),Po(s.B,"free_memory_unused_out"),md(t,"free_memory"),kg(t,s.B)}function _I(s,t){Gc(s.B,t),Po(s.B,t+"_unused_out")}function Hxe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var Ske=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,t=!0){var r,n,a,i,l,o;if(t){const c=s.baseOptions||{};if((r=s.baseOptions)!=null&&r.modelAssetBuffer&&((n=s.baseOptions)!=null&&n.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((a=el(this.baseOptions,eme,1))!=null&&a.g()||(i=el(this.baseOptions,eme,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,h){let m=el(d.baseOptions,fqe,3);if(!m){var x=m=new fqe,y=new lqe;PO(x,4,Cce,y)}"delegate"in h&&(h.delegate==="GPU"?(h=m,x=new OAs,PO(h,2,Cce,x)):(h=m,x=new lqe,PO(h,4,Cce,x))),li(d.baseOptions,0,3,m)}(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),wbe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)wbe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const h=[];for(var m=0;;){const{done:x,value:y}=await d.read();if(x)break;h.push(y),m+=y.length}if(h.length===0)return new Uint8Array(0);if(h.length===1)return h[0];d=new Uint8Array(m),m=0;for(const x of h)d.set(x,m),m+=x.length;return d}(c.modelAssetBuffer).then(d=>{wbe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=FAs(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((r,n)=>{this.H.push(Error(n))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,jqe(this)}finishProcessing(){this.g.finishProcessing(),jqe(this)}close(){this.B=void 0,this.g.closeGraph()}};function bj(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}Ske.prototype.close=Ske.prototype.close;class hMs{constructor(t,r,n,a){this.g=t,this.h=r,this.m=n,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 Nqe(s,t,r){const n=s.g;if(r=bj(n.createShader(r),"Failed to create WebGL shader"),n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${n.getShaderInfoLog(r)}`);return n.attachShader(s.h,r),r}function kqe(s,t){const r=s.g,n=bj(r.createVertexArray(),"Failed to create vertex array");r.bindVertexArray(n);const a=bj(r.createBuffer(),"Failed to create buffer");r.bindBuffer(r.ARRAY_BUFFER,a),r.enableVertexAttribArray(s.O),r.vertexAttribPointer(s.O,2,r.FLOAT,!1,0,0),r.bufferData(r.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),r.STATIC_DRAW);const i=bj(r.createBuffer(),"Failed to create buffer");return r.bindBuffer(r.ARRAY_BUFFER,i),r.enableVertexAttribArray(s.L),r.vertexAttribPointer(s.L,2,r.FLOAT,!1,0,0),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),r.STATIC_DRAW),r.bindBuffer(r.ARRAY_BUFFER,null),r.bindVertexArray(null),new hMs(r,n,a,i)}function SEe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function mMs(s,t,r,n){return SEe(s,t),s.h||(s.m(),s.D()),r?(s.u||(s.u=kqe(s,!0)),r=s.u):(s.A||(s.A=kqe(s,!1)),r=s.A),t.useProgram(s.h),r.bind(),s.l(),s=n(),r.g.bindVertexArray(null),s}function Zft(s,t,r){return SEe(s,t),s=bj(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,r??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),s}function Xft(s,t,r){SEe(s,t),s.B||(s.B=bj(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,s.B),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0)}function fMs(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var Qft=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=bj(s.createProgram(),"Failed to create WebGL program"),this.X=Nqe(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=Nqe(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 eb(s,t){switch(t){case 0:return s.g.find(r=>r instanceof Uint8Array);case 1:return s.g.find(r=>r instanceof Float32Array);case 2:return s.g.find(r=>typeof WebGLTexture<"u"&&r instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function Cke(s){var t=eb(s,1);if(!t){if(t=eb(s,0))t=new Float32Array(t).map(n=>n/255);else{t=new Float32Array(s.width*s.height);const n=wI(s);var r=CEe(s);if(Xft(r,n,Jft(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){r=new Float32Array(s.width*s.height*4),n.readPixels(0,0,s.width,s.height,n.RGBA,n.FLOAT,r);for(let a=0,i=0;aMath.round(255*r))),s.g.push(t)),t;var s,t}ia(){return Cke(this)}N(){return Jft(this)}clone(){const s=[];for(const t of this.g){let r;if(t instanceof Uint8Array)r=new Uint8Array(t);else if(t instanceof Float32Array)r=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const n=wI(this),a=CEe(this);n.activeTexture(n.TEXTURE1),r=Zft(a,n,this.m?n.LINEAR:n.NEAREST),n.bindTexture(n.TEXTURE_2D,r);const i=ept(this);n.texImage2D(n.TEXTURE_2D,0,i,this.width,this.height,0,n.RED,n.FLOAT,null),n.bindTexture(n.TEXTURE_2D,null),Xft(a,n,r),mMs(a,n,!1,()=>{tpt(this),n.clearColor(0,0,0,0),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.TRIANGLE_FAN,0,4),Tke(this)}),fMs(a),Tke(this)}}s.push(r)}return new dh(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&wI(this).deleteTexture(eb(this,2)),Sqe=-1}};dh.prototype.close=dh.prototype.close,dh.prototype.clone=dh.prototype.clone,dh.prototype.getAsWebGLTexture=dh.prototype.N,dh.prototype.getAsFloat32Array=dh.prototype.ia,dh.prototype.getAsUint8Array=dh.prototype.ja,dh.prototype.hasWebGLTexture=dh.prototype.R,dh.prototype.hasFloat32Array=dh.prototype.ka,dh.prototype.hasUint8Array=dh.prototype.Fa;var Sqe=250;function Vy(...s){return s.map(([t,r])=>({start:t,end:r}))}const pMs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((Cqe=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:Kft()?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 r=s.length,n=this.i._malloc(r);this.i.HEAPU8.set(s,n),t?this.i._changeBinaryGraph(r,n):this.i._changeTextGraph(r,n),this.i._free(n)}configureAudio(s,t,r,n,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),Ua(this,n||"input_audio",i=>{Ua(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,r)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){y0(this,"__graph_config__",t=>{s(t)}),Ua(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,r){this.addAudioToStreamWithShape(s,0,0,t,r)}addAudioToStreamWithShape(s,t,r,n,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),Ua(this,n,l=>{this.i._addAudioToInputStream(this.g,t,r,l,a)})}addGpuBufferToStream(s,t,r){Ua(this,t,n=>{const[a,i]=_qe(this,s,n);this.i._addBoundTextureToStream(n,a,i,r)})}addBoolToStream(s,t,r){Ua(this,t,n=>{this.i._addBoolToInputStream(s,n,r)})}addDoubleToStream(s,t,r){Ua(this,t,n=>{this.i._addDoubleToInputStream(s,n,r)})}addFloatToStream(s,t,r){Ua(this,t,n=>{this.i._addFloatToInputStream(s,n,r)})}addIntToStream(s,t,r){Ua(this,t,n=>{this.i._addIntToInputStream(s,n,r)})}addUintToStream(s,t,r){Ua(this,t,n=>{this.i._addUintToInputStream(s,n,r)})}addStringToStream(s,t,r){Ua(this,t,n=>{Ua(this,s,a=>{this.i._addStringToInputStream(a,n,r)})})}addStringRecordToStream(s,t,r){Ua(this,t,n=>{wqe(this,Object.keys(s),a=>{wqe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,n,r)})})})}addProtoToStream(s,t,r,n){Ua(this,r,a=>{Ua(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,n),this.i._free(l)})})}addEmptyPacketToStream(s,t){Ua(this,s,r=>{this.i._addEmptyPacketToInputStream(r,t)})}addBoolVectorToStream(s,t,r){Ua(this,t,n=>{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,n,r)})}addDoubleVectorToStream(s,t,r){Ua(this,t,n=>{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,n,r)})}addFloatVectorToStream(s,t,r){Ua(this,t,n=>{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,n,r)})}addIntVectorToStream(s,t,r){Ua(this,t,n=>{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,n,r)})}addUintVectorToStream(s,t,r){Ua(this,t,n=>{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,n,r)})}addStringVectorToStream(s,t,r){Ua(this,t,n=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)Ua(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,n,r)})}addBoolToInputSidePacket(s,t){Ua(this,t,r=>{this.i._addBoolToInputSidePacket(s,r)})}addDoubleToInputSidePacket(s,t){Ua(this,t,r=>{this.i._addDoubleToInputSidePacket(s,r)})}addFloatToInputSidePacket(s,t){Ua(this,t,r=>{this.i._addFloatToInputSidePacket(s,r)})}addIntToInputSidePacket(s,t){Ua(this,t,r=>{this.i._addIntToInputSidePacket(s,r)})}addUintToInputSidePacket(s,t){Ua(this,t,r=>{this.i._addUintToInputSidePacket(s,r)})}addStringToInputSidePacket(s,t){Ua(this,t,r=>{Ua(this,s,n=>{this.i._addStringToInputSidePacket(n,r)})})}addProtoToInputSidePacket(s,t,r){Ua(this,r,n=>{Ua(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,n),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){Ua(this,t,r=>{const n=this.i._allocateBoolVector(s.length);if(!n)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(n,a);this.i._addBoolVectorToInputSidePacket(n,r)})}addDoubleVectorToInputSidePacket(s,t){Ua(this,t,r=>{const n=this.i._allocateDoubleVector(s.length);if(!n)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(n,a);this.i._addDoubleVectorToInputSidePacket(n,r)})}addFloatVectorToInputSidePacket(s,t){Ua(this,t,r=>{const n=this.i._allocateFloatVector(s.length);if(!n)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(n,a);this.i._addFloatVectorToInputSidePacket(n,r)})}addIntVectorToInputSidePacket(s,t){Ua(this,t,r=>{const n=this.i._allocateIntVector(s.length);if(!n)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(n,a);this.i._addIntVectorToInputSidePacket(n,r)})}addUintVectorToInputSidePacket(s,t){Ua(this,t,r=>{const n=this.i._allocateUintVector(s.length);if(!n)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(n,a);this.i._addUintVectorToInputSidePacket(n,r)})}addStringVectorToInputSidePacket(s,t){Ua(this,t,r=>{const n=this.i._allocateStringVector(s.length);if(!n)throw Error("Unable to allocate new string vector on heap.");for(const a of s)Ua(this,a,i=>{this.i._addStringVectorEntry(n,i)});this.i._addStringVectorToInputSidePacket(n,r)})}attachBoolListener(s,t){y0(this,s,t),Ua(this,s,r=>{this.i._attachBoolListener(r)})}attachBoolVectorListener(s,t){$_(this,s,t),Ua(this,s,r=>{this.i._attachBoolVectorListener(r)})}attachIntListener(s,t){y0(this,s,t),Ua(this,s,r=>{this.i._attachIntListener(r)})}attachIntVectorListener(s,t){$_(this,s,t),Ua(this,s,r=>{this.i._attachIntVectorListener(r)})}attachUintListener(s,t){y0(this,s,t),Ua(this,s,r=>{this.i._attachUintListener(r)})}attachUintVectorListener(s,t){$_(this,s,t),Ua(this,s,r=>{this.i._attachUintVectorListener(r)})}attachDoubleListener(s,t){y0(this,s,t),Ua(this,s,r=>{this.i._attachDoubleListener(r)})}attachDoubleVectorListener(s,t){$_(this,s,t),Ua(this,s,r=>{this.i._attachDoubleVectorListener(r)})}attachFloatListener(s,t){y0(this,s,t),Ua(this,s,r=>{this.i._attachFloatListener(r)})}attachFloatVectorListener(s,t){$_(this,s,t),Ua(this,s,r=>{this.i._attachFloatVectorListener(r)})}attachStringListener(s,t){y0(this,s,t),Ua(this,s,r=>{this.i._attachStringListener(r)})}attachStringVectorListener(s,t){$_(this,s,t),Ua(this,s,r=>{this.i._attachStringVectorListener(r)})}attachProtoListener(s,t,r){y0(this,s,t),Ua(this,s,n=>{this.i._attachProtoListener(n,r||!1)})}attachProtoVectorListener(s,t,r){$_(this,s,t),Ua(this,s,n=>{this.i._attachProtoVectorListener(n,r||!1)})}attachAudioListener(s,t,r){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),y0(this,s,(n,a)=>{n=new Float32Array(n.buffer,n.byteOffset,n.length/4),t(n,a)}),Ua(this,s,n=>{this.i._attachAudioListener(n,r||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends Cqe{get ga(){return this.i}pa(s,t,r){Ua(this,t,n=>{const[a,i]=_qe(this,s,n);this.ga._addBoundTextureAsImageToStream(n,a,i,r)})}Z(s,t){y0(this,s,t),Ua(this,s,r=>{this.ga._attachImageListener(r)})}aa(s,t){$_(this,s,t),Ua(this,s,r=>{this.ga._attachImageVectorListener(r)})}}));var Cqe,Hy=class extends pMs{};async function Yo(s,t,r){return async function(n,a,i,l){return uMs(n,a,i,l)}(s,r.canvas??(Kft()?void 0:document.createElement("canvas")),t,r)}function spt(s,t,r,n){if(s.U){const i=new jft;if(r!=null&&r.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=r.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].");Ka(i,1,(a.left+a.right)/2),Ka(i,2,(a.top+a.bottom)/2),Ka(i,4,a.right-a.left),Ka(i,3,a.bottom-a.top)}else Ka(i,1,.5),Ka(i,2,.5),Ka(i,4,1),Ka(i,3,1);if(r!=null&&r.rotationDegrees){if((r==null?void 0:r.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Ka(i,5,-Math.PI*r.rotationDegrees/180),(r==null?void 0:r.rotationDegrees)%180!=0){const[l,o]=Yft(t);r=Wd(i,3)*o/l,a=Wd(i,4)*l/o,Ka(i,4,r),Ka(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,n)}s.g.pa(t,s.X,n??performance.now()),s.finishProcessing()}function Gy(s,t,r){var n;if((n=s.baseOptions)!=null&&n.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");spt(s,t,r,s.C+1)}function Gv(s,t,r,n){var a;if(!((a=s.baseOptions)!=null&&a.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");spt(s,t,r,n)}function jI(s,t,r,n){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 dh([a],r,!1,s.g.i.canvas,s.P,i,t),n?s.clone():s}var dx=class extends Ske{constructor(s,t,r,n){super(s),this.g=s,this.X=t,this.U=r,this.oa=n,this.P=new Qft}l(s,t=!0){if("runningMode"in s&&Rl(this.baseOptions,2,_F(!!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()}};dx.prototype.close=dx.prototype.close;var Dx=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},li(s=this.h=new Uxe,0,1,t=new Od),Ka(this.h,2,.5),Ka(this.h,3,.3)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Ka(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Ka(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},Gy(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},Gv(this,s,r,t),this.j}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect_in"),hl(s,"detections");const t=new px;Vv(t,ZAs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect_in"),Po(r,"DETECTIONS:detections"),r.o(t),kg(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=bft(i),this.j.detections.push(Gft(n));Na(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Dx.prototype.detectForVideo=Dx.prototype.G,Dx.prototype.detect=Dx.prototype.F,Dx.prototype.setOptions=Dx.prototype.o,Dx.createFromModelPath=async function(s,t){return Yo(Dx,s,{baseOptions:{modelAssetPath:t}})},Dx.createFromModelBuffer=function(s,t){return Yo(Dx,s,{baseOptions:{modelAssetBuffer:t}})},Dx.createFromOptions=function(s,t){return Yo(Dx,s,t)};var TEe=Vy([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]),EEe=Vy([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]),AEe=Vy([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),rpt=Vy([474,475],[475,476],[476,477],[477,474]),MEe=Vy([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]),IEe=Vy([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),npt=Vy([469,470],[470,471],[471,472],[472,469]),LEe=Vy([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]),apt=[...TEe,...EEe,...AEe,...MEe,...IEe,...LEe],ipt=Vy([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 Tqe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var vd=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,li(s=this.h=new Tft,0,1,t=new Od),this.A=new Cft,li(this.h,0,3,this.A),this.u=new Uxe,li(this.h,0,2,this.u),zb(this.u,4,1),Ka(this.u,2,.5),Ka(this.A,2,.5),Ka(this.h,4,.5)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return"numFaces"in s&&zb(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Ka(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Ka(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 Tqe(this),Gy(this,s,t),this.j}G(s,t,r){return Tqe(this),Gv(this,s,r,t),this.j}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect"),hl(s,"face_landmarks");const t=new px;Vv(t,QAs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"NORM_LANDMARKS:face_landmarks"),r.o(t),kg(s,r),this.g.attachProtoVectorListener("face_landmarks",(n,a)=>{for(const i of n)n=HB(i),this.j.faceLandmarks.push(qxe(n));Na(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",n=>{Na(this,n)}),this.outputFaceBlendshapes&&(hl(s,"blendshapes"),Po(r,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(n,a)=>{if(this.outputFaceBlendshapes)for(const i of n)n=$xe(i),this.j.faceBlendshapes.push(kEe(n.g()??[]));Na(this,a)}),this.g.attachEmptyPacketListener("blendshapes",n=>{Na(this,n)})),this.outputFacialTransformationMatrixes&&(hl(s,"face_geometry"),Po(r,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(n,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of n)(n=el(n=XAs(i),UAs,2))&&this.j.facialTransformationMatrixes.push({rows:rg(n,1)??0??0,columns:rg(n,2)??0??0,data:f4(n,3,Y0,m4()).slice()??[]});Na(this,a)}),this.g.attachEmptyPacketListener("face_geometry",n=>{Na(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};vd.prototype.detectForVideo=vd.prototype.G,vd.prototype.detect=vd.prototype.F,vd.prototype.setOptions=vd.prototype.o,vd.createFromModelPath=function(s,t){return Yo(vd,s,{baseOptions:{modelAssetPath:t}})},vd.createFromModelBuffer=function(s,t){return Yo(vd,s,{baseOptions:{modelAssetBuffer:t}})},vd.createFromOptions=function(s,t){return Yo(vd,s,t)},vd.FACE_LANDMARKS_LIPS=TEe,vd.FACE_LANDMARKS_LEFT_EYE=EEe,vd.FACE_LANDMARKS_LEFT_EYEBROW=AEe,vd.FACE_LANDMARKS_LEFT_IRIS=rpt,vd.FACE_LANDMARKS_RIGHT_EYE=MEe,vd.FACE_LANDMARKS_RIGHT_EYEBROW=IEe,vd.FACE_LANDMARKS_RIGHT_IRIS=npt,vd.FACE_LANDMARKS_FACE_OVAL=LEe,vd.FACE_LANDMARKS_CONTOURS=apt,vd.FACE_LANDMARKS_TESSELATION=ipt;var PEe=Vy([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 Eqe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function Aqe(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 Mqe(s,t=!0){const r=[];for(const a of s){var n=$xe(a);s=[];for(const i of n.g())n=t&&rg(i,1)!=null?rg(i,1)??0:-1,s.push({score:Wd(i,2)??0,index:n,categoryName:sm(cd(i,3))??""??"",displayName:sm(cd(i,4))??""??""});r.push(s)}return r}var yp=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],li(s=this.j=new Mft,0,1,t=new Od),this.u=new _Ee,li(this.j,0,2,this.u),this.D=new bEe,li(this.u,0,3,this.D),this.A=new Aft,li(this.u,0,2,this.A),this.h=new JAs,li(this.j,0,3,this.h),Ka(this.A,2,.5),Ka(this.u,4,.5),Ka(this.D,2,.5)}get baseOptions(){return el(this.j,Od,1)}set baseOptions(s){li(this.j,0,1,s)}o(s){var a,i,l,o;if(zb(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ka(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ka(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new lE,r=t,n=kke(s.cannedGesturesClassifierOptions,(a=el(this.h,lE,3))==null?void 0:a.l());li(r,0,2,n),li(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=el(this.h,lE,3))==null||i.g());return s.customGesturesClassifierOptions?(li(r=t=new lE,0,2,n=kke(s.customGesturesClassifierOptions,(l=el(this.h,lE,4))==null?void 0:l.l())),li(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=el(this.h,lE,4))==null||o.g()),this.l(s)}Ha(s,t){return Eqe(this),Gy(this,s,t),Aqe(this)}Ia(s,t,r){return Eqe(this),Gv(this,s,r,t),Aqe(this)}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect"),hl(s,"hand_gestures"),hl(s,"hand_landmarks"),hl(s,"world_hand_landmarks"),hl(s,"handedness");const t=new px;Vv(t,eMs,this.j);const r=new op;cx(r,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"HAND_GESTURES:hand_gestures"),Po(r,"LANDMARKS:hand_landmarks"),Po(r,"WORLD_LANDMARKS:world_hand_landmarks"),Po(r,"HANDEDNESS:handedness"),r.o(t),kg(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n){n=HB(i);const l=[];for(const o of Bb(n,wft,1))l.push({x:Wd(o,1)??0,y:Wd(o,2)??0,z:Wd(o,3)??0,visibility:Wd(o,4)??0});this.landmarks.push(l)}Na(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{Na(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n){n=YA(i);const l=[];for(const o of Bb(n,_ft,1))l.push({x:Wd(o,1)??0,y:Wd(o,2)??0,z:Wd(o,3)??0,visibility:Wd(o,4)??0});this.worldLandmarks.push(l)}Na(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{Na(this,n)}),this.g.attachProtoVectorListener("hand_gestures",(n,a)=>{this.gestures.push(...Mqe(n,!1)),Na(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",n=>{Na(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{this.handedness.push(...Mqe(n)),Na(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function Iqe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}yp.prototype.recognizeForVideo=yp.prototype.Ia,yp.prototype.recognize=yp.prototype.Ha,yp.prototype.setOptions=yp.prototype.o,yp.createFromModelPath=function(s,t){return Yo(yp,s,{baseOptions:{modelAssetPath:t}})},yp.createFromModelBuffer=function(s,t){return Yo(yp,s,{baseOptions:{modelAssetBuffer:t}})},yp.createFromOptions=function(s,t){return Yo(yp,s,t)},yp.HAND_CONNECTIONS=PEe;var vp=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],li(s=this.h=new _Ee,0,1,t=new Od),this.u=new bEe,li(this.h,0,3,this.u),this.j=new Aft,li(this.h,0,2,this.j),zb(this.j,3,1),Ka(this.j,2,.5),Ka(this.u,2,.5),Ka(this.h,4,.5)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return"numHands"in s&&zb(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ka(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ka(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Gy(this,s,t),Iqe(this)}G(s,t,r){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Gv(this,s,r,t),Iqe(this)}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect"),hl(s,"hand_landmarks"),hl(s,"world_hand_landmarks"),hl(s,"handedness");const t=new px;Vv(t,tMs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"LANDMARKS:hand_landmarks"),Po(r,"WORLD_LANDMARKS:world_hand_landmarks"),Po(r,"HANDEDNESS:handedness"),r.o(t),kg(s,r),this.g.attachProtoVectorListener("hand_landmarks",(n,a)=>{for(const i of n)n=HB(i),this.landmarks.push(qxe(n));Na(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",n=>{Na(this,n)}),this.g.attachProtoVectorListener("world_hand_landmarks",(n,a)=>{for(const i of n)n=YA(i),this.worldLandmarks.push(RO(n));Na(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",n=>{Na(this,n)}),this.g.attachProtoVectorListener("handedness",(n,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of n){n=$xe(c);const d=[];for(const h of n.g())d.push({score:Wd(h,2)??0,index:rg(h,1)??0??-1,categoryName:sm(cd(h,3))??""??"",displayName:sm(cd(h,4))??""??""});o.push(d)}l.call(i,...o),Na(this,a)}),this.g.attachEmptyPacketListener("handedness",n=>{Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};vp.prototype.detectForVideo=vp.prototype.G,vp.prototype.detect=vp.prototype.F,vp.prototype.setOptions=vp.prototype.o,vp.createFromModelPath=function(s,t){return Yo(vp,s,{baseOptions:{modelAssetPath:t}})},vp.createFromModelBuffer=function(s,t){return Yo(vp,s,{baseOptions:{modelAssetBuffer:t}})},vp.createFromOptions=function(s,t){return Yo(vp,s,t)},vp.HAND_CONNECTIONS=PEe;var opt=Vy([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 Lqe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function Pqe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{Hxe(s)}}function H$(s,t){s=HB(s),t.push(qxe(s))}var Dc=class extends dx{constructor(s,t){super(new Hy(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,li(s=this.j=new Rft,0,1,t=new Od),this.I=new bEe,li(this.j,0,2,this.I),this.W=new sMs,li(this.j,0,3,this.W),this.u=new Uxe,li(this.j,0,4,this.u),this.O=new Cft,li(this.j,0,5,this.O),this.A=new Pft,li(this.j,0,6,this.A),this.M=new Dft,li(this.j,0,7,this.M),Ka(this.u,2,.5),Ka(this.u,3,.3),Ka(this.O,2,.5),Ka(this.A,2,.5),Ka(this.A,3,.3),Ka(this.M,2,.5),Ka(this.I,2,.5)}get baseOptions(){return el(this.j,Od,1)}set baseOptions(s){li(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Ka(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Ka(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Ka(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Ka(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Ka(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Ka(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Ka(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:r,Lqe(this),Gy(this,s,n),Pqe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.D=typeof r=="function"?r:n,Lqe(this),Gv(this,s,a,t),Pqe(this)}m(){var s=new xx;md(s,"input_frames_image"),hl(s,"pose_landmarks"),hl(s,"pose_world_landmarks"),hl(s,"face_landmarks"),hl(s,"left_hand_landmarks"),hl(s,"left_hand_world_landmarks"),hl(s,"right_hand_landmarks"),hl(s,"right_hand_world_landmarks");const t=new px,r=new nqe;cx(r,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Rl(a,2,Exe(i,0,wF));else{if(!(typeof i=="string"||i instanceof vv||zTe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");dw(a,2,UTe(i,!1),Z3())}}(r,this.j.g());const n=new op;cx(n,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),sEe(n,8,nqe,r),Gc(n,"IMAGE:input_frames_image"),Po(n,"POSE_LANDMARKS:pose_landmarks"),Po(n,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Po(n,"FACE_LANDMARKS:face_landmarks"),Po(n,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Po(n,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Po(n,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Po(n,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),n.o(t),kg(s,n),Vxe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{H$(a,this.h.poseLandmarks),Na(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{Na(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=YA(a),l.push(RO(a)),Na(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{Na(this,a)}),this.outputPoseSegmentationMasks&&(Po(n,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),_I(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[jI(this,a,!0,!this.D)],Na(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],Na(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{H$(a,this.h.faceLandmarks),Na(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{Na(this,a)}),this.outputFaceBlendshapes&&(hl(s,"extra_blendshapes"),Po(n,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=$xe(a),l.push(kEe(a.g()??[]))),Na(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{Na(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{H$(a,this.h.leftHandLandmarks),Na(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{Na(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=YA(a),l.push(RO(a)),Na(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{Na(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{H$(a,this.h.rightHandLandmarks),Na(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{Na(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=YA(a),l.push(RO(a)),Na(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{Na(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Dc.prototype.detectForVideo=Dc.prototype.G,Dc.prototype.detect=Dc.prototype.F,Dc.prototype.setOptions=Dc.prototype.o,Dc.createFromModelPath=function(s,t){return Yo(Dc,s,{baseOptions:{modelAssetPath:t}})},Dc.createFromModelBuffer=function(s,t){return Yo(Dc,s,{baseOptions:{modelAssetBuffer:t}})},Dc.createFromOptions=function(s,t){return Yo(Dc,s,t)},Dc.HAND_CONNECTIONS=PEe,Dc.POSE_CONNECTIONS=opt,Dc.FACE_LANDMARKS_LIPS=TEe,Dc.FACE_LANDMARKS_LEFT_EYE=EEe,Dc.FACE_LANDMARKS_LEFT_EYEBROW=AEe,Dc.FACE_LANDMARKS_LEFT_IRIS=rpt,Dc.FACE_LANDMARKS_RIGHT_EYE=MEe,Dc.FACE_LANDMARKS_RIGHT_EYEBROW=IEe,Dc.FACE_LANDMARKS_RIGHT_IRIS=npt,Dc.FACE_LANDMARKS_FACE_OVAL=LEe,Dc.FACE_LANDMARKS_CONTOURS=apt,Dc.FACE_LANDMARKS_TESSELATION=ipt;var Rx=class extends dx{constructor(s,t){super(new Hy(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},li(s=this.h=new Oft,0,1,t=new Od)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return li(this.h,0,2,kke(s,el(this.h,yEe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},Gy(this,s,t),this.j}ta(s,t,r){return this.j={classifications:[]},Gv(this,s,r,t),this.j}m(){var s=new xx;md(s,"input_image"),md(s,"norm_rect"),hl(s,"classifications");const t=new px;Vv(t,rMs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Gc(r,"IMAGE:input_image"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"CLASSIFICATIONS:classifications"),r.o(t),kg(s,r),this.g.attachProtoListener("classifications",(n,a)=>{this.j=cMs(HAs(n)),Na(this,a)}),this.g.attachEmptyPacketListener("classifications",n=>{Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Rx.prototype.classifyForVideo=Rx.prototype.ta,Rx.prototype.classify=Rx.prototype.sa,Rx.prototype.setOptions=Rx.prototype.o,Rx.createFromModelPath=function(s,t){return Yo(Rx,s,{baseOptions:{modelAssetPath:t}})},Rx.createFromModelBuffer=function(s,t){return Yo(Rx,s,{baseOptions:{modelAssetBuffer:t}})},Rx.createFromOptions=function(s,t){return Yo(Rx,s,t)};var bp=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect",!0),this.h=new Fft,this.embeddings={embeddings:[]},li(s=this.h,0,1,t=new Od)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){var t=this.h,r=el(this.h,mqe,2);return r=r?r.clone():new mqe,s.l2Normalize!==void 0?Rl(r,1,_F(s.l2Normalize)):"l2Normalize"in s&&Rl(r,1),s.quantize!==void 0?Rl(r,2,_F(s.quantize)):"quantize"in s&&Rl(r,2),li(t,0,2,r),this.l(s)}za(s,t){return Gy(this,s,t),this.embeddings}Aa(s,t,r){return Gv(this,s,r,t),this.embeddings}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect"),hl(s,"embeddings_out");const t=new px;Vv(t,nMs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"EMBEDDINGS:embeddings_out"),r.o(t),kg(s,r),this.g.attachProtoListener("embeddings_out",(n,a)=>{n=KAs(n),this.embeddings=function(i){return{embeddings:Bb(i,WAs,1).map(l=>{var d,h;const o={headIndex:rg(l,3)??0??-1,headName:sm(cd(l,4))??""??""};var c=l.v;return Dmt(c,0|c[Ba],hqe,gbe(l,1))!==void 0?(l=f4(l=el(l,hqe,gbe(l,1),void 0),1,Y0,m4()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((h=(d=el(l,GAs,gbe(l,2),void 0))==null?void 0:d.na())==null?void 0:h.h())??c),o}),timestampMs:Hft(cd(i,2,void 0,void 0,Khe)??Amt)}}(n),Na(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",n=>{Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};bp.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=vqe(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=vqe(yqe(s.quantizedEmbedding),yqe(t.quantizedEmbedding))}return s},bp.prototype.embedForVideo=bp.prototype.Aa,bp.prototype.embed=bp.prototype.za,bp.prototype.setOptions=bp.prototype.o,bp.createFromModelPath=function(s,t){return Yo(bp,s,{baseOptions:{modelAssetPath:t}})},bp.createFromModelBuffer=function(s,t){return Yo(bp,s,{baseOptions:{modelAssetBuffer:t}})},bp.createFromOptions=function(s,t){return Yo(bp,s,t)};var Eke=class{constructor(s,t,r){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=r}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(r=>{r.close()}),(t=this.categoryMask)==null||t.close()}};function xMs(s){var r,n;const t=function(a){return Bb(a,op,1)}(s.ca()).filter(a=>(sm(cd(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&&(((n=(r=el(t[0],px,7))==null?void 0:r.j())==null?void 0:n.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=sm(cd(a,1))??""})}function Dqe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function Rqe(s){try{const t=new Eke(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{Hxe(s)}}Eke.prototype.close=Eke.prototype.close;var Zm=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new NEe,this.A=new Bft,li(this.h,0,3,this.A),li(s=this.h,0,1,t=new Od)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Rl(this.h,2,UB(s.displayNamesLocale)):"displayNamesLocale"in s&&Rl(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){xMs(this)}segment(s,t,r){const n=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:r,Dqe(this),Gy(this,s,n),Rqe(this)}La(s,t,r,n){const a=typeof r!="function"?r:{};return this.j=typeof r=="function"?r:n,Dqe(this),Gv(this,s,a,t),Rqe(this)}Da(){return this.u}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect");const t=new px;Vv(t,$ft,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect"),r.o(t),kg(s,r),Vxe(this,s),this.outputConfidenceMasks&&(hl(s,"confidence_masks"),Po(r,"CONFIDENCE_MASKS:confidence_masks"),_I(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>jI(this,i,!0,!this.j)),Na(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],Na(this,n)})),this.outputCategoryMask&&(hl(s,"category_mask"),Po(r,"CATEGORY_MASK:category_mask"),_I(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=jI(this,n,!1,!this.j),Na(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,Na(this,n)})),hl(s,"quality_scores"),Po(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,Na(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Zm.prototype.getLabels=Zm.prototype.Da,Zm.prototype.segmentForVideo=Zm.prototype.La,Zm.prototype.segment=Zm.prototype.segment,Zm.prototype.setOptions=Zm.prototype.o,Zm.createFromModelPath=function(s,t){return Yo(Zm,s,{baseOptions:{modelAssetPath:t}})},Zm.createFromModelBuffer=function(s,t){return Yo(Zm,s,{baseOptions:{modelAssetBuffer:t}})},Zm.createFromOptions=function(s,t){return Yo(Zm,s,t)};var Ake=class{constructor(s,t,r){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=r}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(r=>{r.close()}),(t=this.categoryMask)==null||t.close()}};Ake.prototype.close=Ake.prototype.close;var v0=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new NEe,this.u=new Bft,li(this.h,0,3,this.u),li(s=this.h,0,1,t=new Od)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(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,r,n){const a=typeof r!="function"?r:{};if(this.j=typeof r=="function"?r:n,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,r=this.C+1,n=new Uft,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new _be;dw(i,3,_F(!0),!1),dw(i,1,zD(t.keypoint.x),0),dw(i,2,zD(t.keypoint.y),0),PO(n,1,Nke,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new iMs;for(i of t.scribble)dw(t=new _be,3,_F(!0),!1),dw(t,1,zD(i.x),0),dw(t,2,zD(i.y),0),sEe(o,1,_be,t);PO(n,2,Nke,o)}}this.g.addProtoToStream(n.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",r),Gy(this,s,a);e:{try{const o=new Ake(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{Hxe(this)}l=void 0}return l}m(){var s=new xx;md(s,"image_in"),md(s,"roi_in"),md(s,"norm_rect_in");const t=new px;Vv(t,$ft,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Gc(r,"IMAGE:image_in"),Gc(r,"ROI:roi_in"),Gc(r,"NORM_RECT:norm_rect_in"),r.o(t),kg(s,r),Vxe(this,s),this.outputConfidenceMasks&&(hl(s,"confidence_masks"),Po(r,"CONFIDENCE_MASKS:confidence_masks"),_I(this,"confidence_masks"),this.g.aa("confidence_masks",(n,a)=>{this.confidenceMasks=n.map(i=>jI(this,i,!0,!this.j)),Na(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",n=>{this.confidenceMasks=[],Na(this,n)})),this.outputCategoryMask&&(hl(s,"category_mask"),Po(r,"CATEGORY_MASK:category_mask"),_I(this,"category_mask"),this.g.Z("category_mask",(n,a)=>{this.categoryMask=jI(this,n,!1,!this.j),Na(this,a)}),this.g.attachEmptyPacketListener("category_mask",n=>{this.categoryMask=void 0,Na(this,n)})),hl(s,"quality_scores"),Po(r,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(n,a)=>{this.qualityScores=n,Na(this,a)}),this.g.attachEmptyPacketListener("quality_scores",n=>{this.categoryMask=void 0,Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};v0.prototype.segment=v0.prototype.segment,v0.prototype.setOptions=v0.prototype.o,v0.createFromModelPath=function(s,t){return Yo(v0,s,{baseOptions:{modelAssetPath:t}})},v0.createFromModelBuffer=function(s,t){return Yo(v0,s,{baseOptions:{modelAssetBuffer:t}})},v0.createFromOptions=function(s,t){return Yo(v0,s,t)};var Ox=class extends dx{constructor(s,t){super(new Hy(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},li(s=this.h=new qft,0,1,t=new Od)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Rl(this.h,2,UB(s.displayNamesLocale)):"displayNamesLocale"in s&&Rl(this.h,2),s.maxResults!==void 0?zb(this.h,3,s.maxResults):"maxResults"in s&&Rl(this.h,3),s.scoreThreshold!==void 0?Ka(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Rl(this.h,4),s.categoryAllowlist!==void 0?Zhe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Rl(this.h,5),s.categoryDenylist!==void 0?Zhe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Rl(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},Gy(this,s,t),this.j}G(s,t,r){return this.j={detections:[]},Gv(this,s,r,t),this.j}m(){var s=new xx;md(s,"input_frame_gpu"),md(s,"norm_rect"),hl(s,"detections");const t=new px;Vv(t,oMs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Gc(r,"IMAGE:input_frame_gpu"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"DETECTIONS:detections"),r.o(t),kg(s,r),this.g.attachProtoVectorListener("detections",(n,a)=>{for(const i of n)n=bft(i),this.j.detections.push(Gft(n));Na(this,a)}),this.g.attachEmptyPacketListener("detections",n=>{Na(this,n)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ox.prototype.detectForVideo=Ox.prototype.G,Ox.prototype.detect=Ox.prototype.F,Ox.prototype.setOptions=Ox.prototype.o,Ox.createFromModelPath=async function(s,t){return Yo(Ox,s,{baseOptions:{modelAssetPath:t}})},Ox.createFromModelBuffer=function(s,t){return Yo(Ox,s,{baseOptions:{modelAssetBuffer:t}})},Ox.createFromOptions=function(s,t){return Yo(Ox,s,t)};var Mke=class{constructor(s,t,r){this.landmarks=s,this.worldLandmarks=t,this.segmentationMasks=r}close(){var s;(s=this.segmentationMasks)==null||s.forEach(t=>{t.close()})}};function Oqe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function Fqe(s){try{const t=new Mke(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{Hxe(s)}}Mke.prototype.close=Mke.prototype.close;var _p=class extends dx{constructor(s,t){super(new Hy(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,li(s=this.h=new Vft,0,1,t=new Od),this.A=new Dft,li(this.h,0,3,this.A),this.j=new Pft,li(this.h,0,2,this.j),zb(this.j,4,1),Ka(this.j,2,.5),Ka(this.A,2,.5),Ka(this.h,4,.5)}get baseOptions(){return el(this.h,Od,1)}set baseOptions(s){li(this.h,0,1,s)}o(s){return"numPoses"in s&&zb(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Ka(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Ka(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Ka(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,r){const n=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:r,Oqe(this),Gy(this,s,n),Fqe(this)}G(s,t,r,n){const a=typeof r!="function"?r:{};return this.u=typeof r=="function"?r:n,Oqe(this),Gv(this,s,a,t),Fqe(this)}m(){var s=new xx;md(s,"image_in"),md(s,"norm_rect"),hl(s,"normalized_landmarks"),hl(s,"world_landmarks"),hl(s,"segmentation_masks");const t=new px;Vv(t,lMs,this.h);const r=new op;cx(r,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Gc(r,"IMAGE:image_in"),Gc(r,"NORM_RECT:norm_rect"),Po(r,"NORM_LANDMARKS:normalized_landmarks"),Po(r,"WORLD_LANDMARKS:world_landmarks"),r.o(t),kg(s,r),Vxe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(n,a)=>{this.landmarks=[];for(const i of n)n=HB(i),this.landmarks.push(qxe(n));Na(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",n=>{this.landmarks=[],Na(this,n)}),this.g.attachProtoVectorListener("world_landmarks",(n,a)=>{this.worldLandmarks=[];for(const i of n)n=YA(i),this.worldLandmarks.push(RO(n));Na(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",n=>{this.worldLandmarks=[],Na(this,n)}),this.outputSegmentationMasks&&(Po(r,"SEGMENTATION_MASK:segmentation_masks"),_I(this,"segmentation_masks"),this.g.aa("segmentation_masks",(n,a)=>{this.segmentationMasks=n.map(i=>jI(this,i,!0,!this.u)),Na(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",n=>{this.segmentationMasks=[],Na(this,n)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};_p.prototype.detectForVideo=_p.prototype.G,_p.prototype.detect=_p.prototype.F,_p.prototype.setOptions=_p.prototype.o,_p.createFromModelPath=function(s,t){return Yo(_p,s,{baseOptions:{modelAssetPath:t}})},_p.createFromModelBuffer=function(s,t){return Yo(_p,s,{baseOptions:{modelAssetBuffer:t}})},_p.createFromOptions=function(s,t){return Yo(_p,s,t)},_p.POSE_CONNECTIONS=opt;let p4=null,$D=null;async function gMs(){return p4||$D||($D=(async()=>{const s=await SE.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return p4=await Zm.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}),p4})(),$D)}function yMs(s,t,r,n,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+h]);const x=Math.min(m,r-1)-Math.max(h+1,0)+1;i[c+d]=o/x}}for(let l=0;l=0&&(o-=i[d*r+l]);const m=Math.min(h,n-1)-Math.max(d+1,0)+1;t[c*r+l]=o/m}}}function vMs(){p4&&(p4.close(),p4=null,$D=null)}function bMs(s,t){const r=k.useRef(null),n=k.useRef(null),a=k.useRef(null),i=k.useRef(null),l=k.useRef(0),o=k.useRef(0),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,y]=k.useState(null),v=t.type!=="none"&&s!==null;return k.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const w=new Image;w.crossOrigin="anonymous",w.src=t.imageUrl,w.onload=()=>{i.current=w}}else i.current=null},[t.type,t.imageUrl]),k.useEffect(()=>{if(!v||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const w=document.createElement("video");return w.srcObject=s,w.muted=!0,w.playsInline=!0,w.autoplay=!0,w.play().catch(()=>{}),a.current=w,()=>{w.srcObject=null,a.current=null}},[v,s]),k.useEffect(()=>{if(!v){d(null),y(null);return}let w=!1;return(async()=>{m(!0),y(null);try{const N=await gMs();if(w)return;m(!1);const S=a.current;if(!S||(await new Promise(ve=>{if(S.videoWidth>0)return ve();S.onloadedmetadata=()=>ve(),setTimeout(ve,2e3)}),w))return;const T=S.videoWidth||640,A=S.videoHeight||480,I=r.current;if(!I)return;I.width=T,I.height=A;const D=I.getContext("2d",{willReadFrequently:!1});n.current||(n.current=document.createElement("canvas"));const R=n.current;R.width=T,R.height=A;const $=R.getContext("2d",{willReadFrequently:!0}),F=document.createElement("canvas");F.width=T,F.height=A;const z=F.getContext("2d"),Q=I.captureStream(30);((s==null?void 0:s.getAudioTracks())||[]).forEach(ve=>Q.addTrack(ve)),w||d(Q);const X=t.blurRadius??15,Z=t.mirror??!1,re=new Float32Array(T*A),le=new Float32Array(T*A),oe=new Float32Array(T*A);let ne=!1;const ie=4,ye=.6,ce=()=>{if(w||!a.current)return;const ve=performance.now();if(ve-o.current<30){l.current=requestAnimationFrame(ce);return}o.current=ve;const be=a.current;if(be.readyState<2){l.current=requestAnimationFrame(ce);return}try{const Be=N.segmentForVideo(be,ve).confidenceMasks;if(Be&&Be.length>0){le.fill(0);for(let He=1;HeIe?(et=He.height*Ie,Te=(He.width-et)/2):(fe=He.width/Ie,xe=(He.height-fe)/2),D.drawImage(He,Te,xe,et,fe,0,0,T,A)}$.clearRect(0,0,T,A),$.drawImage(be,0,0,T,A);const De=$.getImageData(0,0,T,A),Ae=De.data;for(let He=0;He{w=!0,l.current&&cancelAnimationFrame(l.current),d(null)}},[v,t.type,t.blurRadius,t.imageUrl,s]),k.useEffect(()=>()=>{vMs()},[]),{canvasRef:r,compositedStream:c,isLoading:h,isActive:v,error:x}}function IL({maxDurationSeconds:s=600,onRecordingComplete:t,onError:r,onRecordingStateChange:n,className:a,teleprompterContent:i}){const l=k.useRef(null),o=k.useRef(null),c=k.useRef(null),[d,h]=k.useState(null),m=k.useRef([]),x=k.useRef(null),y=k.useRef(null),v=k.useRef(null),w=k.useRef(null),b=gL(),[N,S]=k.useState("camera"),T=k.useRef(null),A=k.useRef(null),I=k.useRef(null),D=k.useRef(null),R=k.useRef(null),$=k.useRef(null),[F,z]=k.useState(!0),[Q,K]=k.useState(!0),[X,Z]=k.useState(null),[re,le]=k.useState(!1),[oe,ne]=k.useState(!1),[ie,ye]=k.useState(null),[ce,ve]=k.useState(null),[be,Ue]=k.useState(0),[Be,De]=k.useState("user"),[Ae,He]=k.useState(0),[Le,Ie]=k.useState(!1),[Te,xe]=k.useState(!0),[et,fe]=k.useState(null),[it,Oe]=k.useState(!1),[Ye,We]=k.useState(null),_e=k.useRef(null),[Re,tt]=k.useState(()=>{try{const hr=localStorage.getItem("video-bg-config");if(hr)return JSON.parse(hr)}catch{}return{type:"none"}});k.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Re))}catch{}},[Re]);const[Ke,Ze]=k.useState([]),[lt,xt]=k.useState([]),[Xe,Je]=k.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[jt,ns]=k.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});k.useEffect(()=>{try{localStorage.setItem("video-mic-id",Xe)}catch{}},[Xe]),k.useEffect(()=>{try{localStorage.setItem("video-cam-id",jt)}catch{}},[jt]),k.useEffect(()=>{var Pr,Qn,Gt;if(!((Pr=navigator.mediaDevices)!=null&&Pr.enumerateDevices))return;const hr=async()=>{try{const gr=await navigator.mediaDevices.enumerateDevices();Ze(gr.filter(zt=>zt.kind==="audioinput")),xt(gr.filter(zt=>zt.kind==="videoinput"))}catch(gr){console.warn("[VideoRecorder] enumerateDevices failed",gr)}};return hr(),(Gt=(Qn=navigator.mediaDevices).addEventListener)==null||Gt.call(Qn,"devicechange",hr),()=>{var gr,zt;return(zt=(gr=navigator.mediaDevices).removeEventListener)==null?void 0:zt.call(gr,"devicechange",hr)}},[X]);const{canvasRef:Ns,compositedStream:Ys,isLoading:rs,isActive:bt,error:cs}=bMs(d,Re),yt=k.useRef(r);yt.current=r;const is=k.useCallback(hr=>{z(hr)},[]),Bs=k.useRef(F),ps=k.useCallback(()=>{I.current&&(cancelAnimationFrame(I.current),I.current=null),D.current&&(D.current.terminate(),D.current=null),T.current&&(T.current.getTracks().forEach(hr=>hr.stop()),T.current=null),R.current&&(R.current.getTracks().forEach(hr=>hr.stop()),R.current=null),$.current&&($.current.srcObject=null,$.current=null)},[]),lr=k.useCallback(async()=>{var hr;try{const Pr=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});T.current=Pr;let Qn=null;try{Qn=await navigator.mediaDevices.getUserMedia({video:jt?{deviceId:{exact:jt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Gt=null;try{Gt=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...Xe?{deviceId:{exact:Xe}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Gt.getAudioTracks().map(Rr=>Rr.label))}catch(Rr){console.warn("[VideoRecorder] No mic audio for screen recording",Rr);try{Gt=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const gr=Pr.getVideoTracks()[0],zt=gr.getSettings(),Se=zt.width||1920,ze=zt.height||1080,st=document.createElement("canvas");st.width=Se,st.height=ze,A.current=st;const gt=st.getContext("2d");let At=null;Qn&&(At=document.createElement("video"),At.srcObject=Qn,At.muted=!0,At.playsInline=!0,At.autoplay=!0,await At.play(),$.current=At);const Ft=document.createElement("video");Ft.srcObject=Pr,Ft.muted=!0,Ft.playsInline=!0,Ft.autoplay=!0,await Ft.play();const Wt=()=>{if(gt.drawImage(Ft,0,0,Se,ze),At&&At.readyState>=2){const Rr=Math.round(Se*.2),sn=Math.round(Rr*(At.videoHeight/At.videoWidth||.75)),rn=Se-Rr-20,un=ze-sn-20,fa=12;gt.save(),gt.beginPath(),gt.moveTo(rn+fa,un),gt.lineTo(rn+Rr-fa,un),gt.quadraticCurveTo(rn+Rr,un,rn+Rr,un+fa),gt.lineTo(rn+Rr,un+sn-fa),gt.quadraticCurveTo(rn+Rr,un+sn,rn+Rr-fa,un+sn),gt.lineTo(rn+fa,un+sn),gt.quadraticCurveTo(rn,un+sn,rn,un+sn-fa),gt.lineTo(rn,un+fa),gt.quadraticCurveTo(rn,un,rn+fa,un),gt.closePath(),gt.clip(),gt.translate(rn+Rr,un),gt.scale(-1,1),gt.drawImage(At,0,0,Rr,sn),gt.restore(),gt.strokeStyle="rgba(255,255,255,0.6)",gt.lineWidth=2,gt.beginPath(),gt.moveTo(rn+fa,un),gt.lineTo(rn+Rr-fa,un),gt.quadraticCurveTo(rn+Rr,un,rn+Rr,un+fa),gt.lineTo(rn+Rr,un+sn-fa),gt.quadraticCurveTo(rn+Rr,un+sn,rn+Rr-fa,un+sn),gt.lineTo(rn+fa,un+sn),gt.quadraticCurveTo(rn,un+sn,rn,un+sn-fa),gt.lineTo(rn,un+fa),gt.quadraticCurveTo(rn,un,rn+fa,un),gt.closePath(),gt.stroke()}},Vt="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}}",Jt=new Blob([Vt],{type:"application/javascript"}),qs=new Worker(URL.createObjectURL(Jt));D.current=qs,qs.onmessage=()=>Wt(),qs.postMessage({type:"start",fps:30}),Wt();const Cs=st.captureStream(30),xr=[],Wr=Pr.getAudioTracks();Wr.length&&xr.push(...Wr),Gt&&xr.push(...Gt.getAudioTracks());const tn=new MediaStream([...Cs.getVideoTracks(),...xr]);return R.current=tn,gr.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),ps()},tn}catch(Pr){return console.error("[VideoRecorder] Screen capture error:",Pr),Pr.name!=="NotAllowedError"&&((hr=yt.current)==null||hr.call(yt,"Failed to start screen capture: "+(Pr.message||"Unknown error"))),null}},[ps]),kr=k.useCallback(async()=>{var Pr,Qn;K(!0),fe(null);const hr=b&&F;console.log("[VideoRecorder] initCamera start",{isMobile:b,usePortraitMode:F,shouldBePortrait:hr,facingMode:Be});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(gt=>gt.stop()));const Gt=b&&hr?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},gr=jt?{...Gt,deviceId:{exact:jt}}:{...Gt,facingMode:{ideal:Be}},zt={echoCancellation:!0,noiseSuppression:!0,...Xe?{deviceId:{exact:Xe}}:{}};console.log("[VideoRecorder] requesting getUserMedia",gr);const Se=await navigator.mediaDevices.getUserMedia({video:gr,audio:zt});if(console.log("[VideoRecorder] getUserMedia success"),Se.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Se,h(Se),Z(!0);const st=Se.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",st.width,"x",st.height),l.current){const gt=l.current;gt.srcObject=Se,gt.muted=!0,gt.playsInline=!0,gt.autoplay=!0,gt.setAttribute("muted",""),gt.setAttribute("playsinline",""),gt.setAttribute("autoplay","");try{(Pr=gt.load)==null||Pr.call(gt)}catch(Ft){console.warn("[VideoRecorder] videoEl.load failed",Ft)}const At=async()=>{try{return await gt.play(),console.log("[VideoRecorder] preview play ok"),Oe(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:gt.readyState,videoWidth:gt.videoWidth,videoHeight:gt.videoHeight})},300),!0}catch(Ft){return console.warn("[VideoRecorder] preview play blocked",Ft),Oe(!0),!1}};await new Promise(Ft=>{let Wt=!1;const Vt=()=>{Wt||(Wt=!0,Ft())},Jt=()=>{At().finally(Vt)};gt.onloadedmetadata=Jt,gt.onloadeddata=Jt,setTimeout(Vt,1500)})}try{y.current=new AudioContext;const gt=y.current.createMediaStreamSource(Se);v.current=y.current.createAnalyser(),v.current.fftSize=256,gt.connect(v.current);const At=()=>{if(v.current){const Ft=new Uint8Array(v.current.frequencyBinCount);v.current.getByteFrequencyData(Ft);const Wt=Ft.reduce((Vt,Jt)=>Vt+Jt)/Ft.length;He(Math.min(100,Wt/128*100))}w.current=requestAnimationFrame(At)};At()}catch(gt){console.warn("Audio context not available:",gt)}}catch(Gt){console.error("Camera initialization error:",Gt),Z(!1);let gr="Failed to access camera or microphone.";Gt.name==="NotAllowedError"?gr="Camera permission denied. Please allow camera access in your browser settings.":Gt.name==="NotFoundError"?gr="No camera found. Please connect a camera and try again.":Gt.name==="NotReadableError"?gr="Camera is in use by another application. Please close other apps using the camera.":Gt.message&&(gr=Gt.message),fe(gr),(Qn=yt.current)==null||Qn.call(yt,gr)}finally{K(!1)}},[Be,b,F,Xe,jt]);k.useEffect(()=>{Bs.current!==F&&X&&!re&&!ce&&(Bs.current=F,kr())},[F,X,re,ce,kr]),k.useEffect(()=>(kr(),()=>{c.current&&c.current.getTracks().forEach(hr=>hr.stop()),x.current&&clearInterval(x.current),w.current&&cancelAnimationFrame(w.current),y.current&&y.current.close(),_e.current&&clearInterval(_e.current),ce&&URL.revokeObjectURL(ce),ps()}),[kr,ce]),k.useEffect(()=>{if(Q||X!==!0||ce)return;const hr=c.current,Pr=l.current;!hr||!Pr||bt||(Pr.srcObject!==hr&&(Pr.srcObject=hr,Pr.muted=!0,Pr.playsInline=!0,Pr.autoplay=!0,Pr.setAttribute("muted",""),Pr.setAttribute("playsinline",""),Pr.setAttribute("autoplay","")),Pr.play().then(()=>Oe(!1)).catch(Qn=>{Oe(!0),console.warn("Live preview play blocked on mount:",Qn)}))},[X,Q,ce,bt]),k.useEffect(()=>{n==null||n(re)},[re,n]);const Lr=k.useCallback(async()=>{if(ce)return;const hr=l.current;if(hr)try{await hr.play(),Oe(!1)}catch(Pr){Oe(!0),console.warn("Live preview still blocked (needs user gesture):",Pr)}},[ce]),qr=k.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),x.current&&(clearInterval(x.current),x.current=null),ps(),le(!1),ne(!1)},[ps]),Ur=k.useCallback(async()=>{let hr=null;if(N==="screen"){if(hr=await lr(),!hr)return}else hr=bt&&Ys?Ys:c.current;if(!hr)return;Lr(),m.current=[],Ue(0);const Qn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(gr=>MediaRecorder.isTypeSupported(gr)),Gt=new MediaRecorder(hr,Qn?{mimeType:Qn,videoBitsPerSecond:N==="screen"?4e6:25e5}:{videoBitsPerSecond:N==="screen"?4e6:25e5});Gt.ondataavailable=gr=>{gr.data.size>0&&m.current.push(gr.data)},Gt.onstop=()=>{var ze;const gr=Gt.mimeType||Qn||((ze=m.current[0])==null?void 0:ze.type)||"video/webm",zt=new Blob(m.current,{type:gr});ye(zt);const Se=URL.createObjectURL(zt);ve(Se)},o.current=Gt,Gt.start(100),le(!0),x.current=setInterval(()=>{Ue(gr=>gr>=s-1?(qr(),s):gr+1)},1e3)},[Lr,s,qr,bt,Ys,N,lr]),Mr=k.useCallback(()=>{_e.current&&(clearInterval(_e.current),_e.current=null),We(3);let hr=3;_e.current=setInterval(()=>{hr-=1,hr<=0?(_e.current&&clearInterval(_e.current),_e.current=null,We(null),Ur()):We(hr)},1e3)},[Ur]),Cr=k.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),ne(!0),x.current&&clearInterval(x.current))},[]),Xr=k.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),ne(!1),x.current=setInterval(()=>{Ue(hr=>hr>=s-1?(qr(),s):hr+1)},1e3))},[s,qr]),Ln=k.useCallback(()=>{ce&&URL.revokeObjectURL(ce),ye(null),ve(null),Ue(0),Ie(!1),xe(!0),l.current&&c.current&&!bt&&(l.current.srcObject=c.current,l.current.muted=!0,Lr())},[Lr,ce,bt]),Zs=k.useCallback(()=>{De(hr=>hr==="user"?"environment":"user")},[]),Yr=k.useCallback(()=>{ie&&t(ie,be)},[ie,be,t]),ss=k.useCallback(()=>{l.current&&ce&&(Le?l.current.pause():(xe(!1),l.current.muted=!1,l.current.play()),Ie(!Le))},[ce,Le]);k.useEffect(()=>{if(!ce)return;const hr=l.current;if(!hr)return;xe(!1),hr.pause(),hr.removeAttribute("src"),hr.srcObject=null,hr.load(),hr.src=ce,hr.currentTime=0,hr.playsInline=!0,hr.muted=!1,hr.onended=()=>Ie(!1);const Pr=()=>{var gr;const Qn=hr.error,Gt=Qn?`Recorded video failed to play (code ${Qn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Qn),(gr=yt.current)==null||gr.call(yt,Gt)};return hr.addEventListener("error",Pr),hr.load(),()=>{hr.removeEventListener("error",Pr)}},[ce]);const ta=hr=>{const Pr=Math.floor(hr/60),Qn=hr%60;return`${Pr}:${Qn.toString().padStart(2,"0")}`},nn=N==="screen"?"aspect-video":b&&F?"aspect-[9/16]":"aspect-video";return Q?e.jsx("div",{className:It("flex items-center justify-center bg-black rounded-lg",nn,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(es,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):X===!1?e.jsx("div",{className:It("flex items-center justify-center bg-black rounded-lg",nn,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Oi,{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:et||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(G,{onClick:()=>kr(),variant:"secondary",className:"w-full",children:[e.jsx(Mi,{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:It("flex flex-col gap-2",a),children:[!re&&!ce&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(G,{variant:N==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>S("camera"),children:[e.jsx(Qf,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(G,{variant:N==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>S("screen"),children:[e.jsx(K4,{className:"h-4 w-4"}),"Screen"]})]}),N==="camera"&&!re&&!ce&&e.jsx(LEs,{value:Re,onChange:tt,isLoading:rs,disabled:re}),!re&&!ce&&(Ke.length>0||lt.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[Ke.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(W4,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Is,{value:Xe||"default",onValueChange:hr=>Je(hr==="default"?"":hr),children:[e.jsx(As,{className:"h-8 text-xs",children:e.jsx(Ls,{placeholder:"Default microphone"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"default",children:"Default microphone"}),Ke.map(hr=>e.jsx(ct,{value:hr.deviceId,children:hr.label||`Microphone ${hr.deviceId.slice(0,6)}`},hr.deviceId))]})]})]}),lt.length>1&&N==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Qf,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(Is,{value:jt||"default",onValueChange:hr=>ns(hr==="default"?"":hr),children:[e.jsx(As,{className:"h-8 text-xs",children:e.jsx(Ls,{placeholder:"Default camera"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"default",children:"Default camera"}),lt.map(hr=>e.jsx(ct,{value:hr.deviceId,children:hr.label||`Camera ${hr.deviceId.slice(0,6)}`},hr.deviceId))]})]})]})]}),N==="camera"&&b&&!re&&!ce&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(rj,{className:It("h-4 w-4",F?"text-muted-foreground":"text-primary")}),e.jsx(he,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(_r,{id:"orientation-toggle",checked:F,onCheckedChange:is}),e.jsx(he,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(ig,{className:It("h-4 w-4",F?"text-primary":"text-muted-foreground")})]}),N==="screen"&&!re&&!ce&&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(K4,{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:It("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Lr()},children:[e.jsx("video",{ref:l,src:ce??void 0,className:It("w-full bg-black",F&&!ce?"object-contain":"object-cover",nn,!ce&&Be==="user"!==(Re.mirror??!1)&&"scale-x-[-1]",bt&&!ce&&"hidden"),playsInline:!0,controls:!!ce,muted:ce?Te:!0,autoPlay:!ce},ce??"live"),bt&&!ce&&e.jsx("canvas",{ref:Ns,className:It("w-full bg-black",F?"object-contain":"object-cover",nn,Be==="user"!==(Re.mirror??!1)&&"scale-x-[-1]")}),bt&&rs&&!ce&&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(es,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!ce&&it&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(G,{type:"button",variant:"secondary",onClick:()=>void Lr(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!ce&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Ye!==null&&!ce&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:Ye},Ye),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),re&&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:It("w-3 h-3 rounded-full",oe?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[ta(be)," / ",ta(s)]})]}),re&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(ei,{value:be/s*100,className:"h-1 rounded-none"})}),!ce&&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(W4,{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:ce?e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Ln,children:[e.jsx(Mi,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(G,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ss,children:Le?e.jsx(tm,{className:"h-5 w-5"}):e.jsx(Uo,{className:"h-5 w-5"})}),e.jsxs(G,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Yr,children:[e.jsx(Kn,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[N==="camera"?e.jsx(G,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Zs,disabled:re||Ye!==null,children:e.jsx(cv,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!re&&Ye===null?e.jsx(G,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:N==="screen"?Ur:Mr,children:N==="screen"?e.jsx(K4,{className:"h-6 w-6"}):e.jsx(Jr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:oe?Xr:Cr,children:oe?e.jsx(Uo,{className:"h-5 w-5"}):e.jsx(tm,{className:"h-5 w-5"})}),e.jsx(G,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:qr,children:e.jsx(og,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}const lpt="teleprompter_settings",jbe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function _Ms(){try{const s=localStorage.getItem(lpt);return s?{...jbe,...JSON.parse(s)}:jbe}catch{return jbe}}function wMs(s){try{localStorage.setItem(lpt,JSON.stringify(s))}catch{}}function DEe({text:s,isVisible:t,onToggleVisibility:r,isRecording:n=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=k.useRef(null),c=k.useRef(null),d=k.useRef(0),h=k.useRef(0),[m,x]=k.useState(_Ms),{scrollSpeed:y,fontSize:v,lineHeight:w,opacity:b,position:N,isMirrored:S}=m,T=k.useCallback((K,X)=>{x(Z=>{const re={...Z,[K]:X};return wMs(re),re})},[]),[A,I]=k.useState(!1),[D,R]=k.useState(null),$=k.useCallback(K=>{if(!o.current)return;d.current===0&&(d.current=K);const X=K-d.current;d.current=K,h.current+=y*X/1e3;const Z=Math.floor(h.current);Z>0&&(o.current.scrollTop+=Z,h.current-=Z);const{scrollTop:re,scrollHeight:le,clientHeight:oe}=o.current;if(re+oe>=le){I(!1);return}c.current=requestAnimationFrame($)},[y]);k.useEffect(()=>(A?(d.current=0,h.current=0,c.current=requestAnimationFrame($)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,$]),k.useEffect(()=>{if(n&&t)if(o.current&&(o.current.scrollTop=0),a){R(3);let K=3;const X=setInterval(()=>{K-=1,K<=0?(clearInterval(X),R(null),i==null||i(),I(!0)):R(K)},1e3);return()=>clearInterval(X)}else setTimeout(()=>I(!0),100);else n||(I(!1),R(null))},[n,t,a,i]);const F=k.useCallback(()=>{o.current&&(o.current.scrollTop=0),I(!1)},[]),z=k.useCallback(()=>{I(K=>!K)},[]);if(!t)return e.jsx("div",{className:It("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(G,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const Q={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:It("absolute inset-0 pointer-events-none",l),children:[D!==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:D},D),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:It("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",Q[N],D!==null&&"opacity-30"),style:{opacity:D!==null?.3:b},children:e.jsxs("div",{ref:o,className:It("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",S&&"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:`${v}px`,lineHeight:w,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(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsx(G,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(oo,{className:"h-4 w-4"})})}),e.jsx(_o,{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(he,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y})]}),e.jsx(_y,{value:[y],onValueChange:([K])=>T("scrollSpeed",K),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(he,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v,"px"]})]}),e.jsx(_y,{value:[v],onValueChange:([K])=>T("fontSize",K),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(he,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:w.toFixed(1)})]}),e.jsx(_y,{value:[w*10],onValueChange:([K])=>T("lineHeight",K/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(he,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(b*100),"%"]})]}),e.jsx(_y,{value:[b*100],onValueChange:([K])=>T("opacity",K/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:N==="top"?"default":"outline",size:"sm",onClick:()=>T("position","top"),children:e.jsx(Jf,{className:"h-4 w-4"})}),e.jsx(G,{variant:N==="center"?"default":"outline",size:"sm",onClick:()=>T("position","center"),children:e.jsx(av,{className:"h-4 w-4"})}),e.jsx(G,{variant:N==="bottom"?"default":"outline",size:"sm",onClick:()=>T("position","bottom"),children:e.jsx(Wi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{className:"text-xs",children:"Mirror Mode"}),e.jsx(_r,{checked:S,onCheckedChange:K=>T("isMirrored",K)})]})]})})]}),e.jsx(G,{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(tm,{className:"h-4 w-4"}):e.jsx(Uo,{className:"h-4 w-4"})}),e.jsx(G,{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(cv,{className:"h-4 w-4"})}),e.jsxs(G,{variant:"secondary",size:"sm",onClick:r,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Xh,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function jMs({onSelectScript:s,onCreateNew:t,selectedScriptId:r,className:n}){const{toast:a}=Ma(),[i,l]=k.useState(""),[o,c]=k.useState(null),[d,h]=k.useState("levelup"),{data:m,isLoading:x}=w5s(),{data:y,isLoading:v}=j5s(),{data:w,isLoading:b}=N5s(),N=k5s(),S=k.useMemo(()=>y?y.filter(R=>{const $=!i||R.title.toLowerCase().includes(i.toLowerCase())||R.script_text.toLowerCase().includes(i.toLowerCase())||R.tags.some(z=>z.toLowerCase().includes(i.toLowerCase())),F=!o||R.category_id===o;return $&&F}):[],[y,i,o]),T=k.useMemo(()=>w?w.filter(R=>!i||R.title.toLowerCase().includes(i.toLowerCase())||R.script_text.toLowerCase().includes(i.toLowerCase())):[],[w,i]),A=R=>{s({title:R.title,text:R.script_text})},I=async R=>{try{await N.mutateAsync(R),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},D=x||v||b;return e.jsxs("div",{className:It("flex flex-col h-full",n),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search scripts...",value:i,onChange:R=>l(R.target.value),className:"pl-9"})]})}),e.jsxs(On,{value:d,onValueChange:R=>h(R),className:"flex-1 flex flex-col",children:[e.jsxs(Rn,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Kt,{value:"levelup",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Kt,{value:"my-scripts",children:[e.jsx(ag,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(ts,{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(Ge,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),m==null?void 0:m.map(R=>e.jsx(Ge,{variant:o===R.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(R.id),children:R.name},R.id))]}),e.jsx(Qa,{className:"flex-1 max-h-[50vh]",children:D?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(es,{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(ln,{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:S.map(R=>e.jsxs(ke,{className:It("cursor-pointer hover:bg-accent/50 transition-colors",r===R.id&&"ring-2 ring-primary"),onClick:()=>A(R),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(Dt,{className:"text-sm font-medium truncate",children:R.title}),R.category&&e.jsx(Ge,{variant:"secondary",className:"mt-1 text-xs",children:R.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:$=>{$.stopPropagation(),I(R)},children:e.jsx(ag,{className:"h-4 w-4"})}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Pe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:R.script_text})})]},R.id))})})]}),e.jsxs(ts,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(G,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Qa,{className:"flex-1 max-h-[50vh]",children:b?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):T.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ag,{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:T.map(R=>e.jsxs(ke,{className:It("cursor-pointer hover:bg-accent/50 transition-colors",r===R.id&&"ring-2 ring-primary"),onClick:()=>A(R),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(Dt,{className:"text-sm font-medium truncate",children:R.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:R.is_custom?e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Pe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:R.script_text})})]},R.id))})})]})]})]})}function NMs({selectedTemplate:s,onSelect:t,contactName:r,saving:n=!1}){const[a,i]=k.useState(()=>{const o=RA(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(he,{className:"text-sm font-medium",children:"Share Page Template"}),n&&e.jsx(es,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:I9t.map(o=>{const c=L9t(o.id),d=a.has(o.id),h=c.some(m=>m.id===s);return e.jsxs(Gp,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(Wp,{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,")"]}),h&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(Wi,{className:It("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(Kp,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(m=>{const x=s===m.id;return e.jsxs("button",{type:"button",onClick:()=>t(m.id),disabled:n,className:It("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",x?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[x&&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(Kn,{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:m.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:m.name})]})]},m.id)})})})]},o.id)})}),r&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',RA(s).headerText(r),'"']})]})}function cpt({open:s,onOpenChange:t,video:r,contactName:n,onTemplateUpdated:a}){const[i,l]=k.useState(r.page_template||"default"),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState(r.page_template||"default"),[y,v]=k.useState([]),[w,b]=k.useState(r.contact_id&&n?{id:r.contact_id,name:n,email:null}:null),[N,S]=k.useState(!1),[T,A]=k.useState(!1),I=r.share_token?`https://video.relevelup.com/${r.share_token}`:"";k.useEffect(()=>{s&&y.length===0&&D()},[s]);const D=async()=>{A(!0);try{const{data:re,error:le}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(le)throw le;const oe=(re||[]).map(ne=>({id:ne.id,name:[ne.first_name,ne.last_name].filter(Boolean).join(" ")||"Unnamed",email:ne.email||null}));v(oe)}catch(re){console.error("Failed to fetch contacts:",re)}finally{A(!1)}},R=async re=>{b(re),S(!1),c(!0);try{const{error:le}=await V.from("agent_videos").update({contact_id:(re==null?void 0:re.id)||null,recipient_name:(re==null?void 0:re.name)||null}).eq("id",r.id);if(le)throw le;ue.success(re?`Assigned to ${re.name}`:"Contact removed"),a==null||a()}catch(le){console.error("Failed to update contact:",le),ue.error("Failed to update contact")}finally{c(!1)}},$=async re=>{l(re),c(!0);try{const{error:le}=await V.from("agent_videos").update({page_template:re}).eq("id",r.id);if(le)throw le;x(re),ue.success("Template saved!"),a==null||a()}catch(le){console.error("Failed to save template:",le),ue.error("Failed to save template"),l(m)}finally{c(!1)}},F=(w==null?void 0:w.name)||null,z=()=>{const re=r.title||"Video Message",le=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:r.thumbnail_url||"";return``},Q=async()=>{if(!r.thumbnail_url){ue.error("Video thumbnail not available yet");return}const re=z(),le=`Watch: ${r.title||"Video Message"} ${I}`;try{const oe=new Blob([re],{type:"text/html"}),ne=new Blob([le],{type:"text/plain"}),ie=new ClipboardItem({"text/html":oe,"text/plain":ne});await navigator.clipboard.write([ie]),ue.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(le+` `+re),ue.success("Copied! Paste into your email.")}},K=async()=>{await navigator.clipboard.writeText(I),h(!0),ue.success("Share link copied!"),setTimeout(()=>h(!1),2e3)},X=()=>{const le=RA(i).headerText(F),oe=i==="default"?`Check out this video: ${I}`:`${le} Check out this special video: ${I}`;window.open(`sms:?body=${encodeURIComponent(oe)}`,"_self")},Z=()=>{const re=RA(i),le=re.headerText(F),oe=i==="default"?r.title||"Video Message":le,ne=`${re.subText} Watch the video: ${I}`,ie=w!=null&&w.email?encodeURIComponent(w.email):"";window.open(`mailto:${ie}?subject=${encodeURIComponent(oe)}&body=${encodeURIComponent(ne)}`,"_self")};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(po,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Hr,{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(he,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(To,{open:N,onOpenChange:S,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":N,className:"flex-1 justify-between",disabled:o,children:[w?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"}),w.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[300px] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search contacts..."}),e.jsxs(ax,{children:[e.jsx(ix,{children:T?"Loading...":"No contacts found."}),e.jsx(ox,{children:y.map(re=>e.jsxs(cf,{value:re.name,onSelect:()=>R(re),children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",(w==null?void 0:w.id)===re.id?"opacity-100":"opacity-0")}),re.name]},re.id))})]})]})})]}),w&&e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>R(null),disabled:o,className:"shrink-0",children:e.jsx(vr,{className:"h-4 w-4"})})]}),w&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',RA(i).headerText(w.name),'"']})]}),e.jsx(NMs,{selectedTemplate:i,onSelect:$,contactName:F,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:I,readOnly:!0,className:"font-mono text-sm"}),e.jsx(G,{onClick:K,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Kn,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ra,{className:"h-4 w-4"}),"Copy"]})})]})]}),r.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Share for Email"}),e.jsxs(G,{variant:"outline",className:"w-full gap-2",onClick:Q,children:[e.jsx(ml,{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(he,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",className:"flex-1 gap-2",onClick:X,children:[e.jsx(xi,{className:"h-4 w-4"}),"Text"]}),e.jsxs(G,{variant:"outline",className:"flex-1 gap-2",onClick:Z,children:[e.jsx(Vs,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(an,{children:e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function kMs(){var We;const s=br(),[t]=Ac(),{toast:r}=Ma(),n=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=Dht(),{data:h}=Sm(),m=Yb(),x=A5s(),[y,v]=k.useState("record"),[w,b]=k.useState(""),[N,S]=k.useState(!1),[T,A]=k.useState(!1),[I,D]=k.useState(!1),[R,$]=k.useState(null),[F,z]=k.useState(0),[Q,K]=k.useState(0),[X,Z]=k.useState(null),[re,le]=k.useState(null),[oe,ne]=k.useState(n||""),[ie,ye]=k.useState(""),[ce,ve]=k.useState(""),[be,Ue]=k.useState(null),[Be,De]=k.useState(null),[Ae,He]=k.useState(null),[Le,Ie]=k.useState(!1),Te=k.useCallback(async(_e,Re)=>{$(_e),v("uploading");try{const{videoId:tt,uploadUrl:Ke}=await h5(ie||"Quick Video Touch");Z(tt);const{apiKey:Ze}=await m5(tt),lt=new XMLHttpRequest;lt.upload.onprogress=jt=>{jt.lengthComputable&&z(jt.loaded/jt.total*100)},await new Promise((jt,ns)=>{lt.onload=()=>{lt.status>=200&<.status<300?jt():ns(new Error(`Upload failed: ${lt.status}`))},lt.onerror=()=>ns(new Error("Upload failed")),lt.open("PUT",Ke),lt.setRequestHeader("AccessKey",Ze),lt.send(_e)}),v("processing");let xt=0;const Xe=Date.now(),Je=90*1e3;for(;xt<4;){if(await new Promise(ns=>setTimeout(ns,3e3)),Date.now()-Xe>Je){const ns=_e.size/1048576,Ns=`https://iframe.mediadelivery.net/play/${tt}/${tt}`;await m.mutateAsync({bunny_video_id:tt,playback_url:Ns,file_size_mb:ns,title:ie||"Quick Video Touch",notes:ce||void 0,contact_id:oe&&oe!=="none"?oe:void 0,status:"processing",touch_type:"video_touch"}),r({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 jt=await Ev(tt);if(xt=jt.status,K(jt.encodeProgress||0),xt===4)le({playbackUrl:jt.directPlayUrl,thumbnailUrl:jt.thumbnailUrl,previewUrl:jt.previewUrl||null,duration:jt.length||Re,fileSizeMb:(jt.storageSize||_e.size)/(1024*1024)});else if(xt===5||xt===6)throw new Error("Video processing failed")}v("details")}catch(tt){console.error("Upload error:",tt),r({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),v("record")}},[ie,r]),xe=async()=>{if(!(!X||!re))try{const _e=oe&&oe!=="none"?oe:null,Re=await m.mutateAsync({bunny_video_id:X,contact_id:_e,playback_url:re.playbackUrl,thumbnail_url:re.thumbnailUrl,preview_url:re.previewUrl,duration_seconds:re.duration,file_size_mb:re.fileSizeMb,title:ie||"Quick Video Touch",notes:ce,task_id:a||null,status:"ready"});Ue(Re.id),De(Re.share_token||null),_e&&await x.mutateAsync({contactId:_e,videoId:Re.id,notes:ce}),r({title:"Video saved successfully!"}),v("share")}catch(_e){console.error("Save video error:",_e),r({title:"Failed to save video",description:(_e==null?void 0:_e.message)||"Please try again.",variant:"destructive"})}},et=(_e,Re)=>{navigator.clipboard.writeText(Re),He(_e),setTimeout(()=>He(null),2e3),r({title:"Copied to clipboard!"})},fe=()=>Be?`https://video.relevelup.com/${Be}`:(re==null?void 0:re.playbackUrl)||"",it=()=>{const _e=h==null?void 0:h.find(lt=>lt.id===oe),Re=_e?`${_e.first_name}`:"",tt=(_e==null?void 0:_e.phone)||"",Ke=(_e==null?void 0:_e.email)||"",Ze=fe();return{text:`Hey${Re?` ${Re}`:""}! I recorded a quick video for you: ${Ze}`,link:Ze,contactPhone:tt,contactEmail:Ke}},Oe=()=>{const{text:_e,contactPhone:Re}=it(),tt=Re?`sms:${Re}?body=${encodeURIComponent(_e)}`:`sms:?body=${encodeURIComponent(_e)}`;window.open(tt,"_self")},Ye=()=>{const{link:_e,contactEmail:Re}=it(),tt="Check out this video",Ke=`I recorded a quick video for you: ${_e}`,Ze=Re?`mailto:${Re}?subject=${encodeURIComponent(tt)}&body=${encodeURIComponent(Ke)}`:`mailto:?subject=${encodeURIComponent(tt)}&body=${encodeURIComponent(Ke)}`;window.open(Ze,"_self")};return i?e.jsx(ws,{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(G,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"QuickVid"}),e.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(ln,{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"]})]})]})]}),y==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(IL,{maxDurationSeconds:600,onRecordingComplete:Te,onRecordingStateChange:D,className:"w-full",teleprompterContent:N&&w&&e.jsx(DEe,{text:w,isVisible:N,onToggleVisibility:()=>S(!1),isRecording:I,startCountdown:!1})}),!N&&w&&e.jsxs(G,{variant:"outline",className:"mt-4",onClick:()=>S(!0),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(ke,{className:"lg:col-span-1",children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(or,{placeholder:"Type or paste your script here...",value:w,onChange:_e=>b(_e.target.value),rows:6}),e.jsxs(Jj,{open:T,onOpenChange:A,children:[e.jsx(o4e,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"w-full",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(Vb,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(e2,{className:"p-4 border-b",children:e.jsx(t2,{children:"Select a Script"})}),e.jsx(jMs,{onSelectScript:_e=>{b(_e.text),A(!1),S(!0)},className:"h-[calc(100vh-80px)]"})]})]}),w&&e.jsx(G,{className:"w-full",onClick:()=>S(!0),children:"Use Script"})]})]})]}),y==="uploading"&&e.jsx(ke,{className:"max-w-md mx-auto",children:e.jsxs(Pe,{className:"pt-6 text-center",children:[e.jsx(da,{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(ei,{value:F,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[F.toFixed(0),"%"]})]})}),y==="processing"&&e.jsx(ke,{className:"max-w-md mx-auto",children:e.jsxs(Pe,{className:"pt-6 text-center space-y-4",children:[e.jsx(es,{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(ei,{value:Q,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Q.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.`})]})}),y==="details"&&e.jsxs(ke,{className:"max-w-lg mx-auto",children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Video Details"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(Ne,{value:ie,onChange:_e=>ye(_e.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Attach to Contact (Optional)"}),e.jsxs(Is,{value:oe,onValueChange:ne,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"No contact - use anywhere"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(po,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),h==null?void 0:h.map(_e=>e.jsx(ct,{value:_e.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Di,{className:"h-4 w-4"}),_e.first_name," ",_e.last_name]})},_e.id))]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Notes"}),e.jsx(or,{value:ce,onChange:_e=>ve(_e.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(G,{className:"w-full",onClick:xe,disabled:m.isPending,children:[m.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),y==="share"&&e.jsxs(ke,{className:"max-w-lg mx-auto",children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Pe,{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(G,{variant:"outline",className:"justify-start",onClick:Oe,children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(G,{variant:"outline",className:"justify-start",onClick:Ye,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(G,{variant:"outline",className:"justify-start",onClick:()=>et("link",it().link),children:[e.jsx(po,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Ae==="link"&&e.jsx(Kn,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(G,{variant:"outline",className:"justify-start",onClick:()=>Ie(!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(G,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(G,{onClick:()=>{v("record"),$(null),Z(null),le(null)},children:"Record Another"})]})]})]}),be&&Be&&e.jsx(cpt,{open:Le,onOpenChange:Ie,video:{id:be,share_token:Be,title:ie||null,contact_id:oe||null,thumbnail_url:(re==null?void 0:re.thumbnailUrl)||null},contactName:((We=h==null?void 0:h.find(_e=>_e.id===oe))==null?void 0:We.first_name)||null})]})}):e.jsx(ws,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(id,{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(G,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function SMs({open:s,onOpenChange:t,video:r,gmailEmail:n,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=k.useState([]),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,y]=k.useState(!1),[v,w]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,I]=k.useState(!1),D=Eht(),R=r.share_token?`https://video.relevelup.com/share/video/${r.share_token}`:"",$=r.share_token?`https://video.relevelup.com/thumb/${r.share_token}`:a||r.thumbnail_url||"",F=r.title||"Video Message";k.useEffect(()=>{s&&l.length===0&&z()},[s]),k.useEffect(()=>{if(s&&(N(`I recorded a video for you — ${F}`),T("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),w(""),r.contact_id)){const le=l.find(oe=>oe.id===r.contact_id);le&&(d(le),w(le.email||""))}},[s,r.contact_id,l]);const z=async()=>{y(!0);try{const{data:le,error:oe}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(oe)throw oe;o(le||[])}catch{console.error("Failed to fetch contacts")}finally{y(!1)}},Q=le=>{d(le),m(!1),w(le.email||""),T(`Hey ${le.first_name}! I recorded a quick video just for you. Click below to watch it:`),N(`I recorded a video for you — ${F}`)},K=()=>{d(null),w(""),T("Hey! I recorded a quick video just for you. Click below to watch it:")},X=le=>`${le.first_name} ${le.last_name||""}`.trim(),Z=le=>{const oe=S.split(/\n\n+/).map(ye=>`

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

`).join(""),ne=le?Mht(le):R,ie=le?``:"";return`
${oe}

▶ Watch Video

${ie}
`},re=async()=>{var le;if(!v){ue.error("Please enter a recipient email");return}if(!R){ue.error("Video does not have a share link");return}I(!0);try{let oe;try{const ve=c?X(c):v.split("@")[0];oe=(await D.mutateAsync({video_id:r.id,recipient_email:v,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 ne=Z(oe),{data:ie,error:ye}=await V.functions.invoke("gmail-send",{body:{to:v,subject:b,body:ne,contactId:(c==null?void 0:c.id)||null}});let ce=null;if(ye&&((le=ye.context)!=null&&le.json))try{ce=await ye.context.json()}catch{}if((ce==null?void 0:ce.error)==="insufficient_scope"||(ie==null?void 0:ie.error)==="insufficient_scope"){ue.error((ce==null?void 0:ce.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ye)throw new Error((ce==null?void 0:ce.message)||ye.message);if(!(ie!=null&&ie.success))throw new Error((ie==null?void 0:ie.error)||"Failed to send");ue.success("Video email sent!"),t(!1),i==null||i()}catch(oe){console.error("Gmail send error:",oe),ue.error("Failed to send: "+(oe instanceof Error?oe.message:"Unknown error"))}finally{I(!1)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),n&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:n})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(To,{open:h,onOpenChange:m,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"}),X(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(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[350px] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search contacts..."}),e.jsxs(ax,{children:[e.jsx(ix,{children:x?"Loading...":"No contacts found."}),e.jsx(ox,{children:l.filter(le=>le.email).map(le=>e.jsxs(cf,{value:`${le.first_name} ${le.last_name||""} ${le.email||""}`,onSelect:()=>Q(le),children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",(c==null?void 0:c.id)===le.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:X(le)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:le.email})]})]},le.id))})]})]})})]}),c&&e.jsx(G,{variant:"ghost",size:"icon",onClick:K,className:"shrink-0",children:e.jsx(vr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(Ne,{id:"video-to",value:v,onChange:le=>w(le.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"video-subject",children:"Subject"}),e.jsx(Ne,{id:"video-subject",value:b,onChange:le=>N(le.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(or,{id:"video-message",value:S,onChange:le=>T(le.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(he,{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:[$?e.jsx("img",{src:$,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(Uo,{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(Uo,{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(G,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),e.jsxs(G,{onClick:re,disabled:A||!v||!b,className:"gap-2",children:[A?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const CMs=()=>{const{user:s}=js();return mt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.rpc("get_team_videos",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})};function TMs({recipient:s}){return s.watched_at?e.jsxs(Ge,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Uo,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Ge,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(Bu,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Ge,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(bn,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Ge,{variant:"outline",className:"text-[10px]",children:[e.jsx(en,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function EMs({open:s,onOpenChange:t,videoId:r,videoTitle:n}){const{data:a=[],isLoading:i}=a5s(r);return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(ro,{className:"h-5 w-5"}),"Send Analytics: ",n]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(Fs,{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(Qa,{className:"h-[400px]",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Recipient"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Sent"}),e.jsx(Nt,{children:"Last Activity"})]})}),e.jsx($n,{children:a.map(l=>e.jsxs(Ds,{children:[e.jsx(dt,{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(dt,{children:e.jsx(TMs,{recipient:l})}),e.jsx(dt,{className:"text-xs text-muted-foreground",children:_s(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(dt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?rl(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function AMs(){const{data:s,isLoading:t}=i5s(),{data:r=[],isLoading:n}=o5s(),[a,i]=k.useState(null),l=t||n,o=r.reduce((c,d)=>{const h=d.agent_videos,m=(h==null?void 0:h.id)||d.video_id;return c[m]||(c[m]={videoId:m,title:(h==null?void 0:h.title)||"Untitled",thumbnailUrl:h==null?void 0:h.thumbnail_url,recipients:[]}),c[m].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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Fs,{className:"h-4 w-20"})}),e.jsx(Pe,{children:e.jsx(Fs,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(en,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Pe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(bn,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Bu,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Pe,{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(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Nr,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Pe,{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(m=>m.opened_at).length,h=c.recipients.filter(m=>m.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:m=>{const x=m.currentTarget;x.style.display="none",x.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Jr,{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(en,{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(bn,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(Bu,{className:"h-3 w-3"})," ",h]})]})]}),e.jsx(bo,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(EMs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function MMs({previewSrc:s,thumbnailSrc:t,alt:r,isHovered:n}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),c=n&&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(Jr,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:r,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:r,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function IMs({video:s,previewSrc:t,thumbnailSrc:r,onOpen:n,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:h,onSendViaGmail:m,isGmailConnected:x,getContactName:y,getShareUrl:v,copyToClipboard:w,formatDuration:b}){const[N,S]=k.useState(!1);return e.jsxs(ke,{className:"overflow-hidden group cursor-pointer",onClick:n,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(MMs,{previewSrc:t,thumbnailSrc:r,alt:s.title||"Video preview",isHovered:N}),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(Uo,{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:b(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Ge,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Pe,{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(Di,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:y(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(fn,{className:"h-3 w-3"}),e.jsx("span",{children:_s(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(bn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),x&&s.share_token&&e.jsxs(G,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:T=>{T.stopPropagation(),m==null||m()},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(Di,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:y(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(fn,{className:"h-3 w-3"}),e.jsx("span",{children:_s(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(bn,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:T=>T.stopPropagation(),children:e.jsx(Yx,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",className:"bg-popover",children:[e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),n()},children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(_v,{}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),h()},children:[e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),w(v(s),"Share link")},children:[e.jsx(po,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),o()},children:[e.jsx(P4,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),c()},children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),d()},children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),x&&s.share_token&&e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),m==null||m()},children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),i()},children:[e.jsx(Ea,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(_v,{}),s.contact_id&&e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),l()},children:[e.jsx(Di,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Pa,{onClick:T=>{T.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function LMs(){var Ns,Ys;const s=br(),{data:t,isLoading:r,refetch:n}=S5s(),{data:a}=bxe(),{data:i}=Sm(),l=E5s(),o=T5s(),{isGmailConnected:c,gmailEmail:d}=Eh(),{data:h}=yg(),{data:m=[],isLoading:x}=CMs(),[y,v]=k.useState("my"),[w,b]=k.useState(""),[N,S]=k.useState(null),[T,A]=k.useState(!1),[I,D]=k.useState(!1),[R,$]=k.useState(!1),[F,z]=k.useState(!1),[Q,K]=k.useState(!1),[X,Z]=k.useState(""),[re,le]=k.useState(!1),[oe,ne]=k.useState(!1),[ie,ye]=k.useState(!1),[ce,ve]=k.useState(!1),[be,Ue]=k.useState(""),[Be,De]=k.useState({}),Ae=rs=>{if(!rs)return"Unassigned";const bt=i==null?void 0:i.find(cs=>cs.id===rs);return bt?`${bt.first_name} ${bt.last_name||""}`.trim():"Unknown"},He=rs=>{if(!rs)return"0:00";const bt=Math.floor(rs/60),cs=rs%60;return`${bt}:${cs.toString().padStart(2,"0")}`},[Le,Ie]=k.useState("all"),Te=t==null?void 0:t.filter(rs=>{const bt=rs.category||"general";if(Le==="general"&&bt!=="general"||Le==="open_house"&&bt!=="open_house")return!1;if(!w)return!0;const cs=Ae(rs.contact_id).toLowerCase(),yt=(rs.title||"").toLowerCase(),is=(rs.notes||"").toLowerCase();return cs.includes(w.toLowerCase())||yt.includes(w.toLowerCase())||is.includes(w.toLowerCase())}),xe=(t==null?void 0:t.filter(rs=>(rs.category||"general")==="open_house").length)||0,et=(t==null?void 0:t.filter(rs=>(rs.category||"general")==="general").length)||0,fe=(t||[]).filter(rs=>rs.status==="processing"&&rs.bunny_video_id).map(rs=>rs.id).join(",");k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const bt=t.filter(yt=>yt.status==="processing"&&yt.bunny_video_id);if(!bt.length)return;let cs=!1;for(const yt of bt)try{const{data:is,error:Bs}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:yt.bunny_video_id,isAgentVideo:!0}});if(Bs||!is)continue;is.status===4&&(await V.from("agent_videos").update({status:"ready",playback_url:is.directPlayUrl,thumbnail_url:is.thumbnailUrl,preview_url:is.previewUrl,duration_seconds:is.length||yt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",yt.id),cs=!0)}catch(is){console.warn("Reconcile check failed for video",yt.id,is)}cs&&n()})()},[fe,n]),k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const bt=t.filter(ps=>(ps==null?void 0:ps.bunny_video_id)&&!Be[ps.id]);if(!bt.length)return;const cs=bt.map(ps=>ps.bunny_video_id),{data:yt,error:is}=await V.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:cs,isAgentVideo:!0}});if(is)throw is;const Bs=(yt==null?void 0:yt.assets)||{};De(ps=>{const lr={...ps};for(const kr of bt)Bs[kr.bunny_video_id]&&(lr[kr.id]={previewUrl:Bs[kr.bunny_video_id].previewUrl,thumbnailUrl:Bs[kr.bunny_video_id].thumbnailUrl});return lr})})().catch(bt=>console.warn("Failed to load signed Bunny asset URLs",bt))},[t,Be]);const it=(a==null?void 0:a.total_storage_mb)||0,Oe=(a==null?void 0:a.max_storage_mb)||1024,Ye=it/Oe*100,We=Ye>=80,_e=Ye>=100,Re=async(rs,bt)=>{await navigator.clipboard.writeText(rs),ue.success(`${bt} copied to clipboard`)},tt=rs=>rs.share_token?`https://video.relevelup.com/${rs.share_token}`:rs.playback_url||"",Ke=rs=>{const bt=tt(rs),cs=i==null?void 0:i.find(kr=>kr.id===rs.contact_id),yt=Ae(rs.contact_id),is=yt!=="Unassigned"?yt.split(" ")[0]:"",Bs=(cs==null?void 0:cs.phone)||"",ps=`Hey${is?` ${is}`:""}! I recorded a quick video message for you. Check it out: ${bt}`,lr=Bs?`sms:${Bs}?body=${encodeURIComponent(ps)}`:`sms:?body=${encodeURIComponent(ps)}`;window.open(lr,"_self")},Ze=rs=>{const bt=i==null?void 0:i.find(lr=>lr.id===rs.contact_id),cs=(bt==null?void 0:bt.email)||"",yt=tt(rs),is="Check out this video",Bs=`I recorded a quick video for you: ${yt}`,ps=cs?`mailto:${cs}?subject=${encodeURIComponent(is)}&body=${encodeURIComponent(Bs)}`:`mailto:?subject=${encodeURIComponent(is)}&body=${encodeURIComponent(Bs)}`;window.open(ps,"_self")},lt=rs=>{var is;const bt=tt(rs),cs=rs.title||"Video Message",yt=rs.share_token?`https://video.relevelup.com/thumb/${rs.share_token}`:((is=Be[rs.id])==null?void 0:is.thumbnailUrl)||rs.thumbnail_url||"";return``},xt=async rs=>{if(!rs.thumbnail_url&&!rs.share_token){ue.error("Video thumbnail not available yet");return}const bt=lt(rs),cs=tt(rs),yt=`Watch: ${rs.title||"Video Message"} ${cs}`;try{const is=new Blob([bt],{type:"text/html"}),Bs=new Blob([yt],{type:"text/plain"}),ps=new ClipboardItem({"text/html":is,"text/plain":Bs});await navigator.clipboard.write([ps]),ue.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(yt+` `+bt),ue.success("Copied! Paste into your email.")}},Xe=async rs=>{try{ue.loading("Preparing download...",{id:"download"});const{data:bt,error:cs}=await V.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:rs.bunny_video_id,isAgentVideo:!0}});if(cs||!(bt!=null&&bt.downloadUrl))throw new Error((cs==null?void 0:cs.message)||"Failed to get download URL");const is=`${((rs.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Bs=await fetch(bt.downloadUrl);if(!Bs.ok)throw new Error("Failed to fetch video file");const ps=await Bs.blob(),lr=URL.createObjectURL(ps),kr=document.createElement("a");kr.href=lr,kr.download=is,kr.rel="noreferrer",document.body.appendChild(kr),kr.click(),kr.remove(),URL.revokeObjectURL(lr),ue.success("Download started",{id:"download"})}catch(bt){console.error("Download error:",bt),ue.error("Could not force download (your browser may block it).",{id:"download"})}},Je=async rs=>{S(rs),le(!0),Z(""),K(!0);try{const{data:bt,error:cs}=await V.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:rs.bunny_video_id,title:rs.title,isAgentVideo:!0,shareToken:rs.share_token}});if(cs||!(bt!=null&&bt.html))throw new Error("Failed to generate CRM embed code");Z(bt.html)}catch(bt){console.error("CRM embed error:",bt),ue.error("Failed to generate CRM embed code"),K(!1)}finally{le(!1)}},jt=rs=>{S(rs),A(!0)},ns=async()=>{if(N)try{await l.mutateAsync({id:N.id,bunnyVideoId:N.bunny_video_id,hardDelete:!0}),D(!1),S(null),ue.success("Video deleted successfully")}catch{ue.error("Failed to delete video")}};return e.jsx(ws,{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:()=>v("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${y==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),h&&((Ns=h.team)==null?void 0:Ns.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>v("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${y==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>v("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${y==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(ro,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),y==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>$(!0),children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(G,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),y==="team"?e.jsx(PMs,{videos:m,isLoading:x,searchTerm:w,setSearchTerm:b}):y==="analytics"?e.jsx(AMs,{}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:We?"border-amber-500":_e?"border-destructive":"",children:e.jsxs(Pe,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(bR,{className:`h-5 w-5 ${_e?"text-destructive":We?"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 / ",Oe>=1024?`${(Oe/1024).toFixed(0)} GB`:`${Oe} MB`]})]}),e.jsx(ei,{value:Math.min(Ye,100),className:`h-2 ${_e?"[&>div]:bg-destructive":We?"[&>div]:bg-amber-500":""}`})]}),We&&!_e&&e.jsxs(Ge,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),_e&&e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),_e&&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:et},{id:"open_house",label:"Open House Tours",count:xe}].map(rs=>e.jsxs("button",{onClick:()=>Ie(rs.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Le===rs.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[rs.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:rs.count})]},rs.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos by contact, title, or notes...",value:w,onChange:rs=>b(rs.target.value),className:"pl-10"})]}),r?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"})}):(Te==null?void 0:Te.length)===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(Jr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"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(G,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx($s,{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:Te==null?void 0:Te.map(rs=>{var bt,cs;return e.jsx(IMs,{video:rs,previewSrc:(bt=Be[rs.id])==null?void 0:bt.previewUrl,thumbnailSrc:(cs=Be[rs.id])==null?void 0:cs.thumbnailUrl,onOpen:()=>jt(rs),onDelete:()=>{S(rs),D(!0)},onRename:()=>{S(rs),Ue(rs.title||""),ve(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${rs.contact_id}`),onGetEmbedCode:()=>{S(rs),z(!0)},onCopyEmailHtml:()=>xt(rs),onEmbedToCrm:()=>Je(rs),onShareWithTemplate:()=>{S(rs),ne(!0)},onSendViaGmail:()=>{S(rs),ye(!0)},isGmailConnected:c,getContactName:Ae,getShareUrl:tt,copyToClipboard:Re,formatDuration:He},rs.id)})}),e.jsx(fs,{open:T,onOpenChange:A,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:(N==null?void 0:N.title)||"Video Preview"}),e.jsx(Hr,{children:(N==null?void 0:N.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Di,{className:"h-3 w-3"}),Ae(N.contact_id)]})})]}),N&&e.jsxs("div",{className:"space-y-4",children:[N.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(es,{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(G,{variant:"outline",size:"sm",onClick:()=>{A(!1),n()},children:[e.jsx(Mi,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:N.playback_url?(()=>{let rs=N.playback_url;return rs.includes("iframe.mediadelivery.net/play/")&&(rs=rs.replace("/play/","/embed/"),rs+=(rs.includes("?")?"&":"?")+"autoplay=false&responsive=true"),rs.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:rs,title:N.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:N.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:N.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ue.error("Video preview failed to load")},N.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(Jr,{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(G,{variant:"outline",onClick:()=>Ke(N),children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(G,{variant:"outline",onClick:()=>Ze(N),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(G,{variant:"outline",onClick:()=>Re(tt(N),"Share link"),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(G,{variant:"outline",onClick:()=>xt(N),children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(G,{variant:"outline",onClick:()=>Xe(N),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(G,{variant:"outline",onClick:()=>{A(!1),Je(N)},children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(G,{variant:"outline",onClick:()=>{A(!1),ne(!0)},children:[e.jsx(fl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(N==null?void 0:N.share_token)&&e.jsxs(G,{variant:"outline",onClick:()=>{A(!1),ye(!0)},children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(G,{variant:"destructive",onClick:()=>{A(!1),D(!0)},children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(fs,{open:I,onOpenChange:D,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Delete Video"}),e.jsx(Hr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>D(!1),children:"Cancel"}),e.jsx(G,{variant:"destructive",onClick:ns,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Rht,{open:R,onOpenChange:$}),e.jsx(fs,{open:F,onOpenChange:z,children:e.jsxs(ms,{className:"sm:max-w-lg",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Embed Video"}),e.jsx(Hr,{children:"Copy this code to embed the video on your website."})]}),N&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Embed Code"}),e.jsx(or,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(G,{className:"flex-1",onClick:()=>{const rs=``;Re(rs,"Embed code")},children:[e.jsx(Ra,{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."})]})]})}),N&&e.jsx(cpt,{open:oe,onOpenChange:ne,video:N,contactName:Ae(N.contact_id)}),N&&e.jsx(SMs,{open:ie,onOpenChange:ye,video:N,gmailEmail:d,signedThumbnailUrl:(Ys=Be[N.id])==null?void 0:Ys.thumbnailUrl}),e.jsx(fs,{open:ce,onOpenChange:ve,children:e.jsxs(ms,{className:"max-w-sm",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Rename Video"}),e.jsx(Hr,{children:"Enter a new title for this video."})]}),e.jsx(Ne,{value:be,onChange:rs=>Ue(rs.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:rs=>{rs.key==="Enter"&&be.trim()&&o.mutate({id:N.id,title:be.trim()},{onSuccess:()=>{ue.success("Video renamed"),ve(!1)}})}}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx(G,{disabled:!be.trim()||o.isPending,onClick:()=>{o.mutate({id:N.id,title:be.trim()},{onSuccess:()=>{ue.success("Video renamed"),ve(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(fs,{open:Q,onOpenChange:K,children:e.jsxs(ms,{className:"sm:max-w-lg",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Qr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Hr,{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."})]}),re?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(es,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):X?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"CRM Email HTML"}),e.jsx(or,{readOnly:!0,rows:12,value:X,className:"font-mono text-xs"})]}),e.jsxs(G,{className:"w-full",onClick:()=>{Re(X,"CRM embed code")},children:[e.jsx(Ra,{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 PMs({videos:s,isLoading:t,searchTerm:r,setSearchTerm:n}){const a=k.useMemo(()=>{if(!r)return s;const o=r.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,r]),i=k.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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search team videos by title, owner, or recipient...",value:r,onChange:o=>n(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(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(pr,{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(Nn,{className:"h-7 w-7",children:[e.jsx(ya,{src:c.avatar||""}),e.jsx(kn,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Ge,{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(ke,{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:h=>{h.target.style.display="none"}}):e.jsx(Jr,{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(Pe,{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(Di,{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(bn,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),_s(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const DMs=()=>{const{user:s}=js();return mt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.rpc("get_team_deals",{_user_id:s.id});if(r)throw r;return t||[]},enabled:!!s})},Bqe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function RMs({open:s,onOpenChange:t}){const{data:r,isLoading:n}=DMs(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=k.useMemo(()=>{if(!r)return new Map;const v=new Map;let w=0;return r.forEach(b=>{v.has(b.owner_user_id)||(v.set(b.owner_user_id,{name:b.owner_name||"Unknown",avatar:b.owner_avatar_url,color:Bqe[w%Bqe.length]}),w++)}),v},[r]),d=k.useMemo(()=>Array.from(c.entries()).map(([v,w])=>({id:v,...w})),[c]),h=k.useMemo(()=>{if(!r)return[];let v=r;if(l!=="all"&&(v=v.filter(w=>w.owner_user_id===l)),a.trim()){const w=a.toLowerCase();v=v.filter(b=>{var N,S,T,A;return b.deal_name.toLowerCase().includes(w)||((N=b.contact_name)==null?void 0:N.toLowerCase().includes(w))||((S=b.property_address)==null?void 0:S.toLowerCase().includes(w))||((T=b.city)==null?void 0:T.toLowerCase().includes(w))||((A=b.owner_name)==null?void 0:A.toLowerCase().includes(w))})}return v},[r,a,l]),m=k.useMemo(()=>{const v=new Map;return h.forEach(w=>{const b=w.stage_name||"Unknown";v.has(b)||v.set(b,{name:b,color:w.stage_color,icon:w.stage_icon,deals:[],totalValue:0});const N=v.get(b);N.deals.push(w),N.totalValue+=w.sale_price||0}),Array.from(v.values())},[h]),x=v=>v>=1e6?`$${(v/1e6).toFixed(1)}M`:v>=1e3?`$${(v/1e3).toFixed(0)}K`:`$${v.toFixed(0)}`,y=v=>v?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(v):null;return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(pr,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search deals...",value:a,onChange:v=>i(v.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:l,onValueChange:o,children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{placeholder:"All Members"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Members"}),d.map(v=>e.jsx(ct,{value:v.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:v.color}}),v.name]})},v.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(v=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:v.color}}),v.name.split(" ")[0]]},v.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:n?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(v=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(Fs,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(Fs,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(Fs,{className:"h-24 w-full rounded-lg"})]},v))}):m.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(pr,{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:m.map(v=>{const w=v.icon&&Pme[v.icon]||Ld;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:v.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:v.color?`${v.color}20`:void 0},children:e.jsx(w,{className:"h-3.5 w-3.5",style:{color:v.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:v.name})]}),e.jsx(Ge,{variant:"secondary",className:"text-xs px-2",children:v.deals.length})]}),v.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:x(v.totalValue)})]}),e.jsx(Qa,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:v.deals.map(b=>{const N=c.get(b.owner_user_id);return e.jsx(OMs,{deal:b,ownerColor:(N==null?void 0:N.color)||"#888",ownerName:(N==null?void 0:N.name)||"Unknown",ownerAvatar:(N==null?void 0:N.avatar)||null,formatPrice:y},b.id)})})})]},v.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[h.length," deal",h.length!==1?"s":""," across ",m.length," stage",m.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function OMs({deal:s,ownerColor:t,ownerName:r,ownerAvatar:n,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(Nn,{className:"h-4 w-4",children:[e.jsx(ya,{src:n||""}),e.jsx(kn,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:r.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:r})]}),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(Ge,{variant:"outline",className:It("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(En,{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(wl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function FMs({members:s,enabledMembers:t,onToggleMember:r,isOpen:n,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:It("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",n?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(pr,{className:"h-4 w-4 shrink-0 text-primary"}),n&&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($o,{className:"h-3 w-3 text-muted-foreground"})]}),!n&&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})]})}),n?e.jsxs(Qa,{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:()=>r(l.id),className:It("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(Nn,{className:"h-7 w-7",children:[e.jsx(ya,{src:l.avatar_url||""}),e.jsx(kn,{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:It("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(_r,{checked:o,onCheckedChange:()=>r(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:()=>r(l.id),className:"relative",title:l.name,children:e.jsxs(Nn,{className:It("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(ya,{src:l.avatar_url||""}),e.jsx(kn,{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 zqe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function BMs(){const s=sa(),{data:t}=yg(),r=(t==null?void 0:t.role)==="team_leader",n=t==null?void 0:t.teamId,a=mt({queryKey:["team-pipeline-members",n,s],queryFn:async()=>{const{data:i,error:l}=await V.from("team_members").select("user_id, role").eq("team_id",n).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(h=>h.user_id),{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((h,m)=>({id:h.id,name:h.name||"Unknown",avatar_url:h.avatar_url,color:zqe[m%zqe.length]}))},enabled:!!n&&!!s&&r,staleTime:5*60*1e3});return{isTeamLeader:r,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function zMs(s){return mt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:r}=await V.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(r)throw r;return(t||[]).map(n=>{var a;return{...n,_stage_name:((a=n.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function $Ms(){const s=sa();return mt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:r}=await V.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(r)throw r;const n=t||[],a={},i=new Set;n.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:n,byDeal:a,unique:l}},enabled:!!s})}function dpt({stages:s,currentStageId:t,onStageSelect:r,disabled:n}){const[a,i]=k.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&r(c.id,c.name),i(!1)};return e.jsxs(Fd,{open:a,onOpenChange:i,children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:n,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(va,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(xd,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&Pme[c.icon]||Ld,h=c.id===t;return e.jsxs(Pa,{onClick:()=>o(c),className:It("flex items-center gap-2 cursor-pointer",h&&"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}),h&&e.jsx(Kn,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const UMs={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"}},qMs={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 upt({deal:s,onClick:t,isDragging:r,stages:n,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var S,T;const c=gL(),d=UMs[s.deal_type],h=qMs[s.priority],m=k.useMemo(()=>s.target_close_date?pg(Fl(s.target_close_date),new Date):null,[s.target_close_date]),x=m!==null&&m<0,y=m!==null&&m<=7&&m>=0,v=k.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!A)return null;const I=s.contract_date?Fl(s.contract_date):new Date;return pg(I,Fl(A))},[s]),w=l&&!s.scorecard_transaction_id,b=!!s.scorecard_transaction_id,N=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(ke,{className:It("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",r&&"opacity-50 rotate-2 shadow-xl",x&&"border-red-200 bg-red-50/30",w&&"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(Pe,{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(Nn,{className:"h-4 w-4",children:[e.jsx(ya,{src:o.avatar_url||""}),e.jsx(kn,{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(Ge,{variant:"outline",className:It("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(Nn,{className:"h-5 w-5",children:e.jsxs(kn,{className:"text-[10px] bg-primary/10 text-primary",children:[(S=s.contact.first_name)==null?void 0:S[0],(T=s.contact.last_name)==null?void 0:T[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(tl,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),w&&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(Gi,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),b&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(In,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),v!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(tv,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:It("font-medium",v>90?"text-red-600":v>60?"text-amber-600":"text-muted-foreground"),children:[v," 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(En,{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(wl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:N(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",N(s.expected_commission)," GCI"]}),(()=>{const A=Jx(s);return A!==null&&A!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",N(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:It("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",h.color),children:[e.jsx("div",{className:It("w-1.5 h-1.5 rounded-full",h.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.probability,"%"]})]}),i&&c&&n&&a?e.jsx(dpt,{stages:n,currentStageId:s.stage_id||"",onStageSelect:(A,I)=>a(s.id,A,I)}):s.target_close_date?e.jsxs("div",{className:It("flex items-center gap-1 text-[10px]",x&&"text-red-600",y&&!x&&"text-amber-600",!x&&!y&&"text-muted-foreground"),children:[x?e.jsx(Oi,{className:"h-3 w-3"}):e.jsx(on,{className:"h-3 w-3"}),e.jsx("span",{children:x?`${Math.abs(m)}d overdue`:y?`${m}d left`:_s(Fl(s.target_close_date),"MMM d")})]}):null]})]})})}function VMs({stage:s,deals:t,onDealClick:r,onAddDeal:n,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const h=k.useRef(null),m=t.reduce((b,N)=>b+(N.expected_price||0),0),x=t.reduce((b,N)=>b+(N.expected_commission||0),0),y=t.reduce((b,N)=>b+(Jx(N)||0),0),v=b=>b>=1e6?`$${(b/1e6).toFixed(1)}M`:b>=1e3?`$${(b/1e3).toFixed(0)}K`:`$${b.toFixed(0)}`,w=s.icon&&Pme[s.icon]||Ld;return e.jsxs("div",{ref:h,className:It("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:b=>i(b,s.id),onDrop:b=>l(b,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(w,{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(Ge,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),m>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:v(m)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[v(x)," GCI"]}),y>0&&y!==x&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[v(y)," Net"]})]})]})]}),e.jsx(Qa,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(b=>e.jsx("div",{draggable:!0,onDragStart:N=>{N.dataTransfer.effectAllowed="move",a(b.id,s.id)},children:e.jsx(upt,{deal:b,onClick:()=>r(b),isWonStage:c,ownerInfo:(d==null?void 0:d(b))||null})},b.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(G,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>n(s.id),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function HMs({stats:s,isLoading:t}){const r=a=>a>=1e6?`$${(a/1e6).toFixed(1)}M`:a>=1e3?`$${(a/1e3).toFixed(0)}K`:`$${a.toLocaleString()}`,n=[{label:"Active Deals",value:(s==null?void 0:s.activeDeals)||0,icon:Pd,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:r((s==null?void 0:s.weightedGCI)||0),icon:FR,color:"text-indigo-500",bgColor:"bg-indigo-500/10",tooltip:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:r((s==null?void 0:s.weightedNet)||0),icon:XR,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:r((s==null?void 0:s.ytdWonNet)||0),icon:lR,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:r((s==null?void 0:s.projectedAnnualNet)||0),icon:bo,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(ke,{className:"animate-pulse",children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(Ub,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:n.map(a=>{const i=e.jsx(ke,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:It("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:It("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(cc,{children:[e.jsx(dc,{asChild:!0,children:i}),e.jsx(Gl,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function GMs({formData:s,onChange:t,isEditing:r}){const{isAdmin:n}=js(),[a,i]=k.useState(s.portal_enabled);if(!n)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(jr,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ge,{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(Gp,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(Wp,{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(jr,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Ge,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Wi,{className:It("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(Kp,{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(he,{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(_r,{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(he,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(ab,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:It("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(Hd,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hc,{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:It("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(Hd,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(fc,{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(Si,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(he,{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(Si,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(he,{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(he,{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(he,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(Ne,{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(he,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(Ne,{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(he,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(Ne,{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(he,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(Is,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"email",children:"Email"}),e.jsxs(ct,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const WMs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],KMs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function YMs({open:s,onOpenChange:t,deal:r,defaultStageId:n}){const{data:a}=_xe(),{data:i}=Sm(),{data:l}=nnt(),o=Ufe(),c=nmt(),d=amt(),h=RTe(),[m,x]=k.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[y,v]=k.useState(""),[w,b]=k.useState(!1),[N,S]=k.useState(!1),[T,A]=k.useState({first_name:"",last_name:"",email:"",phone:""}),I=(l==null?void 0:l.filter(X=>((r==null?void 0:r.listing_id)===X.id,!0)))||[],[D,R]=k.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:""});k.useEffect(()=>{var X,Z,re,le,oe,ne,ie,ye;s&&(r?(R({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||"",contact_id:r.contact_id||"",listing_id:r.listing_id||"",property_address:r.property_address||"",city:r.city||"",state:r.state||"",zip_code:r.zip_code||"",expected_price:((X=r.expected_price)==null?void 0:X.toString())||"",commission_percentage:((Z=r.commission_percentage)==null?void 0:Z.toString())||"3",brokerage_split_pct:((re=r.brokerage_split_pct)==null?void 0:re.toString())||"",team_split_pct:((le=r.team_split_pct)==null?void 0:le.toString())||"",referral_fee_pct:((oe=r.referral_fee_pct)==null?void 0:oe.toString())||"",franchise_fee_pct:((ne=r.franchise_fee_pct)==null?void 0:ne.toString())||"",transaction_fee:((ie=r.transaction_fee)==null?void 0:ie.toString())||"",commission_calc_method:r.commission_calc_method||"standard",target_close_date:r.target_close_date?Fl(r.target_close_date):void 0,contract_date:r.contract_date?Fl(r.contract_date):void 0,listing_date:r.listing_date?Fl(r.listing_date):void 0,priority:r.priority,probability:r.probability.toString(),notes:r.notes||""}),r.contact&&v(`${r.contact.first_name} ${r.contact.last_name}`)):(R({deal_name:"",deal_type:"buyer",stage_id:n||((ye=a==null?void 0:a[0])==null?void 0:ye.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:""}),v(""),x({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,r,n,a]);const $=i==null?void 0:i.filter(X=>{var ve,be,Ue,Be,De;const Z=y.toLowerCase().trim();if(!Z)return!0;const re=((ve=X.first_name)==null?void 0:ve.toLowerCase())||"",le=((be=X.last_name)==null?void 0:be.toLowerCase())||"",oe=((Ue=X.email)==null?void 0:Ue.toLowerCase())||"",ne=((De=(Be=X.phone)==null?void 0:Be.toLowerCase)==null?void 0:De.call(Be))||"",ie=`${re} ${le}`.trim(),ye=`${le} ${re}`.trim();if(ie.includes(Z)||ye.includes(Z)||re.includes(Z)||le.includes(Z)||oe.includes(Z)||ne.includes(Z))return!0;const ce=Z.split(/\s+/).filter(Boolean);return ce.length>1?ce.every(Ae=>re.includes(Ae)||le.includes(Ae)||oe.includes(Ae)||ne.includes(Ae)):!1}).slice(0,8),F=()=>{const X=parseFloat(D.expected_price)||0,Z=parseFloat(D.commission_percentage)||0;return X*(Z/100)},z=()=>{const X=F();if(!X)return null;const Z=parseFloat(D.brokerage_split_pct)||0,re=parseFloat(D.team_split_pct)||0,le=parseFloat(D.referral_fee_pct)||0,oe=parseFloat(D.franchise_fee_pct)||0,ne=parseFloat(D.transaction_fee)||0;if(D.commission_calc_method==="referral_first"){let ye=X;le&&(ye-=X*le/100);let ce=ye;return Z&&(ce-=ye*Z/100),re&&(ce-=X*re/100),oe&&(ce-=X*oe/100),ne&&(ce-=ne),Math.max(0,ce)}let ie=X;return Z&&(ie=ie*((100-Z)/100)),re&&(ie=ie*((100-re)/100)),le&&(ie=ie-X*le/100),oe&&(ie=ie-X*oe/100),ne&&(ie=ie-ne),Math.max(0,ie)},Q=async X=>{var Z,re,le;if(X.preventDefault(),!D.deal_name.trim()){ue.error("Please enter a deal name");return}try{const oe={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:F()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,commission_calc_method:D.commission_calc_method,target_close_date:((Z=D.target_close_date)==null?void 0:Z.toISOString().split("T")[0])||null,contract_date:((re=D.contract_date)==null?void 0:re.toISOString().split("T")[0])||null,listing_date:((le=D.listing_date)==null?void 0:le.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(r)await d.mutateAsync({id:r.id,...oe}),ue.success("Deal updated successfully");else{const ne=await c.mutateAsync(oe);if(ue.success("Deal created successfully"),m.portal_enabled&&(ne!=null&&ne.id))try{await h.mutateAsync({deal_id:ne.id,visibility:m.visibility,require_onboarding:m.require_onboarding,allow_spouse:m.allow_spouse,client_name:m.client_name||null,client_email:m.client_email||null,client_phone:m.client_phone||null,invite_method:m.invite_method}),ue.success("Client portal created!")}catch{ue.error("Deal created, but portal setup failed")}}t(!1)}catch{ue.error("Failed to save deal")}},K=c.isPending||d.isPending;return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:r?"Edit Deal":"Add New Deal"}),e.jsx(Hr,{children:r?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:Q,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(he,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(Ne,{id:"deal_name",value:D.deal_name,onChange:X=>R(Z=>({...Z,deal_name:X.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Deal Type"}),e.jsxs(Is,{value:D.deal_type,onValueChange:X=>R(Z=>({...Z,deal_type:X})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:WMs.map(X=>e.jsx(ct,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Stage"}),e.jsxs(Is,{value:D.stage_id||"none",onValueChange:X=>R(Z=>({...Z,stage_id:X==="none"?"":X})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select stage"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No Stage"}),a==null?void 0:a.map(X=>e.jsx(ct,{value:X.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:X.color}}),X.name]})},X.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:y,onChange:X=>{v(X.target.value),b(!0),S(!1),X.target.value||R(Z=>({...Z,contact_id:""}))},onFocus:()=>b(!0),placeholder:"Search contacts...",className:"pl-9"}),w&&y&&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:[$&&$.length>0?$.map(X=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{R(Z=>({...Z,contact_id:X.id})),v(`${X.first_name} ${X.last_name}`),b(!1)},children:[e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[X.first_name," ",X.last_name]}),X.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:X.email})]},X.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 X=y.trim().split(/\s+/);A({first_name:X[0]||"",last_name:X.slice(1).join(" ")||"",email:"",phone:""}),S(!0),b(!1)},children:[e.jsx(sl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',y.trim(),'"']})]})]})]}),N&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(sl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(G,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>S(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{placeholder:"First name *",value:T.first_name,onChange:X=>A(Z=>({...Z,first_name:X.target.value})),className:"h-8 text-sm"}),e.jsx(Ne,{placeholder:"Last name",value:T.last_name,onChange:X=>A(Z=>({...Z,last_name:X.target.value})),className:"h-8 text-sm"}),e.jsx(Ne,{placeholder:"Email",type:"email",value:T.email,onChange:X=>A(Z=>({...Z,email:X.target.value})),className:"h-8 text-sm"}),e.jsx(Ne,{placeholder:"Phone",type:"tel",value:T.phone,onChange:X=>A(Z=>({...Z,phone:X.target.value})),className:"h-8 text-sm"})]}),e.jsx(G,{type:"button",size:"sm",className:"w-full h-8",disabled:!T.first_name.trim()||o.isPending,onClick:async()=>{try{const X=await o.mutateAsync({first_name:T.first_name.trim(),last_name:T.last_name.trim()||null,email:T.email.trim()||null,phone:T.phone.trim()||null});X&&(R(Z=>({...Z,contact_id:X.id})),v(`${X.first_name} ${X.last_name||""}`.trim()),S(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(sl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),I.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"flex items-center gap-2",children:[e.jsx(tl,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(Is,{value:D.listing_id||"none",onValueChange:X=>{const Z=X==="none"?"":X,re=I.find(le=>le.id===Z);R(re?le=>{var oe;return{...le,listing_id:Z,deal_type:"seller",property_address:re.property_address||le.property_address,city:re.city||le.city,state:re.state||le.state,expected_price:((oe=re.price)==null?void 0:oe.toString())||le.expected_price}}:le=>({...le,listing_id:Z}))},children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a listing to sync status..."})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"None"}),I.map(X=>e.jsx(ct,{value:X.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:X.property_address||`${X.city}, ${X.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(X.price/1e3).toFixed(0),"K"]})]})},X.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(he,{htmlFor:"property_address",children:"Address"}),e.jsx(Ne,{id:"property_address",value:D.property_address,onChange:X=>R(Z=>({...Z,property_address:X.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:D.city,onChange:X=>R(Z=>({...Z,city:X.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:D.state,onChange:X=>R(Z=>({...Z,state:X.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(Ne,{id:"zip_code",value:D.zip_code,onChange:X=>R(Z=>({...Z,zip_code:X.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(he,{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(Ne,{id:"expected_price",type:"number",value:D.expected_price,onChange:X=>R(Z=>({...Z,expected_price:X.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:X=>R(Z=>({...Z,commission_percentage:X.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(he,{children:"Expected GCI"}),e.jsx(Ne,{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(he,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(Is,{value:D.commission_calc_method,onValueChange:X=>R(Z=>({...Z,commission_calc_method:X})),children:[e.jsx(As,{className:"h-7 text-xs",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(ct,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:X=>R(Z=>({...Z,brokerage_split_pct:X.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(he,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:X=>R(Z=>({...Z,team_split_pct:X.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(he,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:X=>R(Z=>({...Z,referral_fee_pct:X.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(he,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:X=>R(Z=>({...Z,franchise_fee_pct:X.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(he,{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(Ne,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:X=>R(Z=>({...Z,transaction_fee:X.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(he,{className:"text-xs",children:"Net to Agent"}),e.jsx(Ne,{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(he,{children:"Target Close Date"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal",!D.target_close_date&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),D.target_close_date?_s(D.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:D.target_close_date,onSelect:X=>R(Z=>({...Z,target_close_date:X})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Contract Date"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal",!D.contract_date&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),D.contract_date?_s(D.contract_date,"PPP"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:D.contract_date,onSelect:X=>R(Z=>({...Z,contract_date:X})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(he,{children:"Listing Date (for Days on Market)"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal",!D.listing_date&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),D.listing_date?_s(D.listing_date,"PPP"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:D.listing_date,onSelect:X=>R(Z=>({...Z,listing_date:X})),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(he,{children:"Priority"}),e.jsxs(Is,{value:D.priority,onValueChange:X=>R(Z=>({...Z,priority:X})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:KMs.map(X=>e.jsx(ct,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ne,{type:"number",min:"0",max:"100",value:D.probability,onChange:X=>R(Z=>({...Z,probability:X.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(he,{htmlFor:"notes",children:"Notes"}),e.jsx(or,{id:"notes",value:D.notes,onChange:X=>R(Z=>({...Z,notes:X.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!r&&e.jsx(GMs,{formData:m,onChange:x}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{type:"submit",disabled:K,children:[K&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Update Deal":"Create Deal"]})]})]})]})})}function ZMs({dealId:s}){const t=sa(),r=Xt(),[n,a]=k.useState(""),[i,l]=k.useState(!1),{data:o=[]}=mt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:v,error:w}=await V.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(w)throw w;return v},enabled:!!s}),{data:c=[]}=mt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:v,error:w}=await V.from("deal_tags").select("tag").eq("owner_user_id",t);if(w)throw w;return[...new Set(v.map(N=>N.tag))].sort()},enabled:!!t}),d=Ct({mutationFn:async v=>{if(!t)throw new Error("Not authenticated");const{error:w}=await V.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:v.trim()});if(w)throw w},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]}),r.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),h=Ct({mutationFn:async v=>{const{error:w}=await V.from("deal_tags").delete().eq("id",v);if(w)throw w},onSuccess:()=>{r.invalidateQueries({queryKey:["deal-tags",s]})}}),m=()=>{const v=n.trim();v&&(o.some(w=>w.tag.toLowerCase()===v.toLowerCase())||d.mutate(v))},x=o.map(v=>v.tag.toLowerCase()),y=c.filter(v=>v.toLowerCase().includes(n.toLowerCase())&&!x.includes(v.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(v=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 text-xs",children:[v.tag,e.jsx("button",{type:"button",onClick:()=>h.mutate(v.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(vr,{className:"h-3 w-3"})})]},v.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($s,{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(Ne,{value:n,onChange:v=>a(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),m()),v.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:m,disabled:!n.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"})]}),n&&y.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:y.map(v=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:w=>{w.preventDefault(),d.mutate(v)},children:v},v))})]})]})}function XMs(s){return mt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:r}=await V.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function QMs(){const s=sa(),t=Xt();return Ct({mutationFn:async({dealId:r,file:n})=>{if(!s)throw new Error("Not authenticated");const a=n.name.split(".").pop(),i=`${s}/${r}/${crypto.randomUUID()}.${a}`,{error:l}=await V.storage.from("deal-files").upload(i,n);if(l)throw l;const{data:o,error:c}=await V.from("deal_files").insert({deal_id:r,owner_user_id:s,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["deal-files",n.dealId]})}})}function JMs(){const s=Xt();return Ct({mutationFn:async({fileId:t,storagePath:r,dealId:n})=>{await V.storage.from("deal-files").remove([r]);const{error:a}=await V.from("deal_files").delete().eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function eIs(){const s=Xt();return Ct({mutationFn:async({fileId:t,visible:r,dealId:n})=>{const{error:a}=await V.from("deal_files").update({visible_on_portal:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function tIs(s){const{data:t,error:r}=await V.storage.from("deal-files").createSignedUrl(s,3600);if(r)throw r;return t.signedUrl}const $qe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function hpt({open:s,onOpenChange:t}){const{data:r,isLoading:n}=Q5s(),a=J5s(),i=eTs(),l=tTs(),[o,c]=k.useState(!1),[d,h]=k.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[m,x]=k.useState(""),y=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:((r==null?void 0:r.length)||0)+1}),h({question_text:"",field_type:"text",options:[],is_required:!1}),x(""),c(!1),ue.success("Question added")}catch{ue.error("Failed to add question")}},v=async S=>{try{await l.mutateAsync(S),ue.success("Question removed")}catch{ue.error("Failed to remove question")}},w=async(S,T)=>{try{await i.mutateAsync({id:S,is_required:T})}catch{ue.error("Failed to update question")}},b=()=>{m.trim()&&(h(S=>({...S,options:[...S.options,m.trim()]})),x(""))},N=S=>{h(T=>({...T,options:T.options.filter((A,I)=>I!==S)}))};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsx(gs,{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(Qa,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[n&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),r==null?void 0:r.map(S=>{var T;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(vu,{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:S.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"secondary",className:"text-xs",children:$qe[S.field_type]||S.field_type}),S.is_required&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Required"})]}),S.field_type==="dropdown"&&((T=S.options)==null?void 0:T.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",S.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(_r,{checked:S.is_required,onCheckedChange:A=>w(S.id,A),className:"scale-75"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>v(S.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})},S.id)}),!n&&(r==null?void 0:r.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(he,{className:"text-sm font-medium",children:"Question"}),e.jsx(Ne,{value:d.question_text,onChange:S=>h(T=>({...T,question_text:S.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries($qe).map(([S,T])=>e.jsx("button",{type:"button",onClick:()=>h(A=>({...A,field_type:S,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===S?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:T},S))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((S,T)=>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:S}),e.jsx("button",{onClick:()=>N(T),className:"text-muted-foreground hover:text-destructive",children:e.jsx(vr,{className:"h-3.5 w-3.5"})})]},T)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:m,onChange:S=>x(S.target.value),onKeyDown:S=>S.key==="Enter"&&(S.preventDefault(),b()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(G,{variant:"outline",size:"sm",onClick:b,disabled:!m.trim(),className:"h-8",children:e.jsx($s,{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(_r,{checked:d.is_required,onCheckedChange:S=>h(T=>({...T,is_required:S}))}),e.jsx(he,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(G,{size:"sm",onClick:y,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(es,{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(G,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function sIs({override:s,onChange:t}){const r=sa(),{data:n}=Est(),[a,i]=k.useState(null),l=d=>t({...s,...d}),o=async(d,h)=>{if(r){if(d.size>5*1024*1024){ue.error("Image must be under 5MB");return}i(h);try{const m=await Ast(r,d,`${h}`);l(h==="logo"?{logo_url:m}:{cover_photo_url:m})}catch(m){ue.error(`Upload failed: ${m.message||m}`)}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(jr,{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(Uqe,{label:"Logo",value:s.logo_url??null,globalValue:(n==null?void 0:n.logo_url)??null,uploading:a==="logo",onUpload:d=>o(d,"logo"),onClear:()=>l({logo_url:null}),aspect:"square"}),e.jsx(Uqe,{label:"Cover Photo",value:s.cover_photo_url??null,globalValue:(n==null?void 0:n.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(qqe,{label:"Brand Color",value:s.brand_color??null,globalValue:(n==null?void 0:n.brand_color)??null,onChange:d=>l({brand_color:d})}),e.jsx(qqe,{label:"Accent Color",value:s.accent_color??null,globalValue:(n==null?void 0:n.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(Ne,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(n==null?void 0:n.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(yr,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function Uqe({label:s,value:t,globalValue:r,uploading:n,onUpload:a,onClear:i,aspect:l}){const o=t||r,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(he,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):r?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:It("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(ml,{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 m;const h=(m=d.target.files)==null?void 0:m[0];h&&a(h),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:[n?e.jsx(es,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(da,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(G,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})}function qqe({label:s,value:t,globalValue:r,onChange:n}){const a=t||r||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{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:It("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=>n(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(Ne,{value:t||"",onChange:l=>n(l.target.value||null),placeholder:r||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>n(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(yr,{className:"h-3 w-3"})})]})]})}function rIs({portalId:s,ownerId:t,clientEmail:r,linkedPortalId:n,onLink:a}){const[i,l]=k.useState(""),[o,c]=k.useState(!1),{data:d,isLoading:h}=mt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:v,error:w}=await V.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(w)throw w;return v},enabled:o||!!n}),m=k.useMemo(()=>!n||!d?null:d.find(v=>v.id===n),[n,d]),x=k.useMemo(()=>!d||!r?[]:d.filter(v=>{var w;return((w=v.client_email)==null?void 0:w.toLowerCase())===r.toLowerCase()&&v.id!==s}),[d,r,s]),y=k.useMemo(()=>{if(!d||!i.trim())return[];const v=i.toLowerCase();return d.filter(w=>{var N,S,T,A;const b=w.deal_pipeline;return((N=w.client_name)==null?void 0:N.toLowerCase().includes(v))||((S=w.client_email)==null?void 0:S.toLowerCase().includes(v))||((T=b==null?void 0:b.deal_name)==null?void 0:T.toLowerCase().includes(v))||((A=b==null?void 0:b.property_address)==null?void 0:A.toLowerCase().includes(v))})},[d,i]);if(n){const v=m==null?void 0:m.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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(tl,{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:(m==null?void 0:m.client_name)||(v==null?void 0:v.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(v==null?void 0:v.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(v==null?void 0:v.property_address)||"No address"]})]}),e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(n3,{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(he,{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(G,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(tl,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&x.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)"}),x.map(v=>{const w=v.deal_pipeline;return e.jsxs("button",{onClick:()=>a(v.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(Ge,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(w==null?void 0:w.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:(w==null?void 0:w.deal_name)||v.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:w==null?void 0:w.property_address})]}),e.jsx(tl,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},v.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:i,onChange:v=>l(v.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),h&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(es,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),y.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:y.map(v=>{const w=v.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(v.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(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:(w==null?void 0:w.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:(w==null?void 0:w.deal_name)||v.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:v.client_email})]})]},v.id)})}),i&&y.length===0&&!h&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function REe({contactId:s,onVideoReady:t}){const[r,n]=k.useState(!1),[a,i]=k.useState("record"),[l,o]=k.useState(0),[c,d]=k.useState(0),h=Yb(),m=()=>{i("record"),o(0),d(0)},x=v=>{!v&&(a==="uploading"||a==="processing")||(n(v),v||m())},y=k.useCallback(async(v,w)=>{i("uploading");try{const b="Card Video",{videoId:N,libraryId:S}=await h5(b),{uploadUrl:T,apiKey:A}=await m5(N),I=new XMLHttpRequest;I.upload.onprogress=K=>{K.lengthComputable&&o(K.loaded/K.total*100)},await new Promise((K,X)=>{I.onload=()=>I.status>=200&&I.status<300?K():X(new Error("Upload failed")),I.onerror=()=>X(new Error("Upload failed")),I.open("PUT",T),I.setRequestHeader("AccessKey",A),I.send(v)}),i("processing");let D=0;const R=Date.now(),$=9e4,F=`https://iframe.mediadelivery.net/embed/${S}/${N}`;for(;D<4;){if(await new Promise(X=>setTimeout(X,3e3)),Date.now()-R>$){const X=v.size/1048576;await h.mutateAsync({bunny_video_id:N,playback_url:`https://iframe.mediadelivery.net/play/${S}/${N}`,file_size_mb:X,title:b,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(F),ue.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{n(!1),m()},1500);return}const K=await Ev(N);if(D=K.status,d(K.encodeProgress||0),D===5||D===6)throw new Error("Video processing failed")}const z=await Ev(N),Q=(z.storageSize||v.size)/(1024*1024);await h.mutateAsync({bunny_video_id:N,contact_id:s||void 0,playback_url:z.directPlayUrl||F,thumbnail_url:z.thumbnailUrl,preview_url:z.previewUrl||null,duration_seconds:z.length||w,file_size_mb:Q,title:b,status:"ready",touch_type:"video"}),t(F),ue.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{n(!1),m()},1500)}catch(b){console.error("Recording upload error:",b),ue.error("Failed to process video. Please try again."),i("record")}},[s,t,h]);return e.jsxs(fs,{open:r,onOpenChange:x,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(ms,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(IL,{maxDurationSeconds:600,onRecordingComplete:y,onError:v=>ue.error(v)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(es,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ei,{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(es,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ei,{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(di,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const nIs=s=>`portal-settings-draft:${s}`;function OEe({open:s,onOpenChange:t,portal:r,dealOwnerId:n}){const a=vL(),[i,l]=k.useState(!1),o=k.useMemo(()=>nIs(r.id),[r.id]),[c,d]=k.useState(!1),[h,m]=k.useState(r.next_step_text||""),[x,y]=k.useState(r.next_step_video_url||""),[v,w]=k.useState(r.inspection_date||""),[b,N]=k.useState(r.appraisal_date||""),[S,T]=k.useState(r.welcome_message||""),[A,I]=k.useState(r.review_url||""),[D,R]=k.useState(r.show_post_close_tips),[$,F]=k.useState(r.notify_client),[z,Q]=k.useState(r.require_onboarding),[K,X]=k.useState(r.allow_spouse),[Z,re]=k.useState(r.visibility),[le,oe]=k.useState(r.stage_mapping||[]),[ne,ie]=k.useState(null),[ye,ce]=k.useState(r.linked_portal_id||null),[ve,be]=k.useState(r.referral_enabled??!0),[Ue,Be]=k.useState(r.referral_reward_text||""),[De,Ae]=k.useState(r.referral_cta_headline||""),[He,Le]=k.useState(r.homeowner_hub_video_url||""),[Ie,Te]=k.useState(r.branding_override||{}),xe=()=>{m(r.next_step_text||""),y(r.next_step_video_url||""),w(r.inspection_date||""),N(r.appraisal_date||""),T(r.welcome_message||""),I(r.review_url||""),R(r.show_post_close_tips),F(r.notify_client),Q(r.require_onboarding),X(r.allow_spouse),re(r.visibility),oe(r.stage_mapping||[]),ce(r.linked_portal_id||null),be(r.referral_enabled??!0),Be(r.referral_reward_text||""),Ae(r.referral_cta_headline||""),Le(r.homeowner_hub_video_url||""),Te(r.branding_override||{})};k.useEffect(()=>{d(!1);const _e=localStorage.getItem(o);if(_e)try{const Re=JSON.parse(_e);m(Re.nextStepText||""),y(Re.nextStepVideo||""),w(Re.inspectionDate||""),N(Re.appraisalDate||""),T(Re.welcomeMessage||""),I(Re.reviewUrl||""),R(!!Re.showPostClose),F(!!Re.notifyClient),Q(!!Re.requireOnboarding),X(!!Re.allowSpouse),re(Re.visibility||r.visibility),oe(Re.stageMapping||[]),ce(Re.linkedPortalId??null),be(Re.referralEnabled??!0),Be(Re.referralRewardText||""),Ae(Re.referralCtaHeadline||""),Le(Re.homeownerHubVideoUrl||""),Te(Re.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}xe(),d(!0)},[o,r]),k.useEffect(()=>{if(!c)return;const _e={nextStepText:h,nextStepVideo:x,inspectionDate:v,appraisalDate:b,welcomeMessage:S,reviewUrl:A,showPostClose:D,notifyClient:$,requireOnboarding:z,allowSpouse:K,visibility:Z,stageMapping:le,linkedPortalId:ye,referralEnabled:ve,referralRewardText:Ue,referralCtaHeadline:De,homeownerHubVideoUrl:He,brandingOverride:Ie};h!==(r.next_step_text||"")||x!==(r.next_step_video_url||"")||v!==(r.inspection_date||"")||b!==(r.appraisal_date||"")||S!==(r.welcome_message||"")||A!==(r.review_url||"")||D!==r.show_post_close_tips||$!==r.notify_client||z!==r.require_onboarding||K!==r.allow_spouse||Z!==r.visibility||JSON.stringify(le)!==JSON.stringify(r.stage_mapping||[])||ye!==(r.linked_portal_id||null)||ve!==(r.referral_enabled??!0)||Ue!==(r.referral_reward_text||"")||De!==(r.referral_cta_headline||"")||He!==(r.homeowner_hub_video_url||"")||JSON.stringify(Ie)!==JSON.stringify(r.branding_override||{})?localStorage.setItem(o,JSON.stringify(_e)):localStorage.removeItem(o)},[h,x,v,b,S,A,D,$,z,K,Z,le,ye,ve,Ue,De,He,Ie,o,c,r]);const et=()=>{localStorage.removeItem(o),xe()},fe=async()=>{try{await a.mutateAsync({id:r.id,next_step_text:h||null,next_step_video_url:x||null,inspection_date:v||null,appraisal_date:b||null,welcome_message:S||null,review_url:A||null,show_post_close_tips:D,notify_client:$,require_onboarding:z,allow_spouse:K,visibility:Z,stage_mapping:le.length>0?le:null,linked_portal_id:ye,referral_enabled:ve,referral_reward_text:Ue||null,referral_cta_headline:De||null,homeowner_hub_video_url:He||null,branding_override:Object.values(Ie).some(Re=>Re!=null&&Re!=="")?Ie:null});const _e=r.linked_portal_id;ye&&ye!==_e&&await V.from("client_portals").update({linked_portal_id:r.id}).eq("id",ye),!ye&&_e&&await V.from("client_portals").update({linked_portal_id:null}).eq("id",_e),localStorage.removeItem(o),ue.success("Portal settings saved"),t(!1)}catch{ue.error("Failed to save settings")}},it=()=>{oe([...le,{label:""}])},Oe=_e=>{oe(le.filter((Re,tt)=>tt!==_e)),ne===_e&&ie(null)},Ye=(_e,Re,tt)=>{const Ke=[...le];Ke[_e]={...Ke[_e],[Re]:tt},oe(Ke)},We=()=>{const Re=Efe(null).map(tt=>({label:tt.label,description:tt.description,stageId:void 0}));oe(Re)};return e.jsxs(e.Fragment,{children:[e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Portal Settings"})}),e.jsxs(On,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rn,{className:"grid grid-cols-4 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:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(ts,{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(he,{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(_e=>e.jsx("button",{onClick:()=>re(_e),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${Z===_e?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:_e.charAt(0).toUpperCase()+_e.slice(1)},_e))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:z,onCheckedChange:Q})]}),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(he,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(G,{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(he,{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(_r,{checked:K,onCheckedChange:X})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:D,onCheckedChange:R})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:$,onCheckedChange:F})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(rIs,{portalId:r.id,ownerId:n,clientEmail:r.client_email,linkedPortalId:ye,onLink:ce})}),e.jsx("div",{children:e.jsx(Ne,{type:"date",value:v,onChange:_e=>w(_e.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(Ne,{type:"date",value:b,onChange:_e=>N(_e.target.value),className:"mt-1"})]})]}),e.jsx(ts,{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(he,{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(G,{variant:"outline",size:"sm",onClick:We,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.'}),le.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(G,{variant:"outline",size:"sm",onClick:We,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:le.map((_e,Re)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vu,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(Ne,{value:_e.label,onChange:tt=>Ye(Re,"label",tt.target.value),placeholder:`Stage ${Re+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ie(ne===Re?null:Re),children:ne===Re?"Less":"More"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Oe(Re),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),ne===Re&&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(he,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:_e.description||"",onChange:tt=>Ye(Re,"description",tt.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(he,{className:"text-xs text-muted-foreground",children:"Video"}),_e.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:_e.video_url.length>40?_e.video_url.slice(0,40)+"...":_e.video_url}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Ye(Re,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(REe,{onVideoReady:tt=>Ye(Re,"video_url",tt)}),e.jsx(yL,{userId:n,onSelect:tt=>Ye(Re,"video_url",tt),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const tt=prompt("Paste a YouTube or Loom URL:");tt&&Ye(Re,"video_url",tt)},children:[e.jsx(po,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Re))}),le.length>0&&e.jsxs(G,{variant:"outline",size:"sm",onClick:it,className:"mt-2 text-xs w-full",children:[e.jsx($s,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(ts,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:S,onChange:_e=>T(_e.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(he,{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:h,onChange:_e=>m(_e.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(he,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(Ne,{value:x,onChange:_e=>y(_e.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:A,onChange:_e=>I(_e.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(he,{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(he,{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(_r,{checked:ve,onCheckedChange:be})]}),ve&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Headline"}),e.jsx(Ne,{value:De,onChange:_e=>Ae(_e.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:Ue,onChange:_e=>Be(_e.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:He,onChange:_e=>Le(_e.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(ts,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(sIs,{override:Ie,onChange:Te})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(G,{variant:"ghost",onClick:et,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(G,{onClick:fe,disabled:a.isPending,children:[a.isPending?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bl,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(hpt,{open:i,onOpenChange:l})]})}const aIs=s=>`portal-update-draft:${s}`;function FEe({open:s,onOpenChange:t,portalId:r,portalSlug:n,notifyClient:a}){const i=k.useMemo(()=>aIs(r),[r]),[l,o]=k.useState(""),[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState(!1),[v,w]=k.useState(a??!1),[b,N]=k.useState(!1),S=qht();k.useEffect(()=>{N(!1);const I=localStorage.getItem(i);if(I)try{const D=JSON.parse(I);o(D.title||""),d(D.content||""),m(D.videoUrl||""),y(!!D.isStageChange),w(typeof D.sendNotification=="boolean"?D.sendNotification:a??!1),N(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),m(""),y(!1),w(a??!1),N(!0)},[i,a]),k.useEffect(()=>{if(!b)return;const I={title:l,content:c,videoUrl:h,isStageChange:x,sendNotification:v};l.trim()||c.trim()||h.trim()||x||v!==(a??!1)?localStorage.setItem(i,JSON.stringify(I)):localStorage.removeItem(i)},[l,c,h,x,v,b,i,a]);const T=()=>{localStorage.removeItem(i),o(""),d(""),m(""),y(!1),w(a??!1)},A=async()=>{if(l.trim())try{if(await S.mutateAsync({portal_id:r,title:l.trim(),content:c.trim()||void 0,video_url:h.trim()||void 0,is_stage_change:x}),v&&n)try{const I=yv(n);await V.functions.invoke("send-portal-notification",{body:{portal_id:r,update_title:l.trim(),update_content:c.trim()||null,portal_url:I}}),ue.success("Update posted & client notified")}catch(I){console.error("Notification failed:",I),ue.success("Update posted (notification failed to send)")}else ue.success("Update posted to portal");T(),t(!1)}catch{ue.error("Failed to post update")}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Title *"}),e.jsx(Ne,{value:l,onChange:I=>o(I.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:I=>d(I.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(he,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(Ne,{value:h,onChange:I=>m(I.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(Jr,{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:()=>y(!x),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${x?"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:()=>w(!v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${v?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[v?e.jsx(_m,{className:"h-3 w-3"}):e.jsx(ev,{className:"h-3 w-3"}),v?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(G,{variant:"ghost",onClick:T,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(G,{onClick:A,disabled:!l.trim()||S.isPending,children:[S.isPending?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(en,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function BEe({open:s,onOpenChange:t,portal:r,dealName:n}){const a=vL(),{isGmailConnected:i,gmailEmail:l}=Eh(),[o,c]=k.useState(r.client_name||""),[d,h]=k.useState(r.client_email||""),[m,x]=k.useState(!1),[y,v]=k.useState(!1),w=yv(r.slug),b=o.split(" ")[0]||"there",N=`Your Transaction Portal – ${n}`,S=`Hi ${b}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${w} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,T=()=>{navigator.clipboard.writeText(w),v(!0),setTimeout(()=>v(!1),2e3),ue.success("Portal link copied!")},A=async()=>{if(!d.trim()){ue.error("Please enter the client email");return}x(!0);try{await a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:D}=await V.functions.invoke("gmail-send",{body:{to:d,subject:N,body:S.replace(/\n/g,"
")}});if(D){let R="";try{const $=D==null?void 0:D.context;if($&&typeof $.json=="function"){const F=await $.json();R=(F==null?void 0:F.message)||(F==null?void 0:F.error)||""}}catch{}throw new Error(R||D.message||"Failed to send invite")}ue.success(`Invite sent to ${d}`),t(!1)}catch(D){ue.error(D.message||"Failed to send invite")}finally{x(!1)}},I=()=>{const D=encodeURIComponent(N),R=encodeURIComponent(S);window.open(`mailto:${d}?subject=${D}&body=${R}`,"_blank"),a.mutateAsync({id:r.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(Ne,{value:o,onChange:D=>c(D.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(Ne,{type:"email",value:d,onChange:D=>h(D.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(he,{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:w})}),e.jsx(G,{variant:"outline",size:"icon",onClick:T,className:"shrink-0",children:y?e.jsx(Kn,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Ra,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(G,{onClick:A,disabled:m||!d.trim(),className:"w-full",children:[m?e.jsx(es,{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(G,{onClick:I,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(G,{variant:"ghost",onClick:T,className:"w-full text-muted-foreground",children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function iIs({deal:s}){const{isAdmin:t,user:r}=js(),{data:n,isLoading:a}=Z5s(s.id),i=RTe(),l=vL(),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[y,v]=k.useState(!1),w=`portal-management-ui:${s.id}`;if(k.useEffect(()=>{const D=sessionStorage.getItem(w);if(D)try{const R=JSON.parse(D);h(!!R.settingsOpen),x(!!R.composerOpen),v(!!R.inviteOpen)}catch{sessionStorage.removeItem(w)}},[w]),k.useEffect(()=>{d||m||y?sessionStorage.setItem(w,JSON.stringify({settingsOpen:d,composerOpen:m,inviteOpen:y})):sessionStorage.removeItem(w)},[d,m,y,w]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(es,{className:"h-3 w-3 animate-spin ml-auto"})]})});const b=async()=>{var D,R;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:((D=s.contact)==null?void 0:D.email)||void 0,client_phone:((R=s.contact)==null?void 0:R.phone)||void 0}),ue.success("Client portal enabled!")}catch{ue.error("Failed to create portal")}finally{c(!1)}},N=async D=>{if(n)try{await l.mutateAsync({id:n.id,is_enabled:D}),ue.success(D?"Portal enabled":"Portal disabled")}catch{ue.error("Failed to update portal")}},S=()=>{if(!n)return;const D=yv(n.slug);navigator.clipboard.writeText(D),ue.success("Portal link copied!")},T=()=>{if(!n)return;const D=yv(n.slug);window.open(D,"_blank")};if(!n)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(jr,{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(G,{onClick:b,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(jr,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=yv(n.slug),I=(r==null?void 0:r.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(jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ge,{variant:"outline",className:n.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"})]}),e.jsx(_r,{checked:n.is_enabled,onCheckedChange:N})]}),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(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:n.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:n.require_onboarding?"Required":"Disabled"})]}),n.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:n.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(G,{variant:"outline",size:"sm",onClick:S,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Ra,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:T,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Qr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>v(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(en,{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(G,{variant:"ghost",size:"sm",onClick:()=>x(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(V0,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>h(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(oo,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Yn,{to:"/mission-control/portal-referrals",className:"mt-2 flex items-center justify-center gap-1.5 text-[11px] text-muted-foreground hover:text-primary transition-colors py-1.5",children:[e.jsx(ii,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(OEe,{open:d,onOpenChange:h,portal:n,dealOwnerId:I}),e.jsx(FEe,{open:m,onOpenChange:x,portalId:n.id,portalSlug:n.slug,notifyClient:n.notify_client}),e.jsx(BEe,{open:y,onOpenChange:v,portal:n,dealName:s.deal_name})]})}const oIs=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function lIs(s){return mt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:r}=await V.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(r)throw r;return t||[]},enabled:!!s})}function cIs(){const s=Xt();return Ct({mutationFn:async({dealId:t,contactId:r,role:n})=>{const{data:a,error:i}=await V.from("deal_contacts").insert({deal_id:t,contact_id:r,role:n}).select().single();if(i)throw i;return a},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),ue.success("Contact linked to deal")},onError:t=>{var r;(r=t.message)!=null&&r.includes("duplicate")?ue.error("This contact is already linked to this deal"):ue.error("Failed to link contact")}})}function dIs(){const s=Xt();return Ct({mutationFn:async({id:t,dealId:r})=>{const{error:n}=await V.from("deal_contacts").delete().eq("id",t);if(n)throw n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["deal-contacts",r.dealId]}),ue.success("Contact removed from deal")},onError:()=>{ue.error("Failed to remove contact")}})}function uIs({dealId:s,primaryContactId:t}){const r=br(),{data:n,isLoading:a}=lIs(s),{data:i}=Sm(),l=cIs(),o=dIs(),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,y]=k.useState("Client"),v=new Set((n==null?void 0:n.map(T=>T.contact_id))||[]);t&&v.add(t);const w=i==null?void 0:i.filter(T=>{var I,D,R;if(v.has(T.id))return!1;if(!h.trim())return!0;const A=h.toLowerCase();return((I=T.first_name)==null?void 0:I.toLowerCase().includes(A))||((D=T.last_name)==null?void 0:D.toLowerCase().includes(A))||((R=T.email)==null?void 0:R.toLowerCase().includes(A))}).slice(0,8),b=T=>{l.mutate({dealId:s,contactId:T,role:x}),d(!1),m("")},N=T=>{o.mutate({id:T,dealId:s})},S={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!(n!=null&&n.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(pr,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(To,{open:c,onOpenChange:d,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(_o,{className:"w-80 p-3",align:"start",children:e.jsx(Vqe,{search:h,setSearch:m,selectedRole:x,setSelectedRole:y,filteredContacts:w,onAdd:b})})]})]}):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(pr,{className:"h-4 w-4"}),"Linked Contacts",n&&n.length>0&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] px-1.5",children:n.length})]}),e.jsxs(To,{open:c,onOpenChange:d,children:[e.jsx(Eo,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx($s,{className:"h-3.5 w-3.5"})})}),e.jsx(_o,{className:"w-80 p-3",align:"end",children:e.jsx(Vqe,{search:h,setSearch:m,selectedRole:x,setSelectedRole:y,filteredContacts:w,onAdd:b})})]})]}),e.jsx("div",{className:"space-y-1.5",children:n==null?void 0:n.map(T=>{var A,I,D,R,$,F,z,Q;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Nn,{className:"h-7 w-7",children:e.jsxs(kn,{className:"text-[10px] bg-primary/10 text-primary",children:[(I=(A=T.contact)==null?void 0:A.first_name)==null?void 0:I[0],(R=(D=T.contact)==null?void 0:D.last_name)==null?void 0:R[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>r(`/mission-control/contacts/${T.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[($=T.contact)==null?void 0:$.first_name," ",(F=T.contact)==null?void 0:F.last_name]})}),e.jsx(Ge,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${S[T.role]||S.Other}`,children:T.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((z=T.contact)==null?void 0:z.phone)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${T.contact.phone}`,children:e.jsx(Cn,{className:"h-3 w-3"})})}),((Q=T.contact)==null?void 0:Q.email)&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${T.contact.email}`,children:e.jsx(Vs,{className:"h-3 w-3"})})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>N(T.id),children:e.jsx(yr,{className:"h-3 w-3"})})]})]},T.id)})})]})}function Vqe({search:s,setSearch:t,selectedRole:r,setSelectedRole:n,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Is,{value:r,onValueChange:n,children:[e.jsx(As,{className:"h-8 text-sm",children:e.jsx(Ls,{placeholder:"Role"})}),e.jsx(Ms,{children:oIs.map(l=>e.jsx(ct,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ne,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Qa,{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 hIs={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"}},mIs={note:xi,call:Cn,email:Vs,meeting:on,stage_change:Qr,task_completed:In,document:En,system:fn};function fIs({deal:s,open:t,onOpenChange:r,onEdit:n,onAddToScorecard:a,isWonStage:i}){var Ae,He;const{data:l,isLoading:o}=lEs((s==null?void 0:s.id)||""),{data:c,isLoading:d}=dEs((s==null?void 0:s.id)||""),h=cEs(),m=hEs(),x=uEs(),y=oEs(),{data:v,isLoading:w}=XMs((s==null?void 0:s.id)||""),b=QMs(),N=JMs(),S=eIs(),T=k.useRef(null),[A,I]=k.useState(""),[D,R]=k.useState(""),[$,F]=k.useState(!1),[z,Q]=k.useState(!1);if(!s)return null;const K=hIs[s.deal_type],X=(()=>{var Te;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Le=((Te=s.listing)==null?void 0:Te.created_at)||s.listing_date;if(!Le)return null;const Ie=s.contract_date?Fl(s.contract_date):new Date;return pg(Ie,Fl(Le))})(),Z=Le=>Le?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Le):"-",re=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),I(""),ue.success("Note added")}catch{ue.error("Failed to add note")}},le=async()=>{if(D.trim())try{await m.mutateAsync({deal_id:s.id,title:D,sort_order:((c==null?void 0:c.length)||0)+1}),R(""),ue.success("Task added")}catch{ue.error("Failed to add task")}},oe=async(Le,Ie)=>{try{await x.mutateAsync({id:Le,is_completed:Ie,deal_id:s.id})}catch{ue.error("Failed to update task")}},ne=async()=>{try{await y.mutateAsync(s.id),ue.success("Deal deleted"),r(!1)}catch{ue.error("Failed to delete deal")}},ie=(c==null?void 0:c.filter(Le=>Le.is_completed).length)||0,ye=(c==null?void 0:c.length)||0,ce=(v==null?void 0:v.length)||0,ve=Le=>Le<1024?`${Le} B`:Le<1024*1024?`${(Le/1024).toFixed(1)} KB`:`${(Le/(1024*1024)).toFixed(1)} MB`,be=Le=>Le?Le.startsWith("image/")?ml:Le.includes("pdf")?ln:fA:fA,Ue=async Le=>{const Ie=Le.target.files;if(!(!Ie||!s)){Q(!0);try{for(const Te of Array.from(Ie)){if(Te.size>20*1024*1024){ue.error(`${Te.name} exceeds 20MB limit`);continue}await b.mutateAsync({dealId:s.id,file:Te})}ue.success("File(s) uploaded")}catch{ue.error("Failed to upload file")}finally{Q(!1),T.current&&(T.current.value="")}}},Be=async(Le,Ie)=>{if(s)try{await N.mutateAsync({fileId:Le,storagePath:Ie,dealId:s.id}),ue.success("File deleted")}catch{ue.error("Failed to delete file")}},De=async(Le,Ie)=>{try{const Te=await tIs(Le),xe=document.createElement("a");xe.href=Te,xe.download=Ie,xe.target="_blank",document.body.appendChild(xe),xe.click(),document.body.removeChild(xe)}catch{ue.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(Jj,{open:t,onOpenChange:r,children:e.jsxs(Vb,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(e2,{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(Ge,{variant:"outline",className:It("text-xs",K.color),children:K.label}),e.jsxs(Ge,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(t2,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(ZMs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>n(s),children:e.jsx(sd,{className:"h-4 w-4"})}),e.jsx(G,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>F(!0),children:e.jsx(yr,{className:"h-4 w-4"})})]})]})}),e.jsx(Qa,{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.jsx(Nn,{className:"h-10 w-10",children:e.jsxs(kn,{className:"bg-primary/10 text-primary",children:[(Ae=s.contact.first_name)==null?void 0:Ae[0],(He=s.contact.last_name)==null?void 0:He[0]]})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-medium",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.contact.email})]}),e.jsxs("div",{className:"flex gap-2",children:[s.contact.phone&&e.jsx(G,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Cn,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(G,{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(uIs,{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(En,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.property_address||"Address TBD"}),e.jsx("p",{className:"text-muted-foreground",children:[s.city,s.state,s.zip_code].filter(Boolean).join(", ")})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected Price"}),e.jsx("p",{className:"text-lg font-bold",children:Z(s.expected_price)})]}),e.jsxs("div",{className:"bg-emerald-500/10 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected GCI"}),e.jsx("p",{className:"text-lg font-bold text-emerald-600",children:Z(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee)&&e.jsxs("div",{className:"col-span-2 bg-muted/30 rounded-lg p-3 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Commission Splits"}),s.brokerage_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Brokerage Split"}),e.jsxs("span",{children:[s.brokerage_split_pct,"%",s.expected_commission?` (${Z(s.expected_commission*s.brokerage_split_pct/100)})`:""]})]}),s.team_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Team Split"}),e.jsxs("span",{children:[s.team_split_pct,"%"]})]}),s.referral_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referral Fee"}),e.jsxs("span",{children:[s.referral_fee_pct,"%"]})]}),s.franchise_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Franchise Fee"}),e.jsxs("span",{children:[s.franchise_fee_pct,"%"]})]}),s.transaction_fee!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transaction Fee"}),e.jsx("span",{children:Z(s.transaction_fee)})]}),s.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:Z(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(G,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(Gi,{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(In,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),X!==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:It("text-lg font-bold",X>90?"text-red-600":X>60?"text-amber-600":"text-foreground"),children:[X," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(on,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",_s(Fl(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(wl,{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(iIs,{deal:s}),e.jsxs(On,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Rn,{className:"w-full grid grid-cols-3",children:[e.jsxs(Kt,{value:"tasks",className:"gap-1",children:[e.jsx(In,{className:"h-4 w-4"}),"Tasks ",ye>0&&`(${ie}/${ye})`]}),e.jsxs(Kt,{value:"files",className:"gap-1",children:[e.jsx(nj,{className:"h-4 w-4"}),"Files ",ce>0&&`(${ce})`]}),e.jsxs(Kt,{value:"activity",className:"gap-1",children:[e.jsx(fn,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(ts,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Add a new task...",value:D,onChange:Le=>R(Le.target.value),onKeyDown:Le=>Le.key==="Enter"&&le()}),e.jsx(G,{onClick:le,disabled:!D.trim(),children:e.jsx($s,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[c==null?void 0:c.map(Le=>e.jsxs("div",{className:It("flex items-center gap-3 p-3 rounded-lg border transition-colors",Le.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(Si,{checked:Le.is_completed,onCheckedChange:Ie=>oe(Le.id,!!Ie)}),e.jsx("span",{className:It("flex-1 text-sm",Le.is_completed&&"line-through text-muted-foreground"),children:Le.title}),Le.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:_s(new Date(Le.due_date),"MMM d")})]},Le.id)),(c==null?void 0:c.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(ts,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:T,className:"hidden",multiple:!0,onChange:Ue,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(G,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Le;return(Le=T.current)==null?void 0:Le.click()},disabled:z,children:[z?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-2"}),z?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[v==null?void 0:v.map(Le=>{const Ie=be(Le.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(Ie,{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:Le.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ve(Le.file_size)," · ",_s(new Date(Le.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ub,{children:e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Le.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>S.mutate({fileId:Le.id,visible:!Le.visible_on_portal,dealId:s.id}),children:Le.visible_on_portal?e.jsx(bn,{className:"h-4 w-4"}):e.jsx(Xh,{className:"h-4 w-4"})})}),e.jsx(Gl,{side:"top",children:Le.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>De(Le.storage_path,Le.file_name),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Be(Le.id,Le.storage_path),children:e.jsx(vr,{className:"h-4 w-4"})})]})]},Le.id)}),(v==null?void 0:v.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(ts,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(or,{placeholder:"Add a note...",value:A,onChange:Le=>I(Le.target.value),rows:2}),e.jsxs(G,{onClick:re,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[l==null?void 0:l.map(Le=>{const Ie=mIs[Le.activity_type]||fn;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(Ie,{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:Le.title}),Le.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Le.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:rl(new Date(Le.created_at),{addSuffix:!0})})]})]},Le.id)}),(l==null?void 0:l.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(Ko,{open:$,onOpenChange:F,children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Deal?"}),e.jsxs(Bo,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:ne,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function pIs({open:s,onOpenChange:t,deal:r,onComplete:n}){const a=Vfe(),i=amt(),{data:l}=WI(),{data:o}=fx(),[c,d]=k.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:_s(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});k.useEffect(()=>{if(r&&s){const x=r.deal_type==="seller"?"seller":"buyer",y=r.expected_price||0,v=r.commission_percentage||3,w=r.expected_commission||y*v/100;d({property_address:r.property_address||r.deal_name||"",city:r.city||"",state:r.state||"",zip:r.zip_code||"",transaction_type:x,close_date:r.actual_close_date||r.target_close_date||_s(new Date,"yyyy-MM-dd"),sale_price:y,commission_amount:w,lead_source_id:"",client_type_id:"",notes:r.notes||""})}},[r,s]);const h=async x=>{if(x.preventDefault(),!!r)try{const y=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:r.brokerage_split_pct||null,team_split_pct:r.team_split_pct||null,franchise_fee_pct:r.franchise_fee_pct||null,referral_fee_pct:r.referral_fee_pct||null,transaction_fee:r.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:r.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:r.id,scorecard_transaction_id:y.id,actual_close_date:c.close_date}),ue.success("Deal added to Scorecard! 🎉"),t(!1),n==null||n()}catch(y){console.error("Error syncing to scorecard:",y),ue.error("Failed to add to scorecard")}},m=x=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(x);return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{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(Gi,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(gs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Hr,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(Ne,{id:"property_address",value:c.property_address,onChange:x=>d(y=>({...y,property_address:x.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(he,{htmlFor:"city",children:"City"}),e.jsx(Ne,{id:"city",value:c.city,onChange:x=>d(y=>({...y,city:x.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"state",children:"State"}),e.jsx(Ne,{id:"state",value:c.state,onChange:x=>d(y=>({...y,state:x.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"zip",children:"Zip"}),e.jsx(Ne,{id:"zip",value:c.zip,onChange:x=>d(y=>({...y,zip:x.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(he,{children:"Transaction Type *"}),e.jsxs(Is,{value:c.transaction_type,onValueChange:x=>d(y=>({...y,transaction_type:x})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"buyer",children:"Buyer"}),e.jsx(ct,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(Ne,{id:"close_date",type:"date",value:c.close_date,onChange:x=>d(y=>({...y,close_date:x.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(he,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(Ne,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:x=>d(y=>({...y,sale_price:Number(x.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(Y4,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(Ne,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:x=>d(y=>({...y,commission_amount:Number(x.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Lead Source"}),e.jsxs(Is,{value:c.lead_source_id,onValueChange:x=>d(y=>({...y,lead_source_id:x})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select source"})}),e.jsx(Ms,{children:l==null?void 0:l.map(x=>e.jsx(ct,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Client Type"}),e.jsxs(Is,{value:c.client_type_id,onValueChange:x=>d(y=>({...y,client_type_id:x})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select type"})}),e.jsx(Ms,{children:o==null?void 0:o.map(x=>e.jsx(ct,{value:x.id,children:x.name},x.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"notes",children:"Notes"}),e.jsx(or,{id:"notes",value:c.notes,onChange:x=>d(y=>({...y,notes:x.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(an,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(G,{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(Ha,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const xIs={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"}},Hqe={urgent:0,high:1,medium:2,low:3};function gIs({deals:s,stages:t,onDealClick:r,onStageChange:n}){const[a,i]=k.useState("target_close_date"),[l,o]=k.useState("asc"),c=y=>{a===y?o(v=>v==="asc"?"desc":"asc"):(i(y),o("asc"))},d=k.useMemo(()=>[...s].sort((y,v)=>{var b,N;let w=0;switch(a){case"deal_name":w=y.deal_name.localeCompare(v.deal_name);break;case"stage":{const S=((b=t.find(A=>A.id===y.stage_id))==null?void 0:b.sort_order)||0,T=((N=t.find(A=>A.id===v.stage_id))==null?void 0:N.sort_order)||0;w=S-T;break}case"expected_price":w=(y.expected_price||0)-(v.expected_price||0);break;case"expected_commission":w=(y.expected_commission||0)-(v.expected_commission||0);break;case"target_close_date":{const S=y.target_close_date?Fl(y.target_close_date).getTime():1/0,T=v.target_close_date?Fl(v.target_close_date).getTime():1/0;w=S-T;break}case"priority":w=Hqe[y.priority]-Hqe[v.priority];break}return l==="asc"?w:-w}),[s,t,a,l]),h=y=>y?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(y):"—",m=y=>y?t.find(v=>v.id===y):null,x=({field:y,children:v})=>e.jsxs(G,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(y),children:[v,a===y?l==="asc"?e.jsx(Id,{className:"ml-2 h-4 w-4"}):e.jsx(Hu,{className:"ml-2 h-4 w-4"}):e.jsx(Ad,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{className:"bg-muted/50",children:[e.jsx(Nt,{className:"w-[250px]",children:e.jsx(x,{field:"deal_name",children:"Deal Name"})}),e.jsx(Nt,{className:"w-[150px]",children:e.jsx(x,{field:"stage",children:"Stage"})}),e.jsx(Nt,{className:"w-[100px]",children:"Type"}),e.jsx(Nt,{className:"w-[120px]",children:e.jsx(x,{field:"expected_price",children:"Price"})}),e.jsx(Nt,{className:"w-[120px]",children:e.jsx(x,{field:"expected_commission",children:"GCI"})}),e.jsx(Nt,{className:"w-[130px]",children:e.jsx(x,{field:"target_close_date",children:"Close Date"})}),e.jsx(Nt,{className:"w-[100px]",children:e.jsx(x,{field:"priority",children:"Priority"})})]})}),e.jsx($n,{children:d.map(y=>{m(y.stage_id);const v=xIs[y.deal_type],w=y.target_close_date?pg(Fl(y.target_close_date),new Date):null,b=w!==null&&w<0,N=w!==null&&w<=7&&w>=0;return e.jsxs(Ds,{className:It("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>r(y),children:[e.jsx(dt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:y.deal_name}),y.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[y.contact.first_name," ",y.contact.last_name]})]})}),e.jsx(dt,{onClick:S=>S.stopPropagation(),children:e.jsx(dpt,{stages:t,currentStageId:y.stage_id||"",onStageSelect:(S,T)=>n(y.id,S,T)})}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",className:It("text-xs",v.color),children:v.label})}),e.jsx(dt,{children:e.jsx("span",{className:"font-medium",children:h(y.expected_price)})}),e.jsx(dt,{children:e.jsx("span",{className:"text-emerald-600",children:h(y.expected_commission)})}),e.jsx(dt,{children:y.target_close_date?e.jsxs("div",{className:It("flex items-center gap-1 text-sm",b&&"text-red-600",N&&!b&&"text-amber-600"),children:[b&&e.jsx(Oi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:_s(Fl(y.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",className:It("text-xs capitalize",y.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",y.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",y.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",y.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:y.priority})})]},y.id)})})]})})}function yIs(){const s=sa();return mt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})}function vIs(s){const t=sa();return mt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:r,error:n}=await V.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(n)throw n;return r},enabled:!!t&&!!s})}function bIs(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("deal_tasks").insert({owner_user_id:s,title:r.title,description:r.description||null,deal_id:r.deal_id||null,contact_id:r.contact_id||null,stage_id:r.stage_id||null,priority:r.priority||"medium",status:r.status||"todo",due_date:r.due_date||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function _Is(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("deal_tasks").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function wIs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("deal_tasks").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function zEe(){const s=Xt();return Ct({mutationFn:async({id:t,status:r})=>{const{data:n,error:a}=await V.from("deal_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function jIs(){const s=Xt();return Ct({mutationFn:async t=>{if(t.length===0)return;const{error:r}=await V.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function NIs(s){const t=sa();return mt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let r=V.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(r=r.eq("stage_id",s));const{data:n,error:a}=await r;if(a)throw a;return n},enabled:!!t})}function kIs(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("deal_task_templates").insert({owner_user_id:s,stage_id:r.stage_id,title:r.title,description:r.description||null,priority:r.priority||"medium",default_due_offset_days:r.default_due_offset_days||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function SIs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("deal_task_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function CIs(){const s=sa(),t=Xt();return Ct({mutationFn:async({dealId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",n).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await V.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),o=new Set((l||[]).map(m=>m.title)),c=a.filter(m=>!o.has(m.title)).map((m,x)=>({owner_user_id:s,deal_id:r,stage_id:n,title:m.title,description:m.description,priority:m.priority,due_date:m.default_due_offset_days?new Date(Date.now()+m.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:x,status:"todo"}));if(c.length===0)return[];const{data:d,error:h}=await V.from("deal_tasks").insert(c).select();if(h)throw h;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const TIs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function EIs({open:s,onOpenChange:t,dealId:r,dealName:n,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=vIs(s?r:void 0),h=jIs(),m=CIs(),[x,y]=k.useState(new Set),[v,w]=k.useState(!1),b=(c||[]).filter(A=>A.status!=="done");k.useEffect(()=>{b.length>0&&y(new Set(b.map(A=>A.id)))},[c]);const N=A=>{y(I=>{const D=new Set(I);return D.has(A)?D.delete(A):D.add(A),D})},S=async()=>{w(!0);try{const A=Array.from(x);A.length>0&&await h.mutateAsync(A),await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),ue.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{w(!1)}},T=async()=>{w(!0);try{await o(),await m.mutateAsync({dealId:r,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),ue.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{w(!1)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[480px]",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Move Deal"}),e.jsxs(Hr,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:n})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(Ge,{variant:"outline",className:"text-sm",children:a}),e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ge,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.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:b.length})," incomplete task",b.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(Qa,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:b.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(Si,{checked:x.has(A.id),onCheckedChange:()=>N(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[TIs[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(G,{variant:"ghost",size:"sm",onClick:()=>{x.size===b.length?y(new Set):y(new Set(b.map(A=>A.id)))},children:x.size===b.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:T,disabled:v,children:"Skip"}),e.jsxs(G,{size:"sm",onClick:S,disabled:v,children:[v&&e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}),x.size>0?`Complete ${x.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(In,{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(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:S,disabled:v,children:[v&&e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const AIs=[{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 mpt({open:s,onOpenChange:t}){const r=sa(),{data:n,isLoading:a}=Est(),i=iBt(),[l,o]=k.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=k.useState(null);k.useEffect(()=>{s&&o({logo_url:(n==null?void 0:n.logo_url)??null,cover_photo_url:(n==null?void 0:n.cover_photo_url)??null,brand_color:(n==null?void 0:n.brand_color)??null,accent_color:(n==null?void 0:n.accent_color)??null,tagline:(n==null?void 0:n.tagline)??null,welcome_message:(n==null?void 0:n.welcome_message)??null})},[s,n]);const h=y=>o(v=>({...v,...y})),m=async(y,v)=>{if(r){if(y.size>5*1024*1024){ue.error("Image must be under 5MB");return}d(v);try{const w=await Ast(r,y,v);h(v==="logo"?{logo_url:w}:{cover_photo_url:w})}catch(w){ue.error(`Upload failed: ${w.message||w}`)}finally{d(null)}}},x=async()=>{try{await i.mutateAsync(l),ue.success("Portal branding saved"),t(!1)}catch{ue.error("Failed to save branding")}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Hr,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(Qa,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(MIs,{draft:l}),e.jsx(Gqe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:y=>m(y,"logo"),onClear:()=>h({logo_url:null}),aspect:"square"}),e.jsx(Gqe,{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:y=>m(y,"cover"),onClear:()=>h({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{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:AIs.map(y=>{const v=l.brand_color===y.brand&&l.accent_color===y.accent;return e.jsxs("button",{type:"button",onClick:()=>h({brand_color:y.brand,accent_color:y.accent}),className:It("group relative rounded-lg border-2 p-2 text-left transition-all",v?"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:y.brand}}),e.jsx("div",{className:"flex-1",style:{background:y.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:y.name})]},y.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Wqe,{label:"Brand",value:l.brand_color,onChange:y=>h({brand_color:y})}),e.jsx(Wqe,{label:"Accent",value:l.accent_color,onChange:y=>h({accent_color:y})})]})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:l.tagline||"",onChange:y=>h({tagline:y.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(he,{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:y=>h({welcome_message:y.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(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(G,{onClick:x,disabled:i.isPending,children:[i.isPending?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bl,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function MIs({draft:s}){const t=s.brand_color||"#2a4c64",r=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, ${r}cc), url(${s.cover_photo_url}) center/cover`:`linear-gradient(135deg, ${t}, ${r})`},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 Gqe({label:s,hint:t,value:r,uploading:n,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(he,{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:It("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:r?e.jsx("img",{src:r,alt:s,className:"h-full w-full object-cover"}):e.jsx(ml,{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:[n?e.jsx(es,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(da,{className:"h-3.5 w-3.5"}),r?"Replace":"Upload"]})]}),r&&e.jsx(G,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})}function Wqe({label:s,value:t,onChange:r}){const n=t||"#000000";return e.jsxs("div",{children:[e.jsx(he,{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:n,onChange:a=>r(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(Ne,{value:t||"",onChange:a=>r(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function IIs(){const s=sa();return mt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("client_portals").select("*").eq("owner_user_id",s);if(r)throw r;return t||[]},enabled:!!s})}function LIs({dealId:s,dealName:t,contactName:r,portal:n,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=RTe(),d=vL(),h=zht(),m=$ht(),[x,y]=k.useState(!1),v=!!(n!=null&&n.archived_at),w=async()=>{y(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ue.success("Portal enabled!")}catch{ue.error("Failed to create portal")}finally{y(!1)}},b=async I=>{if(n)try{await d.mutateAsync({id:n.id,is_enabled:I}),ue.success(I?"Portal enabled":"Portal disabled")}catch{ue.error("Failed to update portal")}},N=()=>{n&&(navigator.clipboard.writeText(yv(n.slug)),ue.success("Link copied!"))},S=()=>{n&&window.open(yv(n.slug),"_blank")},T=async()=>{if(n)try{await h.mutateAsync(n.id),ue.success("Portal archived")}catch{ue.error("Failed to archive portal")}},A=async()=>{if(n)try{await m.mutateAsync(n.id),ue.success("Portal restored")}catch{ue.error("Failed to restore portal")}};return n?v?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Yn,{to:`/mission-control/client-portals/${n.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(Ge,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(G,{variant:"ghost",size:"sm",onClick:A,className:"text-xs gap-1",children:[e.jsx(lA,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>o(n),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}):e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:border-primary/40 hover:bg-muted/30 transition-colors group",children:[e.jsxs(Yn,{to:`/mission-control/client-portals/${n.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(Ge,{variant:"outline",className:n.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:n.is_enabled?"Active":"Disabled"}),e.jsx(va,{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:n.client_name||r||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:N,title:"Copy link",children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:S,title:"Preview",children:e.jsx(Qr,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(n,t),title:"Invite client",children:e.jsx(en,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(n),title:"Post update",children:e.jsx(V0,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(n),title:"Settings",children:e.jsx(oo,{className:"h-3.5 w-3.5"})}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Lp,{className:"h-3.5 w-3.5"})})}),e.jsx(xd,{align:"end",children:e.jsxs(Pa,{onClick:T,children:[e.jsx(Kw,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(_r,{checked:n.is_enabled,onCheckedChange:b,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:r||"No contact"})]}),e.jsxs(G,{size:"sm",onClick:w,disabled:x,className:"shrink-0 ml-4",children:[x?e.jsx(es,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(jr,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function fpt(){const{data:s,isLoading:t}=wxe(),{data:r,isLoading:n}=IIs(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=Uht(),[d,h]=k.useState(null),[m,x]=k.useState(null),[y,v]=k.useState(null),[w,b]=k.useState(null),[N,S]=k.useState(!1),T=sa(),A=t||n,I=new Map;r==null||r.forEach(K=>I.set(K.deal_id,K));const R=[...(s||[]).filter(K=>{var oe,ne,ie,ye,ce;const X=I.get(K.id),Z=a.toLowerCase(),re=!Z||K.deal_name.toLowerCase().includes(Z)||((ne=(oe=K.contact)==null?void 0:oe.first_name)==null?void 0:ne.toLowerCase().includes(Z))||((ye=(ie=K.contact)==null?void 0:ie.last_name)==null?void 0:ye.toLowerCase().includes(Z))||((ce=X==null?void 0:X.client_name)==null?void 0:ce.toLowerCase().includes(Z));let le=!0;return l==="active"?le=!!(X!=null&&X.is_enabled)&&!(X!=null&&X.archived_at):l==="disabled"?le=!!X&&!X.is_enabled&&!X.archived_at:l==="archived"?le=!!(X!=null&&X.archived_at):l==="none"?le=!X:l==="all"&&(le=!(X!=null&&X.archived_at)||!X),re&&le})].sort((K,X)=>{const Z=I.get(K.id),re=I.get(X.id);if(Z!=null&&Z.archived_at&&!(re!=null&&re.archived_at))return 1;if(!(Z!=null&&Z.archived_at)&&(re!=null&&re.archived_at)||Z&&!re)return-1;if(!Z&&re)return 1;if(Z&&re){if(Z.is_enabled&&!re.is_enabled)return-1;if(!Z.is_enabled&&re.is_enabled)return 1}return 0}),$=(r==null?void 0:r.filter(K=>!K.archived_at).length)||0,F=(r==null?void 0:r.filter(K=>K.is_enabled&&!K.archived_at).length)||0,z=(r==null?void 0:r.filter(K=>K.archived_at).length)||0,Q=async()=>{if(w)try{await c.mutateAsync({id:w.id,dealId:w.deal_id}),ue.success("Portal permanently deleted"),b(null)}catch{ue.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(es,{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(jr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[$," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[F," active · ",$-F," disabled",z>0&&` · ${z} archived`]})]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>S(!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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search deals or clients...",value:a,onChange:K=>i(K.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(vr,{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(K=>e.jsx(G,{variant:l===K?"secondary":"ghost",size:"sm",onClick:()=>o(K),className:"text-xs px-3 capitalize",children:K==="none"?"No Portal":K},K))})]}),e.jsx(Qa,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[R.map(K=>{const X=I.get(K.id)||null,Z=K.contact?`${K.contact.first_name||""} ${K.contact.last_name||""}`.trim():"";return e.jsx(LIs,{dealId:K.id,dealName:K.deal_name,contactName:Z,portal:X,onSettingsOpen:h,onComposerOpen:re=>x(re),onInviteOpen:(re,le)=>v({portal:re,dealName:le}),onDeleteConfirm:b},K.id)}),R.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(jr,{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(OEe,{open:!!d,onOpenChange:K=>!K&&h(null),portal:d,dealOwnerId:T||""}),m&&e.jsx(FEe,{open:!!m,onOpenChange:K=>!K&&x(null),portalId:m.id,portalSlug:m.slug,notifyClient:m.notify_client}),y&&e.jsx(BEe,{open:!!y,onOpenChange:K=>!K&&v(null),portal:y.portal,dealName:y.dealName}),e.jsx(mpt,{open:N,onOpenChange:S}),e.jsx(Ko,{open:!!w,onOpenChange:K=>!K&&b(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Permanently delete this portal?"}),e.jsx(Bo,{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(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:Q,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class PIs extends k.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){console.error("DealPipeline error:",t,r)}render(){return this.state.hasError?e.jsx(ws,{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 gD="deal-pipeline-detail-sheet";function DIs(){var Bs;const s=gL(),{data:t,isLoading:r}=_xe(),{data:n,isLoading:a,refetch:i}=wxe(),{data:l,isLoading:o}=mEs(),c=rmt(),d=iEs(),[h,m]=k.useState("board"),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState(null),[S,T]=k.useState(null),[A,I]=k.useState(null),[D,R]=k.useState(null),[$,F]=k.useState(!1),[z,Q]=k.useState(null),[K,X]=k.useState(""),[Z,re]=k.useState("all"),[le,oe]=k.useState("all"),{data:ne}=$Ms(),[ie,ye]=k.useState(!1),[ce,ve]=k.useState(!1),[be,Ue]=k.useState(new Set),Be=k.useRef(!1),[De,Ae]=k.useState(null),{data:He}=yg(),{isTeamLeader:Le,teamMembers:Ie}=BMs(),Te=k.useMemo(()=>Array.from(be),[be]),{data:xe}=zMs(Te),et=k.useMemo(()=>{const ps=new Map;return Ie.forEach(lr=>ps.set(lr.id,{name:lr.name,avatar_url:lr.avatar_url,color:lr.color})),ps},[Ie]),fe=k.useCallback(ps=>ps.owner_user_id&&et.get(ps.owner_user_id)||null,[et]),it=k.useCallback(ps=>{Ue(lr=>{const kr=new Set(lr);return kr.has(ps)?kr.delete(ps):kr.add(ps),kr})},[]);k.useEffect(()=>{!r&&t&&t.length===0&&c.mutate()},[r,t]);const[Oe,Ye]=Ac(),We=k.useRef(!1);k.useEffect(()=>{const ps=Oe.get("deal");if(ps&&n&&n.length>0&&!We.current){const lr=n.find(kr=>kr.id===ps);lr&&(We.current=!0,N(lr),w(!0),Oe.delete("deal"),Ye(Oe,{replace:!0}))}},[n,Oe]);const _e=k.useMemo(()=>{if(!xe||!t)return[];const ps=new Map(t.map(lr=>[lr.name,lr.id]));return xe.map(lr=>{const kr=lr._stage_name&&ps.get(lr._stage_name)||null;return{...lr,stage_id:kr||lr.stage_id}})},[xe,t]),Re=k.useMemo(()=>[...n||[],..._e],[n,_e]);k.useEffect(()=>{if(Be.current||Re.length===0)return;Be.current=!0;const ps=sessionStorage.getItem(gD);if(ps)try{const lr=JSON.parse(ps);if(!lr.open||!lr.dealId)return;const kr=Re.find(Lr=>Lr.id===lr.dealId);kr&&(N(kr),w(!0))}catch{sessionStorage.removeItem(gD)}},[Re]),k.useEffect(()=>{v&&(b!=null&&b.id)?sessionStorage.setItem(gD,JSON.stringify({dealId:b.id,open:!0})):sessionStorage.removeItem(gD)},[v,b==null?void 0:b.id]);const tt=(ne==null?void 0:ne.byDeal)||{},Ke=(ne==null?void 0:ne.unique)||[],Ze=Re.filter(ps=>{var Mr,Cr,Xr,Ln,Zs,Yr;const lr=K.toLowerCase(),kr=tt[ps.id]||[],Lr=!lr||ps.deal_name.toLowerCase().includes(lr)||((Cr=(Mr=ps.contact)==null?void 0:Mr.first_name)==null?void 0:Cr.toLowerCase().includes(lr))||((Ln=(Xr=ps.contact)==null?void 0:Xr.last_name)==null?void 0:Ln.toLowerCase().includes(lr))||((Zs=ps.property_address)==null?void 0:Zs.toLowerCase().includes(lr))||((Yr=ps.city)==null?void 0:Yr.toLowerCase().includes(lr))||kr.some(ss=>ss.toLowerCase().includes(lr)),qr=Z==="all"||ps.deal_type===Z,Ur=le==="all"||kr.includes(le);return Lr&&qr&&Ur}),lt=k.useMemo(()=>{if(!t)return l||null;const ps=new Set(t.filter(Mr=>Mr.is_won_stage).map(Mr=>Mr.id)),lr=new Set(t.filter(Mr=>Mr.is_lost_stage).map(Mr=>Mr.id)),kr=Re.filter(Mr=>Mr.stage_id&&!ps.has(Mr.stage_id)&&!lr.has(Mr.stage_id)),Lr=Re.filter(Mr=>Mr.stage_id&&ps.has(Mr.stage_id)),qr=new Date().getFullYear(),Ur=Lr.filter(Mr=>Mr.actual_close_date?new Date(Mr.actual_close_date).getFullYear()===qr:!0);return{totalDeals:Re.length,activeDeals:kr.length,wonDeals:Lr.length,pipelineValue:kr.reduce((Mr,Cr)=>Mr+(Cr.expected_price||0),0),expectedCommission:kr.reduce((Mr,Cr)=>Mr+(Cr.expected_commission||0),0),expectedNetToAgent:kr.reduce((Mr,Cr)=>Mr+(Jx(Cr)||0),0),wonValue:Lr.reduce((Mr,Cr)=>Mr+(Cr.expected_price||0),0),weightedGCI:kr.reduce((Mr,Cr)=>Mr+(Cr.expected_commission||0)*((Cr.probability??50)/100),0),weightedNet:kr.reduce((Mr,Cr)=>Mr+(Jx(Cr)||0)*((Cr.probability??50)/100),0),ytdWonDeals:Ur.length,ytdWonGCI:Ur.reduce((Mr,Cr)=>Mr+(Cr.expected_commission||0),0),ytdWonNet:Ur.reduce((Mr,Cr)=>Mr+(Jx(Cr)||0),0),projectedAnnualNet:Ur.reduce((Mr,Cr)=>Mr+(Jx(Cr)||0),0)+kr.reduce((Mr,Cr)=>Mr+(Jx(Cr)||0)*((Cr.probability??50)/100),0)}},[Re,t,l]),xt=ps=>{N(ps),w(!0)},Xe=ps=>{T(ps||null),N(null),y(!0)},Je=ps=>{N(ps),w(!1),y(!0)},jt=ps=>{w(ps),ps||sessionStorage.removeItem(gD)},ns=(ps,lr)=>{I(ps)},Ns=(ps,lr)=>{ps.preventDefault(),ps.dataTransfer.dropEffect="move",R(lr)},Ys=async(ps,lr)=>{if(ps.preventDefault(),R(null),!A)return;const kr=n==null?void 0:n.find(Ur=>Ur.id===A),Lr=t==null?void 0:t.find(Ur=>Ur.id===lr),qr=t==null?void 0:t.find(Ur=>Ur.id===(kr==null?void 0:kr.stage_id));if(!kr||!Lr||kr.stage_id===lr){I(null);return}Ae({dealId:A,dealName:kr.deal_name,fromStageName:(qr==null?void 0:qr.name)||"Unknown",toStageName:Lr.name,toStageId:lr,isWonStage:Lr.is_won_stage,deal:kr}),I(null)},rs=async()=>{if(!De)return;const{dealId:ps,toStageId:lr,toStageName:kr,isWonStage:Lr,deal:qr}=De;if(await d.mutateAsync({dealId:ps,stageId:lr,stageName:kr}),ue.success(`Moved to ${kr}`),Lr&&!qr.scorecard_transaction_id){const Ur={...qr,stage_id:lr};Q(Ur),F(!0)}},bt=k.useCallback(async(ps,lr,kr)=>{const Lr=n==null?void 0:n.find(Mr=>Mr.id===ps),qr=t==null?void 0:t.find(Mr=>Mr.id===lr),Ur=t==null?void 0:t.find(Mr=>Mr.id===(Lr==null?void 0:Lr.stage_id));!Lr||!qr||Lr.stage_id===lr||Ae({dealId:ps,dealName:Lr.deal_name,fromStageName:(Ur==null?void 0:Ur.name)||"Unknown",toStageName:kr,toStageId:lr,isWonStage:qr.is_won_stage,deal:Lr})},[n,t]),cs=ps=>Ze.filter(lr=>lr.stage_id===ps),yt=r||a,is=s?"list":h;return e.jsxs(ws,{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(G,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(Mi,{className:"h-4 w-4"})}),!s&&e.jsx(Ub,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:h==="board"?"secondary":"ghost",size:"sm",onClick:()=>m("board"),className:"px-3 gap-1.5",children:[e.jsx(xf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(Gl,{children:"Kanban board view"})]}),e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:h==="list"?"secondary":"ghost",size:"sm",onClick:()=>m("list"),className:"px-3 gap-1.5",children:[e.jsx(em,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(Gl,{children:"Grouped list view"})]}),e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:h==="table"?"secondary":"ghost",size:"sm",onClick:()=>m("table"),className:"px-3 gap-1.5",children:[e.jsx(kA,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(Gl,{children:"Sortable table view"})]}),e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsxs(G,{variant:h==="portals"?"secondary":"ghost",size:"sm",onClick:()=>m("portals"),className:"px-3 gap-1.5",children:[e.jsx(jr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(Gl,{children:"Client portal management"})]})]})}),He&&!Le&&e.jsxs(G,{variant:"outline",onClick:()=>ye(!0),children:[e.jsx(pr,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(G,{onClick:()=>Xe(),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),is!=="portals"&&e.jsx(HMs,{stats:lt,isLoading:o}),is!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search deals, contacts, addresses, tags...",value:K,onChange:ps=>X(ps.target.value),className:"pl-9 pr-8"}),K&&e.jsx("button",{onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(vr,{className:"h-4 w-4"})})]}),e.jsxs(Is,{value:Z,onValueChange:re,children:[e.jsx(As,{className:"w-[140px]",children:e.jsx(Ls,{placeholder:"All Types"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Types"}),e.jsx(ct,{value:"buyer",children:"Buyer"}),e.jsx(ct,{value:"seller",children:"Seller"}),e.jsx(ct,{value:"dual",children:"Dual"}),e.jsx(ct,{value:"referral",children:"Referral"}),e.jsx(ct,{value:"lease",children:"Lease"})]})]}),e.jsxs(Is,{value:le,onValueChange:oe,children:[e.jsxs(As,{className:"w-[160px]",children:[e.jsx(wh,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(Ls,{placeholder:"All Tags"})]}),e.jsxs(Ms,{className:"max-h-[300px]",children:[e.jsx(ct,{value:"all",children:"All Tags"}),Ke.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Ke.map(ps=>e.jsx(ct,{value:ps,children:ps},ps))]})]}),le!=="all"&&e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(wh,{className:"h-3 w-3"}),le,e.jsx("button",{onClick:()=>oe("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(vr,{className:"h-3 w-3"})})]}),(K||Z!=="all"||le!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[Ze.length," of ",(n==null?void 0:n.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Le&&!s&&Ie.length>0&&e.jsx(FMs,{members:Ie,enabledMembers:be,onToggleMember:it,isOpen:ce,onToggleOpen:()=>ve(ps=>!ps)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:yt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(ps=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(Fs,{className:"h-full rounded-xl"})},ps))}):is==="board"?e.jsxs(Qa,{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(ps=>e.jsx(VMs,{stage:ps,deals:cs(ps.id),onDealClick:xt,onAddDeal:Xe,onDragStart:ns,onDragOver:Ns,onDrop:Ys,isDragOver:D===ps.id,isWonStage:ps.is_won_stage,getOwnerInfo:fe},ps.id))}),e.jsx(wfe,{orientation:"horizontal"})]}):is==="table"?e.jsx(Qa,{className:"h-full",children:e.jsx(gIs,{deals:Ze,stages:t||[],onDealClick:xt,onStageChange:bt})}):is==="portals"?e.jsx(fpt,{}):e.jsx(Qa,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(ps=>{const lr=cs(ps.id);return lr.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:ps.color}}),e.jsx("h3",{className:"font-semibold",children:ps.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",lr.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:lr.map(kr=>e.jsx(upt,{deal:kr,onClick:()=>xt(kr),stages:t,onStageChange:bt,showStagePicker:!0,isWonStage:ps.is_won_stage,ownerInfo:fe(kr)},kr.id))})]},ps.id)}),(n==null?void 0:n.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(xf,{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(G,{onClick:()=>Xe(),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((n==null?void 0:n.length)||0)>0&&Ze.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(yn,{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(G,{variant:"outline",onClick:()=>{X(""),re("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(YMs,{open:x,onOpenChange:y,deal:b,defaultStageId:S}),e.jsx(fIs,{deal:b,open:v,onOpenChange:jt,onEdit:Je,isWonStage:b?(Bs=t==null?void 0:t.find(ps=>ps.id===b.stage_id))==null?void 0:Bs.is_won_stage:!1,onAddToScorecard:ps=>{Q(ps),F(!0),w(!1)}}),e.jsx(pIs,{open:$,onOpenChange:F,deal:z,onComplete:()=>{i(),Q(null)}}),De&&e.jsx(EIs,{open:!!De,onOpenChange:ps=>{ps||Ae(null)},dealId:De.dealId,dealName:De.dealName,fromStageName:De.fromStageName,toStageName:De.toStageName,toStageId:De.toStageId,onConfirm:rs}),e.jsx(RMs,{open:ie,onOpenChange:ye})]})}function RIs(){return e.jsx(PIs,{children:e.jsx(DIs,{})})}function ppt({open:s,onOpenChange:t,editTask:r,defaultDealId:n,defaultStageId:a}){var X;const i=bIs(),l=_Is(),{data:o}=wxe(),c=sa(),{data:d}=mt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:Z,error:re}=await V.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(re)throw re;return Z},enabled:!!c&&s}),[h,m]=k.useState(""),[x,y]=k.useState(""),[v,w]=k.useState("none"),[b,N]=k.useState("none"),[S,T]=k.useState("medium"),[A,I]=k.useState("todo"),[D,R]=k.useState(),[$,F]=k.useState(!1),[z,Q]=k.useState(!1);k.useEffect(()=>{r?(m(r.title),y(r.description||""),w(r.deal_id||"none"),N(r.contact_id||"none"),T(r.priority),I(r.status),R(r.due_date?nf(r.due_date):void 0)):(m(""),y(""),w(n||"none"),N("none"),T("medium"),I("todo"),R(void 0))},[r,s,n]);const K=async()=>{if(!h.trim()){ue.error("Task title is required");return}try{const Z={title:h.trim(),description:x.trim()||null,deal_id:v==="none"?null:v,contact_id:b==="none"?null:b,stage_id:a||null,priority:S,status:A,due_date:D?_s(D,"yyyy-MM-dd"):null};r?(await l.mutateAsync({id:r.id,...Z}),ue.success("Task updated")):(await i.mutateAsync(Z),ue.success("Task created")),t(!1)}catch{ue.error("Failed to save task")}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[480px]",children:[e.jsx(ys,{children:e.jsx(gs,{children:r?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title *"}),e.jsx(Ne,{value:h,onChange:Z=>m(Z.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:x,onChange:Z=>y(Z.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Priority"}),e.jsxs(Is,{value:S,onValueChange:Z=>T(Z),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"low",children:"🟢 Low"}),e.jsx(ct,{value:"medium",children:"🟡 Medium"}),e.jsx(ct,{value:"high",children:"🟠 High"}),e.jsx(ct,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Status"}),e.jsxs(Is,{value:A,onValueChange:Z=>I(Z),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"todo",children:"To Do"}),e.jsx(ct,{value:"in_progress",children:"In Progress"}),e.jsx(ct,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Due Date"}),e.jsxs(To,{children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:It("w-full justify-start text-left font-normal",!D&&"text-muted-foreground"),children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),D?_s(D,"PPP"):"Pick a date"]})}),e.jsx(_o,{className:"w-auto p-0",align:"start",children:e.jsx(Yp,{mode:"single",selected:D,onSelect:R,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Link to Deal"}),e.jsxs(To,{open:$,onOpenChange:F,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{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(Sa,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?((X=o==null?void 0:o.find(Z=>Z.id===v))==null?void 0:X.deal_name)||"Select deal":"No Deal"]}),e.jsx(qp,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search deals..."}),e.jsxs(ax,{children:[e.jsx(ix,{children:"No deals found."}),e.jsxs(ox,{children:[e.jsxs(cf,{value:"no-deal",onSelect:()=>{w("none"),F(!1)},children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(Z=>e.jsxs(cf,{value:Z.deal_name,onSelect:()=>{w(Z.id),F(!1)},children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",v===Z.id?"opacity-100":"opacity-0")}),Z.deal_name]},Z.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Link to Contact"}),e.jsxs(To,{open:z,onOpenChange:Q,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{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(Di,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),b!=="none"?(()=>{const Z=d==null?void 0:d.find(re=>re.id===b);return Z?`${Z.first_name} ${Z.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(qp,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search contacts..."}),e.jsxs(ax,{children:[e.jsx(ix,{children:"No contacts found."}),e.jsxs(ox,{children:[e.jsxs(cf,{value:"no-contact",onSelect:()=>{N("none"),Q(!1)},children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",b==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(Z=>e.jsxs(cf,{value:`${Z.first_name} ${Z.last_name}`,onSelect:()=>{N(Z.id),Q(!1)},children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",b===Z.id?"opacity-100":"opacity-0")}),Z.first_name," ",Z.last_name]},Z.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:K,disabled:i.isPending||l.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const OIs={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 FIs({tasks:s}){const t=zEe(),r=wIs(),n=br(),[a,i]=k.useState(null),l=async h=>{const m=h.status==="done"?"todo":"done";try{await t.mutateAsync({id:h.id,status:m})}catch{ue.error("Failed to update task")}},o=async h=>{try{await r.mutateAsync(h),ue.success("Task deleted")}catch{ue.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(In,{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(h=>{if(h.deal){const m=c.get(h.deal.id)||{dealName:h.deal.deal_name,tasks:[]};m.tasks.push(h),c.set(h.deal.id,m)}else d.push(h)}),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(h=>e.jsx(Kqe,{task:h,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:m=>n(`/mission-control/pipeline?deal=${m}`)},h.id))]}),Array.from(c.entries()).map(([h,m])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${h}`),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(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:m.dealName}),e.jsxs(Ge,{variant:"secondary",className:"ml-auto text-xs",children:[m.tasks.filter(x=>x.status==="done").length,"/",m.tasks.length]}),e.jsx(va,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),m.tasks.map(x=>e.jsx(Kqe,{task:x,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:y=>n(`/mission-control/pipeline?deal=${y}`)},x.id))]},h)),a&&e.jsx(ppt,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function Kqe({task:s,onToggle:t,onDelete:r,onEdit:n,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&hv(nf(s.due_date))&&!zu(nf(s.due_date)),o=!i&&s.due_date&&zu(nf(s.due_date)),c=OIs[s.priority];return e.jsxs("div",{className:It("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(In,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Ld,{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:It("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(Di,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Ge,{variant:"outline",className:It("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:It("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(fn,{className:"h-3 w-3"}),_s(nf(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:()=>n(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(sd,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>r(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const BIs=[{status:"todo",label:"To Do",icon:Ld,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:rf,color:"border-t-blue-500"},{status:"done",label:"Done",icon:In,color:"border-t-emerald-500"}],zIs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function $Is({tasks:s}){const t=zEe(),r=k.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),n=(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{ue.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:BIs.map(i=>e.jsxs("div",{className:It("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(Ge,{variant:"secondary",className:"ml-auto text-xs",children:r[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[i.status].map(l=>e.jsx(UIs,{task:l,onDragStart:n},l.id)),r[i.status].length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},i.status))})}function UIs({task:s,onDragStart:t}){const r=s.status==="done",n=!r&&s.due_date&&hv(nf(s.due_date))&&!zu(nf(s.due_date)),a=!r&&s.due_date&&zu(nf(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:It("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",n&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-xs mt-0.5",children:zIs[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:It("text-sm font-medium",r&&"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(Sa,{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(Di,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:It("text-[10px] mt-1.5 flex items-center gap-1",n&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!n&&!a&&"text-muted-foreground"),children:[e.jsx(fn,{className:"h-2.5 w-2.5"}),n?"Overdue — ":a?"Due today — ":"",_s(nf(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 Yqe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function qIs({tasks:s}){const[t,r]=k.useState(new Date),n=zEe(),a=$c(t),i=qx(t),l=jm(a),o=xfe(i),c=gIt({start:l,end:o}),d=k.useMemo(()=>{const x=new Map;return s.forEach(y=>{if(!y.due_date)return;const v=y.due_date,w=x.get(v)||[];w.push(y),x.set(v,w)}),x},[s]),h=k.useMemo(()=>s.filter(x=>!x.due_date),[s]),m=async x=>{const y=x.status==="done"?"todo":"done";try{await n.mutateAsync({id:x.id,status:y})}catch{ue.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(G,{variant:"ghost",size:"icon",onClick:()=>r(t4(t,1)),children:e.jsx($o,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:_s(t,"MMMM yyyy")}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>r(gf(t,1)),children:e.jsx(va,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(x=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:x},x))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(x=>{const y=_s(x,"yyyy-MM-dd"),v=d.get(y)||[],w=yfe(x,t),b=zu(x);return e.jsxs("div",{className:It("border-r border-b min-h-[100px] p-1",!w&&"bg-muted/30",b&&"bg-primary/5"),children:[e.jsx("div",{className:It("text-xs font-medium mb-1 text-right px-1",!w&&"text-muted-foreground/40",b&&"text-primary font-bold"),children:_s(x,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[v.slice(0,3).map(N=>e.jsxs("button",{onClick:()=>m(N),className:It("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",N.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[N.status==="done"?e.jsx(In,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Ld,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Yqe[N.priority]," ",N.title]})]},N.id)),v.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",v.length-3," more"]})]})]},y)})}),h.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 (",h.length,")"]}),e.jsx("div",{className:"space-y-1",children:h.map(x=>e.jsxs("button",{onClick:()=>m(x),className:It("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",x.status==="done"&&"opacity-50 line-through"),children:[x.status==="done"?e.jsx(In,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Ld,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Yqe[x.priority]," ",x.title]}),x.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",x.deal.deal_name]})]},x.id))})]})]})}const VIs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function HIs({open:s,onOpenChange:t,stages:r}){var N;const[n,a]=k.useState(((N=r[0])==null?void 0:N.id)||""),{data:i,isLoading:l}=NIs(n||void 0),o=kIs(),c=SIs(),[d,h]=k.useState(""),[m,x]=k.useState("medium"),[y,v]=k.useState(""),w=async()=>{if(!(!d.trim()||!n))try{await o.mutateAsync({stage_id:n,title:d.trim(),priority:m,default_due_offset_days:y?parseInt(y):null,sort_order:((i==null?void 0:i.length)||0)+1}),h(""),v(""),ue.success("Template added")}catch{ue.error("Failed to add template")}},b=async S=>{try{await c.mutateAsync(S),ue.success("Template deleted")}catch{ue.error("Failed to delete template")}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[560px]",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(pR,{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(he,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(S=>!S.is_won_stage&&!S.is_lost_stage).map(S=>e.jsx("button",{onClick:()=>a(S.id),className:It("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===S.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:S.name},S.id))})]}),e.jsx(Qa,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((S,T)=>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:VIs[S.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:S.title}),S.default_due_offset_days&&e.jsxs(Ge,{variant:"outline",className:"text-[10px]",children:["+",S.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>b(S.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]},S.id)),(i==null?void 0:i.length)===0&&n&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Task title...",value:d,onChange:S=>h(S.target.value),className:"flex-1",onKeyDown:S=>S.key==="Enter"&&w()}),e.jsxs(Is,{value:m,onValueChange:S=>x(S),children:[e.jsx(As,{className:"w-[100px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"low",children:"🟢 Low"}),e.jsx(ct,{value:"medium",children:"🟡 Med"}),e.jsx(ct,{value:"high",children:"🟠 High"}),e.jsx(ct,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(Ne,{type:"number",placeholder:"e.g., 7",value:y,onChange:S=>v(S.target.value)})]}),e.jsxs(G,{onClick:w,disabled:!d.trim()||o.isPending,children:[e.jsx($s,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function GIs(){const{data:s,isLoading:t}=yIs(),{data:r}=_xe(),[n,a]=k.useState("list"),[i,l]=k.useState(""),[o,c]=k.useState("active"),[d,h]=k.useState("all"),[m,x]=k.useState("all"),[y,v]=k.useState(!1),[w,b]=k.useState(!1),N=k.useMemo(()=>{if(!s)return[];const A=new Map;return s.forEach(I=>{I.deal&&A.set(I.deal.id,I.deal.deal_name)}),Array.from(A,([I,D])=>({id:I,name:D}))},[s]),S=k.useMemo(()=>s?s.filter(A=>{var z,Q,K,X;const I=i.toLowerCase(),D=!I||A.title.toLowerCase().includes(I)||((Q=(z=A.deal)==null?void 0:z.deal_name)==null?void 0:Q.toLowerCase().includes(I))||`${((K=A.contact)==null?void 0:K.first_name)||""} ${((X=A.contact)==null?void 0:X.last_name)||""}`.toLowerCase().includes(I),R=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&&hv(nf(A.due_date))&&!zu(nf(A.due_date)),$=d==="all"||A.priority===d,F=m==="all"||m==="no_deal"&&!A.deal_id||A.deal_id===m;return D&&R&&$&&F}):[],[s,i,o,d,m]),T=k.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const A=s.filter(I=>I.status!=="done");return{total:A.length,overdue:A.filter(I=>I.due_date&&hv(nf(I.due_date))&&!zu(nf(I.due_date))).length,dueToday:A.filter(I=>I.due_date&&zu(nf(I.due_date))).length,dueThisWeek:A.filter(I=>I.due_date&&mPt(nf(I.due_date))).length,completed:s.filter(I=>I.status==="done").length}},[s]);return e.jsx(ws,{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(G,{variant:"outline",size:"sm",onClick:()=>b(!0),children:[e.jsx(Sy,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(G,{size:"sm",onClick:()=>v(!0),children:[e.jsx($s,{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(em,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.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(id,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:T.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(fn,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.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(hd,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.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(In,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:T.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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:d,onValueChange:h,children:[e.jsx(As,{className:"w-[130px]",children:e.jsx(Ls,{placeholder:"Priority"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Priorities"}),e.jsx(ct,{value:"urgent",children:"🔴 Urgent"}),e.jsx(ct,{value:"high",children:"🟠 High"}),e.jsx(ct,{value:"medium",children:"🟡 Medium"}),e.jsx(ct,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(Is,{value:m,onValueChange:x,children:[e.jsx(As,{className:"w-[160px]",children:e.jsx(Ls,{placeholder:"Deal"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Deals"}),e.jsx(ct,{value:"no_deal",children:"No Deal"}),N.map(A=>e.jsx(ct,{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 ${n==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(em,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("kanban"),className:`p-1.5 rounded-md transition-colors ${n==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(nv,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("calendar"),className:`p-1.5 rounded-md transition-colors ${n==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(hd,{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:[n==="list"&&e.jsx(FIs,{tasks:S}),n==="kanban"&&e.jsx($Is,{tasks:S}),n==="calendar"&&e.jsx(qIs,{tasks:S})]}),e.jsx(ppt,{open:y,onOpenChange:v}),e.jsx(HIs,{open:w,onOpenChange:b,stages:r||[]})]})})}function xpt(){const s=sa();return mt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(r)throw r;return t||[]},enabled:!!s})}function WIs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("portal_referrals").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function KIs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("portal_referrals").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const YIs=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),Nbe=[{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"}],ZIs={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function gpt(){const{data:s=[],isLoading:t}=xpt(),r=WIs(),n=KIs(),[a,i]=k.useState("all"),[l,o]=k.useState({}),c=k.useMemo(()=>a==="all"?s:s.filter(y=>y.status===a),[s,a]),d=k.useMemo(()=>({total:s.length,new:s.filter(y=>y.status==="new").length,converted:s.filter(y=>y.status==="converted").length}),[s]),h=(y,v)=>{r.mutate({id:y.id,status:v}),ue.success("Status updated")},m=y=>{const v=l[y.id];r.mutate({id:y.id,agent_notes:v}),o(w=>{const{[y.id]:b,...N}=w;return N}),ue.success("Notes saved")},x=y=>{confirm(`Delete referral for ${y.friend_name}?`)&&n.mutate(y.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(nl,{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(ii,{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"},...Nbe.map(y=>({v:y.value,l:y.label}))].map(y=>e.jsx("button",{onClick:()=>i(y.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===y.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:y.l},y.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center",children:[e.jsx(ii,{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(y=>{var N,S;const v=Nbe.find(T=>T.value===y.status),w=(N=y.client_portals)==null?void 0:N.slug,b=y.referrer_name||((S=y.client_portals)==null?void 0:S.client_name)||"Anonymous client";return e.jsxs(ke,{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(Dt,{className:"text-lg",children:y.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(on,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:b})," ·"," ",YIs(y.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{variant:"outline",className:v==null?void 0:v.className,children:(v==null?void 0:v.label)||y.status}),e.jsxs(Is,{value:y.status,onValueChange:T=>h(y,T),children:[e.jsx(As,{className:"h-8 w-[130px] text-xs",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:Nbe.map(T=>e.jsx(ct,{value:T.value,className:"text-xs",children:T.label},T.value))})]})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[y.friend_interest&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:ZIs[y.friend_interest]||y.friend_interest}),y.friend_email&&e.jsxs("a",{href:`mailto:${y.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"}),y.friend_email]}),y.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${y.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Cn,{className:"h-3 w-3"}),y.friend_phone]}),e.jsxs("a",{href:`sms:${y.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Jl,{className:"h-3 w-3"}),"Text"]})]})]}),y.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:['"',y.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[y.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(or,{value:l[y.id],onChange:T=>o(A=>({...A,[y.id]:T.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{size:"sm",onClick:()=>m(y),children:"Save"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>o(T=>{const{[y.id]:A,...I}=T;return I}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(T=>({...T,[y.id]:y.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:y.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:[w&&e.jsxs("a",{href:`/portal/${w}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(Qr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>x(y),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]},y.id)})})]})}function ypt({vendor:s,onEdit:t,onDelete:r,onToggleVisible:n,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=lB.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(ke,{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(Hc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Xn,{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(Ge,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Ge,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Ge,{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(Cn,{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(fc,{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(on,{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(Ca,{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:[n&&e.jsxs(G,{size:"sm",variant:a?"default":"outline",onClick:()=>n(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(bn,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(Xh,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(G,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(sd,{className:"w-3.5 h-3.5"})}),r&&e.jsx(G,{size:"sm",variant:"ghost",onClick:r,className:"text-destructive",children:e.jsx(yr,{className:"w-3.5 h-3.5"})})]})]})}function vpt({open:s,onOpenChange:t,vendor:r,ownerType:n,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=VFt(),[c,d]=k.useState({}),[h,m]=k.useState(!1),x=k.useRef(null),y=async b=>{if(!b.type.startsWith("image/")){ue.error("Please select an image");return}if(b.size>5*1024*1024){ue.error("Image must be under 5MB");return}m(!0);try{const N=b.name.split(".").pop()||"png",S=`${n}/${a||i||"misc"}/${Date.now()}.${N}`,{error:T}=await V.storage.from("vendor-logos").upload(S,b,{upsert:!0,contentType:b.type});if(T)throw T;const{data:A}=V.storage.from("vendor-logos").getPublicUrl(S);d(I=>({...I,logo_url:A.publicUrl})),ue.success("Logo uploaded")}catch(N){ue.error(N.message||"Upload failed")}finally{m(!1)}};k.useEffect(()=>{s&&d(r||{owner_type:n,owner_brokerage_id:n==="brokerage"&&a||null,owner_user_id:n==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,r,n,a,i]);const v=(b,N)=>d(S=>({...S,[b]:N})),w=async()=>{var b;if(!((b=c.name)!=null&&b.trim())){ue.error("Name is required");return}try{await o.mutateAsync(c),ue.success(r?"Vendor updated":"Vendor added"),t(!1)}catch(N){ue.error(N.message||"Failed to save vendor")}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:r?"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(he,{children:"Contact Name *"}),e.jsx(Ne,{value:c.name||"",onChange:b=>v("name",b.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Company"}),e.jsx(Ne,{value:c.company||"",onChange:b=>v("company",b.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Category"}),e.jsxs(Is,{value:c.category,onValueChange:b=>v("category",b),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:lB.map(b=>e.jsx(ct,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(Ne,{value:c.phone||"",onChange:b=>v("phone",b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(Ne,{type:"email",value:c.email||"",onChange:b=>v("email",b.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Website"}),e.jsx(Ne,{value:c.website||"",onChange:b=>v("website",b.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Logo"}),e.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];N&&y(N),b.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:()=>v("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(vr,{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(da,{className:"h-5 w-5"})}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:()=>{var b;return(b=x.current)==null?void 0:b.click()},disabled:h,children:[h?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(he,{children:"Address"}),e.jsx(Ne,{value:c.address||"",onChange:b=>v("address",b.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(he,{children:"Description"}),e.jsx(or,{rows:3,value:c.description||"",onChange:b=>v("description",b.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Primary Action"}),e.jsxs(Is,{value:c.action_type,onValueChange:b=>v("action_type",b),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:$Ft.map(b=>e.jsx(ct,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Booking URL (Calendly etc.)"}),e.jsx(Ne,{value:c.booking_url||"",onChange:b=>v("booking_url",b.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(he,{children:"Compliance Disclosure (optional)"}),e.jsx(or,{rows:2,value:c.disclosure_text||"",onChange:b=>v("disclosure_text",b.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(he,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(_r,{checked:!!c.is_active,onCheckedChange:b=>v("is_active",b)})]}),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(he,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(_r,{checked:!!c.is_featured,onCheckedChange:b=>v("is_featured",b)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(he,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(_r,{checked:!!c.is_required,onCheckedChange:b=>v("is_required",b)})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{onClick:w,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function bpt({embedded:s=!1}={}){const t=sa(),{brokerageId:r}=js(),{data:n,isLoading:a}=qFt(),{data:i={}}=kst("agent",t),l=Nst(),o=HFt(),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,y]=k.useState(""),[v,w]=k.useState("all"),b=(n==null?void 0:n.vendors)||[],N=(n==null?void 0:n.selections)||[],S=k.useMemo(()=>{const z=new Map;return N.forEach(Q=>z.set(Q.vendor_id,Q.is_visible)),z},[N]),T=k.useMemo(()=>b.filter(z=>!(v!=="all"&&z.category!==v||x&&!`${z.name} ${z.company||""}`.toLowerCase().includes(x.toLowerCase()))),[b,x,v]),A=T.filter(z=>z.owner_type==="agent"),I=T.filter(z=>z.owner_type==="brokerage"),D=async z=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync(z),ue.success("Vendor deleted")}catch(Q){ue.error(Q.message)}},R=async(z,Q)=>{try{await o.mutateAsync({vendorId:z,isVisible:Q})}catch(K){ue.error(K.message)}},$=z=>z.is_required?!0:S.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(Gu,{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(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx($s,{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(yn,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Ne,{className:"pl-9",placeholder:"Search vendors...",value:x,onChange:z=>y(z.target.value)})]}),e.jsxs("select",{value:v,onChange:z=>w(z.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),lB.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(On,{defaultValue:r?"all":"personal",children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"all",children:["All (",T.length,")"]}),r&&e.jsxs(Kt,{value:"brokerage",children:["From Brokerage (",I.length,")"]}),e.jsxs(Kt,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(ts,{value:"all",className:"mt-4",children:e.jsx(kbe,{vendors:T,isVisibleInPortals:$,onToggle:R,onEdit:z=>{d(z),m(!0)},onDelete:D,userId:t,clicks:i})}),r&&e.jsx(ts,{value:"brokerage",className:"mt-4",children:I.length===0?e.jsx(Zqe,{icon:e.jsx(jr,{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(kbe,{vendors:I,isVisibleInPortals:$,onToggle:R,userId:t,clicks:i})}),e.jsx(ts,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(Zqe,{icon:e.jsx(Gu,{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(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx($s,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(kbe,{vendors:A,isVisibleInPortals:$,onToggle:R,onEdit:z=>{d(z),m(!0)},onDelete:D,userId:t,clicks:i})})]}),e.jsx(vpt,{open:h,onOpenChange:m,vendor:c,ownerType:"agent",agentUserId:t})]});return s?F:e.jsx(ws,{children:F})}function kbe({vendors:s,isVisibleInPortals:t,onToggle:r,onEdit:n,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(ypt,{vendor:o,isVisible:t(o),onToggleVisible:c=>r(o.id,c),onEdit:o.owner_type==="agent"&&o.owner_user_id===i?()=>n==null?void 0:n(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 Zqe({icon:s,title:t,desc:r,action:n}){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:r}),n]})}function XIs(){const{brokerageId:s,isBrokerageManager:t,isAdmin:r,loading:n}=js(),{data:a=[],isLoading:i}=UFt(s),{data:l={}}=kst("brokerage",s),o=Nst(),[c,d]=k.useState(null),[h,m]=k.useState(!1),[x,y]=k.useState(""),[v,w]=k.useState("all");if(n)return e.jsx(ws,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!r)return e.jsx(ws,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const b=a.filter(S=>!(v!=="all"&&S.category!==v||x&&!`${S.name} ${S.company||""}`.toLowerCase().includes(x.toLowerCase()))),N=async S=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(S),ue.success("Vendor deleted")}catch(T){ue.error(T.message)}};return e.jsx(ws,{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(Sa,{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(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx($s,{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(yn,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(Ne,{className:"pl-9",placeholder:"Search vendors...",value:x,onChange:S=>y(S.target.value)})]}),e.jsxs("select",{value:v,onChange:S=>w(S.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),lB.map(S=>e.jsx("option",{value:S.value,children:S.label},S.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):b.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Sa,{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(G,{onClick:()=>{d(null),m(!0)},children:[e.jsx($s,{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:b.map(S=>e.jsx(ypt,{vendor:S,onEdit:()=>{d(S),m(!0)},onDelete:()=>N(S.id),clickCount:l[S.id]},S.id))}),e.jsx(vpt,{open:h,onOpenChange:m,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const QIs=[{value:"overview",label:"Portals",icon:xf},{value:"vendors",label:"Vendors",icon:Qw},{value:"referrals",label:"Referrals",icon:ii},{value:"branding",label:"Branding",icon:fl},{value:"questions",label:"Onboarding",icon:pb}];function JIs(){const[s,t]=Ac(),r=s.get("tab")||"overview",[n,a]=k.useState(r),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return k.useEffect(()=>{t(d=>{const h=new URLSearchParams(d);return h.set("tab",n),h},{replace:!0})},[n,t]),e.jsxs(ws,{children:[e.jsx(nl,{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(jr,{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(QR,{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(G,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(Yn,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(On,{value:n,onValueChange:a,className:"w-full",children:[e.jsx(Rn,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:QIs.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(ts,{value:"overview",className:"mt-6",children:e.jsx(fpt,{})}),e.jsx(ts,{value:"vendors",className:"mt-6",children:e.jsx(eLs,{})}),e.jsx(ts,{value:"referrals",className:"mt-6",children:e.jsx(tLs,{})}),e.jsx(ts,{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(G,{onClick:()=>l(!0),children:[e.jsx(oo,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(ts,{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(pb,{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(G,{onClick:()=>c(!0),children:[e.jsx(oo,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(mpt,{open:i,onOpenChange:l}),e.jsx(hpt,{open:o,onOpenChange:c})]})}function eLs(){return e.jsx(bpt,{embedded:!0})}function tLs(){return e.jsx(gpt,{})}const cE=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function sLs(s){return mt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("client_portals").select("*").eq("id",s).maybeSingle();if(r)throw r;if(!t)return{portal:null,deal:null};const{data:n,error:a}=await V.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(n!=null&&n.contact_id){const{data:l,error:o}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",n.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:n?{deal_name:n.deal_name,contact_id:n.contact_id,contact:i}:null}},enabled:!!s})}function rLs(){const{portalId:s}=Ki(),t=br(),r=sa(),{data:n,isLoading:a}=sLs(s),{data:i=[]}=X5s(s),{data:l=[]}=xpt(),o=vL(),c=zht(),d=$ht(),h=Uht(),[m,x]=k.useState(!1),[y,v]=k.useState(!1),[w,b]=k.useState(!1),[N,S]=k.useState(!1),T=(n==null?void 0:n.portal)??null,A=(n==null?void 0:n.deal)??null,I=k.useMemo(()=>T?l.filter(le=>le.portal_id===T.id):[],[l,T==null?void 0:T.id]);if(a)return e.jsx(ws,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!T)return e.jsx(ws,{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(G,{asChild:!0,variant:"outline",children:e.jsxs(Yn,{to:"/mission-control/client-portals",children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const D=yv(T.slug),R=(A==null?void 0:A.deal_name)||"Untitled deal",$=A==null?void 0:A.contact,F=$?`${$.first_name||""} ${$.last_name||""}`.trim():"",z=!!T.archived_at,Q=()=>{navigator.clipboard.writeText(D),ue.success("Portal link copied!")},K=async le=>{try{await o.mutateAsync({id:T.id,is_enabled:le}),ue.success(le?"Portal enabled":"Portal disabled")}catch{ue.error("Failed to update")}},X=async()=>{try{await c.mutateAsync(T.id),ue.success("Portal archived")}catch{ue.error("Failed to archive")}},Z=async()=>{try{await d.mutateAsync(T.id),ue.success("Portal restored")}catch{ue.error("Failed to restore")}},re=async()=>{try{await h.mutateAsync({id:T.id,dealId:T.deal_id}),ue.success("Portal deleted"),t("/mission-control/client-portals")}catch{ue.error("Failed to delete")}};return e.jsxs(ws,{children:[e.jsx(nl,{children:e.jsxs("title",{children:[R," — 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(G,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Yn,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(ka,{className:"w-4 h-4 mr-1"})," All Client Portals"]})})}),e.jsxs("div",{className:"border rounded-xl p-6 bg-gradient-to-br from-card to-muted/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx(jr,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:R}),e.jsx(Ge,{variant:"outline",className:z?"bg-muted text-muted-foreground":T.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:z?"Archived":T.is_enabled?"Active":"Disabled"}),e.jsx(Ge,{variant:"outline",className:"capitalize text-xs",children:T.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Di,{className:"w-3.5 h-3.5"}),T.client_name||F||"No client name set",($==null?void 0:$.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Vs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:$.email})]}),($==null?void 0:$.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Cn,{className:"w-3.5 h-3.5"}),$.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:D})})]}),!z&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(_r,{checked:T.is_enabled,onCheckedChange:K})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(G,{onClick:Q,variant:"outline",size:"sm",children:[e.jsx(Ra,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(G,{onClick:()=>window.open(D,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Qr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(G,{onClick:()=>b(!0),size:"sm",children:[e.jsx(en,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(G,{onClick:()=>v(!0),variant:"outline",size:"sm",children:[e.jsx(V0,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(G,{onClick:()=>x(!0),variant:"outline",size:"sm",children:[e.jsx(oo,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[z?e.jsxs(G,{onClick:Z,variant:"outline",size:"sm",children:[e.jsx(lA,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(G,{onClick:X,variant:"ghost",size:"sm",children:[e.jsx(Kw,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(G,{onClick:()=>S(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(G$,{icon:V0,label:"Updates Posted",value:i.length}),e.jsx(G$,{icon:ii,label:"Referrals",value:I.length}),e.jsx(G$,{icon:on,label:"Inspection",value:T.inspection_date?cE(T.inspection_date):"—"}),e.jsx(G$,{icon:on,label:"Appraisal",value:T.appraisal_date?cE(T.appraisal_date):"—"})]}),e.jsxs(On,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(Kt,{value:"referrals",children:["Referrals (",I.length,")"]}),e.jsx(Kt,{value:"branding",children:"Branding"}),e.jsx(Kt,{value:"details",children:"Details"})]}),e.jsx(ts,{value:"updates",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{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(G,{size:"sm",onClick:()=>v(!0),children:[e.jsx(V0,{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(V0,{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(le=>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:le.title}),le.is_stage_change&&e.jsx(Ge,{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:cE(le.created_at)}),le.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:le.content}),le.video_url&&e.jsxs("a",{href:le.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(Jr,{className:"w-3 h-3"})," View video"]})]})})},le.id))})]})})}),e.jsx(ts,{value:"referrals",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),I.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(ii,{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:I.map(le=>e.jsx(Yn,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:le.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[le.friend_email||le.friend_phone||"No contact info"," · ",cE(le.created_at)]})]}),e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:le.status})]})},le.id))})]})})}),e.jsx(ts,{value:"branding",className:"mt-4",children:e.jsx(ke,{children:e.jsx(Pe,{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(G,{onClick:()=>x(!0),children:[e.jsx(oo,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(ts,{value:"details",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6 space-y-4",children:[e.jsx(U_,{label:"Visibility",value:T.visibility}),e.jsx(U_,{label:"Onboarding Required",value:T.require_onboarding?"Yes":"No"}),e.jsx(U_,{label:"Allow Spouse",value:T.allow_spouse?"Yes":"No"}),e.jsx(U_,{label:"Notify Client on Updates",value:T.notify_client?"Yes":"No"}),e.jsx(U_,{label:"Show Post-Close Tips",value:T.show_post_close_tips?"Yes":"No"}),e.jsx(U_,{label:"Slug",value:T.slug,mono:!0}),e.jsx(U_,{label:"Created",value:cE(T.created_at)}),e.jsx(U_,{label:"Last Updated",value:cE(T.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(G,{variant:"outline",onClick:()=>x(!0),children:[e.jsx(oo,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(OEe,{open:m,onOpenChange:x,portal:T,dealOwnerId:r||""}),e.jsx(FEe,{open:y,onOpenChange:v,portalId:T.id,portalSlug:T.slug,notifyClient:T.notify_client}),e.jsx(BEe,{open:w,onOpenChange:b,portal:T,dealName:R}),e.jsx(Ko,{open:N,onOpenChange:S,children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Permanently delete this portal?"}),e.jsx(Bo,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:re,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function G$({icon:s,label:t,value:r}){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:r})]})}function U_({label:s,value:t,mono:r}){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 ${r?"font-mono text-xs":""} text-right truncate`,children:t})]})}const Ike=[{value:"video_intro",label:"Video Intro",icon:Jr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:ER,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:wh,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:tl,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Ec,description:"Links to your social profiles"}],nLs=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],aLs={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function _pt({cardId:s}){const{data:t,isLoading:r}=tMt(s),n=sMt(),a=rMt(),i=nMt(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState(null);if(r)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fs,{className:"h-16 w-full"}),e.jsx(Fs,{className:"h-16 w-full"})]});const x=()=>{c&&n.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:aLs[c]||{}},{onSuccess:()=>{o(!1),d("")}})},y=S=>{a.mutate({id:S.id,is_visible:!S.is_visible})},v=(S,T)=>{if(!t)return;const A=t.findIndex(R=>R.id===S.id),I=T==="up"?A-1:A+1;if(I<0||I>=t.length)return;const D=t[I];a.mutate({id:S.id,sort_order:D.sort_order}),a.mutate({id:D.id,sort_order:S.sort_order})},w=S=>{confirm("Remove this block from this card?")&&i.mutate(S.id)},b=(S,T)=>{a.mutate({id:S.id,config:T},{onSuccess:()=>m(null)})},N=S=>Ike.find(T=>T.value===S);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(G,{size:"sm",onClick:()=>o(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((S,T)=>{const A=N(S.block_type),I=(A==null?void 0:A.icon)||wh;return e.jsx(ke,{className:S.is_visible?"":"opacity-50",children:e.jsx(Pe,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vu,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(I,{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)||S.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:iLs(S)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>v(S,"up"),disabled:T===0,children:e.jsx(Id,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>v(S,"down"),disabled:T===t.length-1,children:e.jsx(Hu,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(S),children:S.is_visible?e.jsx(bn,{className:"h-3 w-3"}):e.jsx(Xh,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>m(S),children:"Edit"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>w(S),children:e.jsx(yr,{className:"h-3 w-3"})})]})]})})},S.id)}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:Ike.map(S=>{const T=S.icon;return e.jsxs("button",{onClick:()=>d(S.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===S.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(T,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:S.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S.description})]})]},S.value)})}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(G,{onClick:x,disabled:!c||n.isPending,children:"Add Block"})]})]})}),h&&e.jsx(oLs,{block:h,onSave:S=>b(h,S),onClose:()=>m(null)})]})}function iLs(s){var r;const t=s.config;switch(s.block_type){case"video_intro":return t.video_url?"Video configured":"No video set";case"testimonials":{const n=((r=t.testimonials)==null?void 0:r.length)||0;return`${n} testimonial${n!==1?"s":""}`}case"specialties":{const n=t.tags||[];return n.length?n.slice(0,3).join(", ")+(n.length>3?"...":""):"No tags"}case"custom_links":{const n=t.links||[];return`${n.length} link${n.length!==1?"s":""}`}case"social_media":{const n=t.platforms||[];return n.length?n.map(a=>a.platform).join(", "):"No platforms"}default:return""}}function oLs({block:s,onSave:t,onClose:r}){const[n,a]=k.useState(s.config),i=Ike.find(l=>l.value===s.block_type);return e.jsx(fs,{open:!0,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(lLs,{config:n,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(cLs,{config:n,onChange:a}),s.block_type==="specialties"&&e.jsx(dLs,{config:n,onChange:a}),s.block_type==="custom_links"&&e.jsx(uLs,{config:n,onChange:a}),s.block_type==="social_media"&&e.jsx(hLs,{config:n,onChange:a}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:r,children:"Cancel"}),e.jsx(G,{onClick:()=>t(n),children:"Save"})]})]})})}function lLs({config:s,onChange:t,cardId:r}){var y,v;const[n,a]=k.useState(""),[i,l]=k.useState((y=s.video_url)!=null&&y.includes("youtube")||(v=s.video_url)!=null&&v.includes("youtu.be")?"youtube":"library"),{data:o}=mt({queryKey:["card-owner",r],queryFn:async()=>{const{data:w}=await V.from("agent_cards").select("user_id").eq("id",r).single();return w==null?void 0:w.user_id},enabled:!!r}),{data:c,isLoading:d}=mt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:w,error:b}=await V.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(b)throw b;return w||[]},enabled:!!o}),h=(c==null?void 0:c.filter(w=>!n||(w.title||"").toLowerCase().includes(n.toLowerCase())))||[],m=s.bunny_video_id,x=w=>{var T;const b=(T=w.playback_url)==null?void 0:T.match(/\/(?:play|embed)\/(\d+)\//),S=`https://iframe.mediadelivery.net/embed/${b?b[1]:"570924"}/${w.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:S,bunny_video_id:w.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(On,{value:i,onValueChange:l,children:[e.jsxs(Rn,{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(ts,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search videos...",value:n,onChange:w=>a(w.target.value),className:"pl-9"})]}),e.jsx(Qa,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Fs,{className:"h-14 w-full"}),e.jsx(Fs,{className:"h-14 w-full"})]}):h.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:h.map(w=>e.jsxs("button",{onClick:()=>x(w),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${m===w.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[w.thumbnail_url?e.jsx("img",{src:w.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:b=>{var N;b.currentTarget.style.display="none",(N=b.currentTarget.nextElementSibling)==null||N.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${w.thumbnail_url?"hidden":""}`,children:e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:w.title||"Untitled Video"}),m===w.bunny_video_id&&e.jsx(Kn,{className:"h-4 w-4 text-primary flex-shrink-0"})]},w.id))})})]}),e.jsx(ts,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(he,{children:"YouTube URL"}),e.jsx(Ne,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:w=>t({...s,video_url:w.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 cLs({config:s,onChange:t}){const r=s.testimonials||[],n=(l,o,c)=>{const d=[...r];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...r,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:r.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[r.map((l,o)=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(he,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),r.length>1&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(yr,{className:"h-3 w-3"})})]}),e.jsx(Ne,{placeholder:"Client name",value:l.name,onChange:c=>n(o,"name",c.target.value)}),e.jsx(Ne,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>n(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=>n(o,"quote",c.target.value)})]})},o)),e.jsxs(G,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function dLs({config:s,onChange:t}){const r=s.tags||[],[n,a]=k.useState(""),i=o=>{t({...s,tags:r.includes(o)?r.filter(c=>c!==o):[...r,o]})},l=()=>{n.trim()&&!r.includes(n.trim())&&(t({...s,tags:[...r,n.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:nLs.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${r.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(he,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Add your own...",value:n,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(G,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.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 uLs({config:s,onChange:t}){const r=s.links||[],n=(l,o,c)=>{const d=[...r];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...r,{label:"",url:""}]}),i=l=>t({...s,links:r.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[r.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(Ne,{placeholder:"Button label",value:l.label,onChange:c=>n(o,"label",c.target.value)}),e.jsx(Ne,{placeholder:"https://...",value:l.url,onChange:c=>n(o,"url",c.target.value)})]}),r.length>1&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(yr,{className:"h-3 w-3"})})]},o)),e.jsxs(G,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const Xqe=[{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 hLs({config:s,onChange:t}){const r=s.platforms||[],n=c=>{r.find(d=>d.platform===c)||t({...s,platforms:[...r,{platform:c,url:""}]})},a=(c,d)=>{const h=[...r];h[c]={...h[c],url:d},t({...s,platforms:h})},i=c=>{t({...s,platforms:r.filter((d,h)=>h!==c)})},l=Xqe.filter(c=>!r.find(d=>d.platform===c.value)),o=c=>{const d=eje[c],h=Xqe.find(m=>m.value===c);return{label:(h==null?void 0:h.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:[r.length>0&&e.jsx("div",{className:"space-y-3",children:r.map((c,d)=>{const h=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:h.color+"30",backgroundColor:h.color+"10"},children:h.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:h.color,children:e.jsx("path",{d:h.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(Ne,{placeholder:`Your ${h.label} profile URL`,value:c.url,onChange:m=>a(d,m.target.value)})}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(he,{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=eje[c.value];return e.jsxs("button",{onClick:()=>n(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)})})]}),r.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 mLs=Object.defineProperty,tme=Object.getOwnPropertySymbols,wpt=Object.prototype.hasOwnProperty,jpt=Object.prototype.propertyIsEnumerable,Qqe=(s,t,r)=>t in s?mLs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[t]=r,Lke=(s,t)=>{for(var r in t||(t={}))wpt.call(t,r)&&Qqe(s,r,t[r]);if(tme)for(var r of tme(t))jpt.call(t,r)&&Qqe(s,r,t[r]);return s},Pke=(s,t)=>{var r={};for(var n in s)wpt.call(s,n)&&t.indexOf(n)<0&&(r[n]=s[n]);if(s!=null&&tme)for(var n of tme(s))t.indexOf(n)<0&&jpt.call(s,n)&&(r[n]=s[n]);return r};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var J3;(s=>{const t=class ho{constructor(c,d,h,m){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cho.MAX_VERSION)throw new RangeError("Version value out of range");if(m<-1||m>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let x=[];for(let v=0;v7)throw new RangeError("Invalid value");let v,w;for(v=h;;v++){const T=ho.getNumDataCodewords(v,d)*8,A=l.getTotalBits(c,v);if(A<=T){w=A;break}if(v>=m)throw new RangeError("Data too long")}for(const T of[ho.Ecc.MEDIUM,ho.Ecc.QUARTILE,ho.Ecc.HIGH])y&&w<=ho.getNumDataCodewords(v,T)*8&&(d=T);let b=[];for(const T of c){r(T.mode.modeBits,4,b),r(T.numChars,T.mode.numCharCountBits(v),b);for(const A of T.getData())b.push(A)}a(b.length==w);const N=ho.getNumDataCodewords(v,d)*8;a(b.length<=N),r(0,Math.min(4,N-b.length),b),r(0,(8-b.length%8)%8,b),a(b.length%8==0);for(let T=236;b.lengthS[A>>>3]|=T<<7-(A&7)),new ho(v,d,S,x)}getModule(c,d){return 0<=c&&c>>9)*1335;const m=(d<<10|h)^21522;a(m>>>15==0);for(let x=0;x<=5;x++)this.setFunctionModule(8,x,n(m,x));this.setFunctionModule(8,7,n(m,6)),this.setFunctionModule(8,8,n(m,7)),this.setFunctionModule(7,8,n(m,8));for(let x=9;x<15;x++)this.setFunctionModule(14-x,8,n(m,x));for(let x=0;x<8;x++)this.setFunctionModule(this.size-1-x,8,n(m,x));for(let x=8;x<15;x++)this.setFunctionModule(8,this.size-15+x,n(m,x));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let h=0;h<12;h++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let h=0;h<18;h++){const m=n(d,h),x=this.size-11+h%3,y=Math.floor(h/3);this.setFunctionModule(x,y,m),this.setFunctionModule(y,x,m)}}drawFinderPattern(c,d){for(let h=-4;h<=4;h++)for(let m=-4;m<=4;m++){const x=Math.max(Math.abs(m),Math.abs(h)),y=c+m,v=d+h;0<=y&&y{(T!=w-x||I>=v)&&S.push(A[T])});return a(S.length==y),S}drawCodewords(c){if(c.length!=Math.floor(ho.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let h=this.size-1;h>=1;h-=2){h==6&&(h=5);for(let m=0;m>>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(v,w),y||(c+=this.finderPenaltyCountPatterns(w)*ho.PENALTY_N3),y=this.modules[x][b],v=1);c+=this.finderPenaltyTerminateAndCount(y,v,w)*ho.PENALTY_N3}for(let x=0;x5&&c++):(this.finderPenaltyAddHistory(v,w),y||(c+=this.finderPenaltyCountPatterns(w)*ho.PENALTY_N3),y=this.modules[b][x],v=1);c+=this.finderPenaltyTerminateAndCount(y,v,w)*ho.PENALTY_N3}for(let x=0;xy+(v?1:0),d);const h=this.size*this.size,m=Math.ceil(Math.abs(d*20-h*10)/h)-1;return a(0<=m&&m<=9),c+=m*ho.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 h=[6];for(let m=this.size-7;h.lengthho.MAX_VERSION)throw new RangeError("Version number out of range");let d=(16*c+128)*c+64;if(c>=2){const h=Math.floor(c/7)+2;d-=(25*h-10)*h-55,c>=7&&(d-=36)}return a(208<=d&&d<=29648),d}static getNumDataCodewords(c,d){return Math.floor(ho.getNumRawDataModules(c)/8)-ho.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*ho.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 m=0;m0);for(const m of c){const x=m^h.shift();h.push(0),d.forEach((y,v)=>h[v]^=ho.reedSolomonMultiply(y,x))}return h}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let h=0;for(let m=7;m>=0;m--)h=h<<1^(h>>>7)*285,h^=(d>>>m&1)*c;return a(h>>>8==0),h}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const h=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(h&&c[0]>=d*4&&c[6]>=d?1:0)+(h&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,h){return c&&(this.finderPenaltyAddHistory(d,h),d=0),d+=this.size,this.finderPenaltyAddHistory(d,h),this.finderPenaltyCountPatterns(h)}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 r(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let h=c-1;h>=0;h--)d.push(o>>>h&1)}function n(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class bd{constructor(c,d,h){if(this.mode=c,this.numChars=d,this.bitData=h,d<0)throw new RangeError("Invalid argument");this.bitData=h.slice()}static makeBytes(c){let d=[];for(const h of c)r(h,8,d);return new bd(bd.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!bd.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let h=0;h=1<{(t=>{const r=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};r.LOW=new r(0,1),r.MEDIUM=new r(1,0),r.QUARTILE=new r(2,3),r.HIGH=new r(3,2),t.Ecc=r})(s.QrCode||(s.QrCode={}))})(J3||(J3={}));(s=>{(t=>{const r=class{constructor(a,i){this.modeBits=a,this.numBitsCharCount=i}numCharCountBits(a){return this.numBitsCharCount[Math.floor((a+7)/17)]}};r.NUMERIC=new r(1,[10,12,14]),r.ALPHANUMERIC=new r(2,[9,11,13]),r.BYTE=new r(4,[8,16,16]),r.KANJI=new r(8,[8,10,12]),r.ECI=new r(7,[0,0,0]),t.Mode=r})(s.QrSegment||(s.QrSegment={}))})(J3||(J3={}));var JE=J3;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var fLs={L:JE.QrCode.Ecc.LOW,M:JE.QrCode.Ecc.MEDIUM,Q:JE.QrCode.Ecc.QUARTILE,H:JE.QrCode.Ecc.HIGH},Npt=128,kpt="L",Spt="#FFFFFF",Cpt="#000000",Tpt=!1,Ept=1,pLs=4,xLs=0,gLs=.1;function Apt(s,t=0){const r=[];return s.forEach(function(n,a){let i=null;n.forEach(function(l,o){if(!l&&i!==null){r.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===n.length-1){if(!l)return;i===null?r.push(`M${o+t},${a+t} h1v1H${o+t}z`):r.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),r.join("")}function Mpt(s,t){return s.slice().map((r,n)=>n=t.y+t.h?r:r.map((a,i)=>i=t.x+t.w?a:!1))}function yLs(s,t,r,n){if(n==null)return null;const a=s.length+r*2,i=Math.floor(t*gLs),l=a/t,o=(n.width||i)*l,c=(n.height||i)*l,d=n.x==null?s.length/2-o/2:n.x*l,h=n.y==null?s.length/2-c/2:n.y*l,m=n.opacity==null?1:n.opacity;let x=null;if(n.excavate){let v=Math.floor(d),w=Math.floor(h),b=Math.ceil(o+d-v),N=Math.ceil(c+h-w);x={x:v,y:w,w:b,h:N}}const y=n.crossOrigin;return{x:d,y:h,h:c,w:o,excavation:x,opacity:m,crossOrigin:y}}function vLs(s,t){return t!=null?Math.max(Math.floor(t),0):s?pLs:xLs}function Ipt({value:s,level:t,minVersion:r,includeMargin:n,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=wt.useMemo(()=>{const v=(Array.isArray(s)?s:[s]).reduce((w,b)=>(w.push(...JE.QrSegment.makeSegments(b)),w),[]);return JE.QrCode.encodeSegments(v,fLs[t],r,void 0,void 0,o)},[s,t,r,o]);const{cells:d,margin:h,numCells:m,calculatedImageSettings:x}=wt.useMemo(()=>{let y=c.getModules();const v=vLs(n,a),w=y.length+v*2,b=yLs(y,l,v,i);return{cells:y,margin:v,numCells:w,calculatedImageSettings:b}},[c,l,i,n,a]);return{qrcode:c,margin:h,cells:d,numCells:m,calculatedImageSettings:x}}var bLs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),_Ls=wt.forwardRef(function(t,r){const n=t,{value:a,size:i=Npt,level:l=kpt,bgColor:o=Spt,fgColor:c=Cpt,includeMargin:d=Tpt,minVersion:h=Ept,boostLevel:m,marginSize:x,imageSettings:y}=n,w=Pke(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:b}=w,N=Pke(w,["style"]),S=y==null?void 0:y.src,T=wt.useRef(null),A=wt.useRef(null),I=wt.useCallback(Z=>{T.current=Z,typeof r=="function"?r(Z):r&&(r.current=Z)},[r]),[D,R]=wt.useState(!1),{margin:$,cells:F,numCells:z,calculatedImageSettings:Q}=Ipt({value:a,level:l,minVersion:h,boostLevel:m,includeMargin:d,marginSize:x,imageSettings:y,size:i});wt.useEffect(()=>{if(T.current!=null){const Z=T.current,re=Z.getContext("2d");if(!re)return;let le=F;const oe=A.current,ne=Q!=null&&oe!==null&&oe.complete&&oe.naturalHeight!==0&&oe.naturalWidth!==0;ne&&Q.excavation!=null&&(le=Mpt(F,Q.excavation));const ie=window.devicePixelRatio||1;Z.height=Z.width=i*ie;const ye=i/z*ie;re.scale(ye,ye),re.fillStyle=o,re.fillRect(0,0,z,z),re.fillStyle=c,bLs?re.fill(new Path2D(Apt(le,$))):F.forEach(function(ce,ve){ce.forEach(function(be,Ue){be&&re.fillRect(Ue+$,ve+$,1,1)})}),Q&&(re.globalAlpha=Q.opacity),ne&&re.drawImage(oe,Q.x+$,Q.y+$,Q.w,Q.h)}}),wt.useEffect(()=>{R(!1)},[S]);const K=Lke({height:i,width:i},b);let X=null;return S!=null&&(X=wt.createElement("img",{src:S,key:S,style:{display:"none"},onLoad:()=>{R(!0)},ref:A,crossOrigin:Q==null?void 0:Q.crossOrigin})),wt.createElement(wt.Fragment,null,wt.createElement("canvas",Lke({style:K,height:i,width:i,ref:I,role:"img"},N)),X)});_Ls.displayName="QRCodeCanvas";var GB=wt.forwardRef(function(t,r){const n=t,{value:a,size:i=Npt,level:l=kpt,bgColor:o=Spt,fgColor:c=Cpt,includeMargin:d=Tpt,minVersion:h=Ept,boostLevel:m,title:x,marginSize:y,imageSettings:v}=n,w=Pke(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:b,cells:N,numCells:S,calculatedImageSettings:T}=Ipt({value:a,level:l,minVersion:h,boostLevel:m,includeMargin:d,marginSize:y,imageSettings:v,size:i});let A=N,I=null;v!=null&&T!=null&&(T.excavation!=null&&(A=Mpt(N,T.excavation)),I=wt.createElement("image",{href:v.src,height:T.h,width:T.w,x:T.x+b,y:T.y+b,preserveAspectRatio:"none",opacity:T.opacity,crossOrigin:T.crossOrigin}));const D=Apt(A,b);return wt.createElement("svg",Lke({height:i,width:i,viewBox:`0 0 ${S} ${S}`,ref:r,role:"img"},w),!!x&&wt.createElement("title",null,x),wt.createElement("path",{fill:o,d:`M0,0 h${S}v${S}H0z`,shapeRendering:"crispEdges"}),wt.createElement("path",{fill:c,d:D,shapeRendering:"crispEdges"}),I)});GB.displayName="QRCodeSVG";function wLs({slug:s,agentName:t}){const r=k.useRef(null),n=`https://cards.relevelup.com/${s}`,a=k.useCallback(()=>{var m;const i=(m=r.current)==null?void 0:m.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),h=new Image;h.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(h,0,0,o,o);const x=document.createElement("a");x.download=`${s}-qr-code.png`,x.href=l.toDataURL("image/png"),x.click(),ue.success("QR code downloaded!")},h.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:r,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(GB,{value:n,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(G,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(Ya,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function Sbe(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 jLs(){const{user:s}=js(),{data:t,isLoading:r}=QAt(s==null?void 0:s.id),n=gL(),[a,i]=k.useState(null),l=k.useMemo(()=>a||(t?Sbe(t):null),[a,t]);if(r)return e.jsx(ws,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(Fs,{className:"h-8 w-48"}),e.jsx(Fs,{className:"h-32 w-full"}),e.jsx(Fs,{className:"h-32 w-full"})]})});if(!t)return e.jsx(ws,{children:e.jsx(kLs,{userId:s==null?void 0:s.id})});const o=l||Sbe(t),c=d=>{i(h=>{const m=h||Sbe(t);return typeof d=="function"?d(m):d})};return e.jsx(ws,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${n?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(SLs,{card:t}),e.jsx(ALs,{card:t,form:o,setForm:c})]}),!n&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!n&&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(rj,{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(NLs,{card:t,form:o})})]})})]})})}function NLs({card:s,form:t}){const{data:r}=mt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await V.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 V.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),n=k.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:(r==null?void 0:r.name)||null,email:t.display_email||(r==null?void 0:r.email)||null,phone:(r==null?void 0:r.phone)||null,brokerage_id:(r==null?void 0:r.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(r==null?void 0:r.avatar_url)||null}),[s,t,r]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(KCe,{card:n})})}function kLs({userId:s}){var c;const[t,r]=k.useState(""),n=IJe(),{data:a}=mt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await V.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){ue.error("Please enter a URL slug for your card");return}n.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ue.success("Your digital card has been created!")})},o=[{icon:fc,title:"Shareable Link",desc:"One link that works everywhere"},{icon:Ku,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Wu,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(jr,{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(ke,{className:"shadow-lg border-2",children:[e.jsxs(Mt,{className:"text-center pb-2",children:[e.jsx(Dt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Nr,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Pe,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:t||i,onChange:d=>r(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(G,{onClick:l,disabled:n.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),n.isPending?"Creating...":"Create My Card"]})]})]})]})}function SLs({card:s}){const r=`https://cards.relevelup.com/${s.slug}`,n=()=>{navigator.clipboard.writeText(r),ue.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(Ge,{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(fc,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[e.jsx(Ra,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(G,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function CLs({userId:s}){const t=Xt(),r=k.useRef(null),[n,a]=k.useState(!1),[i,l]=k.useState(""),{data:o,isLoading:c}=mt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:Q}=await V.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let K=(Q==null?void 0:Q.avatar_url)||null;if(!K){const{data:X}=await V.storage.from("avatars").list(`${s}`);if(X&&X.length>0){const{data:Z}=V.storage.from("avatars").getPublicUrl(`${s}/${X[0].name}`);K=`${Z.publicUrl}?t=${Date.now()}`,await V.from("profiles").update({avatar_url:K}).eq("id",s)}}return{...Q,avatar_url:K}}}),[d,h]=k.useState(null),[m,x]=k.useState(null),[y,v]=k.useState(null),[w,b]=k.useState(!1),N=d??(o==null?void 0:o.name)??"",S=m??(o==null?void 0:o.phone)??"",T=y??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,I=((o==null?void 0:o.name)||"A").split(" ").map(Q=>Q[0]).join("").toUpperCase().slice(0,2),D=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),R=Ct({mutationFn:async Q=>{const{error:K}=await V.from("profiles").update(Q).eq("id",s);if(K)throw K},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ue.success("Profile updated!")},onError:()=>ue.error("Failed to update profile")}),$=()=>{const Q={};if(d!==null&&d!==(o==null?void 0:o.name)&&(Q.name=d),m!==null&&m!==(o==null?void 0:o.phone)&&(Q.phone=m||null),y!==null&&y!==(o==null?void 0:o.email)&&(Q.email=y),Object.keys(Q).length===0){ue.info("No changes to save");return}R.mutate(Q)},F=Q=>{var Z;const K=(Z=Q.target.files)==null?void 0:Z[0];if(!K)return;if(!K.type.startsWith("image/")){ue.error("Please select an image file");return}const X=new FileReader;X.onloadend=()=>{l(X.result),a(!0)},X.readAsDataURL(K),Q.target.value=""},z=async Q=>{b(!0);try{const{data:K}=await V.storage.from("avatars").list(`${s}`);K&&K.length>0&&await V.storage.from("avatars").remove(K.map(oe=>`${s}/${oe.name}`));const X=`${s}/avatar.jpg`,{error:Z}=await V.storage.from("avatars").upload(X,Q,{upsert:!0,contentType:"image/jpeg"});if(Z)throw Z;const{data:re}=V.storage.from("avatars").getPublicUrl(X),le=re.publicUrl+"?t="+Date.now();await V.from("profiles").update({avatar_url:le}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ue.success("Photo updated!")}catch{ue.error("Failed to upload photo")}finally{b(!1)}};return c?e.jsx(Fs,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:D?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Pe,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(he,{className:"text-sm font-semibold",children:"Profile Info"}),D&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Oi,{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 Q;return(Q=r.current)==null?void 0:Q.click()},children:[e.jsxs(Nn,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(ya,{src:A||void 0,alt:N}),e.jsx(kn,{className:"text-lg font-semibold bg-primary/10 text-primary",children:I})]}),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(Qf,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:r,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:w?"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(he,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(Ne,{value:N,onChange:Q=>h(Q.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(he,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(Ne,{value:S,onChange:Q=>x(Q.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(Ne,{value:T,onChange:Q=>v(Q.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:$,disabled:R.isPending,className:"w-full",children:R.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(e5e,{open:n,onClose:()=>a(!1),imageSrc:i,onCropComplete:z,aspectRatio:1})]})}function TLs({form:s,setForm:t,userId:r}){const[n,a]=k.useState(null),[i,l]=k.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=k.useState(s.team_logo_url?"logo":"name"),d=y=>{l(y),t(y==="name"?v=>({...v,brokerage_logo_url:""}):v=>({...v,brokerage_display_name:""}))},h=y=>{c(y),t(y==="name"?v=>({...v,team_logo_url:""}):v=>({...v,team_name:""}))},m=async(y,v)=>{var b;const w=(b=y.target.files)==null?void 0:b[0];if(w){if(!w.type.startsWith("image/")){ue.error("Please select an image file");return}a(v);try{const N=w.name.split(".").pop()||"png",T=`${r}/${v==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${N}`,{error:A}=await V.storage.from("card-logos").upload(T,w,{upsert:!0});if(A)throw A;const{data:I}=V.storage.from("card-logos").getPublicUrl(T),D=I.publicUrl+"?t="+Date.now();t(v==="brokerage_logo_url"?R=>({...R,[v]:D,brokerage_display_name:""}):R=>({...R,[v]:D,team_name:""})),ue.success("Logo uploaded!")}catch{ue.error("Failed to upload logo")}finally{a(null),y.target.value=""}}},x=y=>{t(v=>({...v,[y]:""}))};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{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(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(G,{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(he,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(Ne,{value:s.brokerage_display_name,onChange:y=>t(v=>({...v,brokerage_display_name:y.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{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:()=>x("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(Qf,{className:"h-3.5 w-3.5"}),n==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>m(y,"brokerage_logo_url"),disabled:n!==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(he,{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(_y,{value:[s.brokerage_logo_size||56],onValueChange:([y])=>t(v=>({...v,brokerage_logo_size:y})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>h("name"),children:"Use Name"}),e.jsx(G,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>h("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(Ne,{value:s.team_name,onChange:y=>t(v=>({...v,team_name:y.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{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:()=>x("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(Qf,{className:"h-3.5 w-3.5"}),n==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>m(y,"team_logo_url"),disabled:n!==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(he,{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(_y,{value:[s.team_logo_size||56],onValueChange:([y])=>t(v=>({...v,team_logo_size:y})),min:24,max:120,step:4})]})]})]})]})})}function ELs({form:s,setForm:t}){const r={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},n=s.bold_theme_colors||r,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...r,...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(he,{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(G,{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:n[o],onChange:h=>a(o,h.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:n[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(Ne,{value:n[o],onChange:h=>{const m=h.target.value;/^#[0-9a-fA-F]{0,6}$/.test(m)&&a(o,m)},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:n.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:n.button}})]})]})]})}function ALs({card:s,form:t,setForm:r}){var w;const n=LJe(),a=Xt(),{data:i}=PJe(s.id),[l,o]=k.useState(s.slug),[c,d]=k.useState(!1),[h,m]=k.useState("idle"),x=k.useRef(JSON.stringify(t)),y=k.useRef(null);k.useEffect(()=>{const b=JSON.stringify(t);if(b!==x.current)return y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{m("saving"),n.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:()=>{x.current=b,m("saved"),setTimeout(()=>m("idle"),2e3)},onError:()=>m("idle")})},1500),()=>{y.current&&clearTimeout(y.current)}},[t]);const v=async()=>{const b=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!b){ue.error("Please enter a valid URL");return}if(b===s.slug){ue.info("No changes to save");return}d(!0);try{const{data:N}=await V.from("agent_cards").select("id").eq("slug",b).neq("id",s.id).maybeSingle();if(N){ue.error("This URL is already taken. Try another one.");return}const{error:S}=await V.from("agent_cards").update({slug:b}).eq("id",s.id);if(S)throw S;o(b),a.invalidateQueries({queryKey:["agent-card"]}),ue.success("Card address updated!")}catch{ue.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(On,{defaultValue:"content",children:[e.jsxs(Rn,{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(Vp,{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(bn,{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(Ku,{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(ov,{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(qc,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(ts,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(CLs,{userId:s.user_id}),e.jsx(TLs,{form:t,setForm:r,userId:s.user_id}),e.jsx(ke,{children:e.jsxs(Pe,{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(he,{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(_r,{checked:t.is_published,onCheckedChange:b=>r(N=>({...N,is_published:b}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{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(Ne,{value:l,onChange:b=>o(b.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:v,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(he,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(Ne,{value:t.display_email,onChange:b=>r(N=>({...N,display_email:b.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(he,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(Is,{value:t.theme,onValueChange:b=>r(N=>({...N,theme:b})),children:[e.jsx(As,{className:"h-11",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(ct,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(ct,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(ct,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(ELs,{form:t,setForm:r}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(Ne,{value:t.title,onChange:b=>r(N=>({...N,title:b.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(he,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(Ne,{value:t.positioning_statement,onChange:b=>r(N=>({...N,positioning_statement:b.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Bio"}),e.jsx(or,{value:t.bio,onChange:b=>r(N=>({...N,bio:b.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(he,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(Ne,{value:t.review_snippet,onChange:b=>r(N=>({...N,review_snippet:b.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(Ne,{value:t.review_source_url,onChange:b=>r(N=>({...N,review_source_url:b.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(Ne,{value:t.booking_url,onChange:b=>r(N=>({...N,booking_url:b.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(he,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(Ne,{value:t.custom_cta_label,onChange:b=>r(N=>({...N,custom_cta_label:b.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(ts,{value:"sections",className:"mt-4",children:e.jsx(ke,{children:e.jsx(Pe,{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:b,label:N,desc:S})=>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(he,{className:"text-sm font-medium",children:N}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S})]}),e.jsx(_r,{checked:t[b],onCheckedChange:T=>r(A=>({...A,[b]:T}))})]},b))})})}),e.jsx(ts,{value:"blocks",className:"mt-4",children:e.jsx(_pt,{cardId:s.id})}),e.jsx(ts,{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:bn,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:qc,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((w=i==null?void 0:i.leads)==null?void 0:w.length)??0,icon:sl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(b=>e.jsx(ke,{className:"overflow-hidden",children:e.jsxs(Pe,{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 ${b.color}`,children:e.jsx(b.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:b.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:b.value})]})},b.label))}),i&&i.leads.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Dt,{className:"text-base",children:"Recent Leads"})}),e.jsx(Pe,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(b=>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:b.name}),b.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:b.phone})]}),b.intent&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:b.intent})]},b.id))})]}),(!i||i.leads.length===0)&&e.jsx(ke,{children:e.jsxs(Pe,{className:"p-8 text-center",children:[e.jsx(qc,{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(ts,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(ke,{children:e.jsx(Pe,{className:"p-6",children:e.jsx(wLs,{slug:s.slug})})})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground",children:[h==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-400 animate-pulse"})," Saving..."]}),h==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-green-500"})," All changes saved"]}),h==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/30"})," Changes auto-save"]})]})]})}function MLs(){const s=Xt(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[y,v]=k.useState(null),[w,b]=k.useState(null),[N,S]=k.useState(0),[T,A]=k.useState(""),[I,D]=k.useState(!1),{data:R,isLoading:$}=mt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ie,error:ye}=await V.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ye)throw ye;return ie}}),F=Ct({mutationFn:async ie=>{const{data:ye,error:ce}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ie}});if(ce)throw ce;if(ye!=null&&ye.error)throw new Error(ye.error);return ye},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),r(""),ue.success("BoldTrail connected successfully!")},onError:ie=>{ue.error(ie.message||"Failed to connect BoldTrail")}}),z=Ct({mutationFn:async()=>{const{data:ie,error:ye}=await V.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ye)throw ye;return ie},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.success("BoldTrail disconnected")},onError:()=>ue.error("Failed to disconnect")}),Q=Ct({mutationFn:async ie=>{const{data:ye,error:ce}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ie}});if(ce)throw ce;if(ye!=null&&ye.error)throw new Error(ye.error);return ye},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.success("Sync direction saved")},onError:ie=>{ue.error(ie.message||"Failed to save sync direction")}}),K=Ct({mutationFn:async()=>{const{data:ie,error:ye}=await V.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ye)throw ye;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ie.kvcore_user_id){const ye=ie.detected_name||ie.detected_email||`ID ${ie.kvcore_user_id}`;ue.success(`Detected your BoldTrail account: ${ye}`)}else if(ie.candidates&&ie.candidates.length>0){const ye=ie.candidates.slice(0,5).map(ce=>`${ce.id} (${ce.count} contacts)`).join(", ");ue.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ye}. Pick yours and enter it below.`,{duration:12e3}),D(!0)}else ue.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),D(!0)},onError:ie=>ue.error(ie.message||"Detection failed")}),X=Ct({mutationFn:async ie=>{const{data:ye,error:ce}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ie}});if(ce)throw ce;if(ye!=null&&ye.error)throw new Error(ye.error);return ye},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ue.success("Settings saved"),D(!1)},onError:ie=>ue.error(ie.message||"Failed to save settings")}),Z=Ct({mutationFn:async()=>{const{data:ie,error:ye}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ye)throw ye;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{v(null),c(ie),a(!0)},onError:ie=>{ue.error(ie.message||"Failed to generate sync preview")}}),re=Ct({mutationFn:async()=>{b("Initializing sync..."),S(5);const{data:ie,error:ye}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ne}});if(ye)throw ye;if(ie!=null&&ie.error)throw new Error(ie.error);const ce=ie;let ve=ce.sync_log_id,be=ce.next_phase,Ue=ce.next_offset,Be=ce.push_total||0,De=ce.pull_total||0,Ae=0,He=0;for(;be!=="finalize";){const Te=Be+De;be==="fetch_bt"?b("Fetching BoldTrail contacts..."):be==="analyze"?(b("Analyzing contacts..."),S(15)):be==="push"?(b(`Pushing contacts to BoldTrail... (${Ae}/${Be})`),S(Te>0?Ae/Te*100:0)):be==="pull"&&(b(`Pulling contacts from BoldTrail... (${He}/${De})`),S(Te>0?(Be+He)/Te*100:0));const{data:xe,error:et}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:be,offset:Ue,sync_log_id:ve,sync_direction:ne}});if(et)throw et;if(xe!=null&&xe.error)throw new Error(xe.error);const fe=xe;Ae+=fe.chunk_pushed||0,He+=fe.chunk_pulled||0,fe.push_total!==void 0&&(Be=fe.push_total||0),fe.pull_total!==void 0&&(De=fe.pull_total||0),fe.progress&&b(fe.progress),be==="pull"&&De>0?S(Math.min(95,He/De*100)):be==="push"&&Be>0&&S(Math.min(95,Ae/Be*100)),be=fe.next_phase,Ue=fe.next_offset}b("Finalizing sync..."),S(95);const{data:Le,error:Ie}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ve,sync_direction:ne}});if(Ie)throw Ie;return S(100),Le},onSuccess:ie=>{b(null),S(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"]}),ue.success(`Sync complete! Pushed ${ie.contacts_pushed||0}, pulled ${ie.contacts_pulled||0}, skipped ${ie.contacts_skipped||0} duplicates.`)},onError:ie=>{b(null),S(0),ue.error(ie.message||"Sync failed")}}),le=R==null?void 0:R.connected,oe=(R==null?void 0:R.sync_direction)||"bidirectional",ne=y??oe;return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{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(Ad,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",le&&e.jsx(Ge,{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(rf,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Nr,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Pe,{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(di,{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(di,{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(di,{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"})]}),le?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"}),(R==null?void 0:R.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(R.last_sync_at).toLocaleString(),R.last_sync_status&&e.jsx(Ge,{variant:R.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:R.last_sync_status})]}),(R==null?void 0:R.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[R.boldtrail_contact_count," contacts in BoldTrail"]}),(R==null?void 0:R.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:R.last_sync_message})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect BoldTrail?"}),e.jsx(Bo,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{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(uv,{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(_r,{checked:!!(R!=null&&R.sync_only_owned),onCheckedChange:ie=>X.mutate({sync_only_owned:ie}),disabled:X.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Your BoldTrail Agent ID"}),I?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",placeholder:"e.g. 12345",value:T,onChange:ie=>A(ie.target.value),className:"h-8 text-sm"}),e.jsx(G,{size:"sm",onClick:()=>{const ie=T.trim()===""?null:Number(T);X.mutate({kvcore_user_id:ie})},disabled:X.isPending,children:"Save"}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>D(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(R==null?void 0:R.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>K.mutate(),disabled:K.isPending,children:[K.isPending?e.jsx(Mi,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{var ie;A(((ie=R==null?void 0:R.kvcore_user_id)==null?void 0:ie.toString())??""),D(!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(dke,{value:oe,onChange:ie=>Q.mutate(ie)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(G,{onClick:()=>Z.mutate(),disabled:Z.isPending||re.isPending,variant:"outline",className:"gap-2",children:[Z.isPending?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx(bn,{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(Ne,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ie=>r(ie.target.value),className:"flex-1"}),e.jsxs(G,{onClick:()=>F.mutate(t),disabled:!t||t.length<10||F.isPending,children:[F.isPending?e.jsx(Mi,{className:"h-4 w-4 animate-spin mr-2"}):null,"Connect"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Find your API token in BoldTrail → Lead Engine → Lead Dropbox → My API Tokens. Generate a ",e.jsx("strong",{children:"Contacts"})," scope token."]})]})]})})]}),e.jsx(fs,{open:n,onOpenChange:ie=>{re.isPending||a(ie)},children:e.jsxs(ms,{className:"sm:max-w-lg",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Hr,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ie=ne==="pull_only"?0:o.to_push,ye=ne==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(dke,{value:ne,onChange:v,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(uv,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Owner filter is on. Only contacts assigned to your BoldTrail account",o.kvcore_user_id?` (ID ${o.kvcore_user_id})`:""," will be synced.",o.boldtrail_total_brokerage!=null&&e.jsxs(e.Fragment,{children:[" Brokerage total: ",e.jsx("strong",{children:o.boldtrail_total_brokerage.toLocaleString()}),"."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ne==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ie}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Id,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ne==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:ye}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Hu,{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(pr,{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"]}),re.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ei,{value:N||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:w||"Sync in progress..."})]}),ie>0&&e.jsxs(Gp,{open:d,onOpenChange:h,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Id,{className:"h-3 w-3 text-emerald-600"}),ie," contacts to push to BoldTrail"]}),e.jsx(Wi,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(Kp,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((ce,ve)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ce.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ce.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"]})]})})]}),ye>0&&e.jsxs(Gp,{open:m,onOpenChange:x,children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hu,{className:"h-3 w-3 text-blue-600"}),ye," contacts to pull from BoldTrail"]}),e.jsx(Wi,{className:`h-3 w-3 transition-transform ${m?"rotate-180":""}`})]})}),e.jsx(Kp,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((ce,ve)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ce.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ce.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"]})]})})]}),ie===0&&ye===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(G,{variant:"outline",onClick:()=>a(!1),disabled:re.isPending,children:"Cancel"}),e.jsxs(G,{onClick:()=>re.mutate(),disabled:re.isPending||ie===0&&ye===0,className:"gap-2",children:[re.isPending?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx(Ad,{className:"h-4 w-4"}),re.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(ys,{className:"p-6 pb-0",children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Ad,{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 ILs(){const s=Xt(),[t,r]=k.useState(""),[n,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(null),{data:d,isLoading:h}=mt({queryKey:["fub-status"],queryFn:async()=>{const{data:w,error:b}=await V.functions.invoke("followupboss-sync",{body:{action:"status"}});if(b)throw b;return w}}),m=Ct({mutationFn:async w=>{const{data:b,error:N}=await V.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:w}});if(N)throw N;if(b!=null&&b.error)throw new Error(b.error);return b},onSuccess:()=>{ue.success("Connected to Follow Up Boss"),r(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:w=>ue.error(w.message)}),x=Ct({mutationFn:async()=>{const{error:w}=await V.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(w)throw w},onSuccess:()=>{ue.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),y=Ct({mutationFn:async w=>{const{error:b}=await V.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:w}});if(b)throw b},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),v=async()=>{a(!0),l(0),c("Pulling from FUB…");let w=0,b=0,N=0,S=0;try{for(;;){const{data:D,error:R}=await V.functions.invoke("followupboss-sync",{body:{action:"sync",offset:w}});if(R)throw R;if(D!=null&&D.error)throw new Error(D.error);b+=D.chunk_created||0,N+=D.chunk_updated||0,S+=D.chunk_skipped||0,w=D.next_offset;const $=D.total?Math.min(100,Math.round(w/D.total*100)):100;if(l($),c(`Pulling · ${w} / ${D.total||"?"}`),D.done)break;await new Promise(F=>setTimeout(F,400))}let T=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let D=0;for(l(0),c("Pushing to FUB…");;){const{data:R,error:$}=await V.functions.invoke("followupboss-sync",{body:{action:"push",offset:D}});if($)throw $;if(R!=null&&R.error)throw new Error(R.error);T+=R.chunk_pushed||0,A+=R.chunk_failed||0,D=R.next_offset;const F=R.total?Math.min(100,Math.round(D/R.total*100)):100;if(l(F),c(`Pushing · ${D} / ${R.total||"?"}`),R.done)break;await new Promise(z=>setTimeout(z,400))}}const I=T||A?` · pushed ${T}${A?`, ${A} failed`:""}`:"";ue.success(`Sync complete · ${b} new, ${N} updated${S?`, ${S} skipped`:""}${I}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(T){ue.error(T.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Z4,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Ge,{variant:"default",className:"ml-1",children:[e.jsx(di,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Nr,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Pe,{className:"space-y-4",children:h?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(_r,{checked:d.sync_direction==="bidirectional",onCheckedChange:w=>y.mutate(w?"bidirectional":"pull_only"),disabled:n||y.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ei,{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(G,{onClick:v,disabled:n,children:[e.jsx(Mi,{className:`h-4 w-4 mr-2 ${n?"animate-spin":""}`}),n?"Syncing…":"Sync Now"]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsxs(G,{variant:"outline",disabled:n,children:[e.jsx(yr,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Follow Up Boss?"}),e.jsx(Bo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>x.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(Ne,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:w=>r(w.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(Qr,{className:"h-3 w-3"})]})]})]}),e.jsx(G,{onClick:()=>m.mutate(t),disabled:!t.trim()||m.isPending,children:m.isPending?"Connecting…":"Connect"})]})})]})}function Lpt(){const s=br(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState("Test from ReLevelUp"),[o,c]=k.useState(!1),{data:d,isLoading:h}=mt({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:y}}=await V.auth.getSession();if(!y)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 ${y.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),m=async()=>{if(!t||!n){ue.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:y}}=await V.auth.getSession();if(!y)throw new Error("Not authenticated");const w=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y.access_token}`},body:JSON.stringify({action:"test_send",to:t,from_email:n,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();w.success?ue.success(`Test email sent! Message ID: ${w.messageId}`):ue.error(w.error||"Failed to send test email")}catch(y){ue.error(y.message||"Failed to send test email")}finally{c(!1)}},x=(d==null?void 0:d.configured)===!0;return e.jsxs(ke,{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(Dt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Nr,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Ge,{variant:x?"default":"secondary",children:h?"Checking...":x?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(di,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Oi,{className:"h-3 w-3"})," Not Configured"]})})]})}),x&&e.jsxs(Pe,{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(he,{className:"text-xs",children:"From Email"}),e.jsx(Ne,{placeholder:"notifications@mail.relevelup.com",value:n,onChange:y=>a(y.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"To Email"}),e.jsx(Ne,{placeholder:"your@email.com",value:t,onChange:y=>r(y.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Subject"}),e.jsx(Ne,{value:i,onChange:y=>l(y.target.value),className:"text-sm"})]})]}),e.jsxs(G,{onClick:m,disabled:o,size:"sm",children:[o?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(en,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(G,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(bu,{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)"]})]})]}),!x&&!h&&e.jsx(Pe,{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 Cbe(s){const{data:{session:t}}=await V.auth.getSession();if(!t)throw new Error("Not authenticated");const r=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)}),n=await r.json();if(!r.ok)throw new Error(n.error||"Request failed");return n}function LLs({status:s}){return s==="verified"?e.jsxs(Ge,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(In,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(fn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Ge,{variant:"outline",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"})," Not started"]})}function Ppt({brokerageId:s,onVerifiedSelect:t}){const r=Xt(),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),{data:y,isLoading:v}=mt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:S,error:T}=await V.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(T)throw T;return S||[]}}),w=Ct({mutationFn:async()=>Cbe({action:"request_verification",brokerage_id:s,email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ue.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:S=>ue.error(S.message)}),b=async S=>{var T,A;h(S.id);try{const I=await Cbe({action:"check_status",sender_id:S.id});r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((T=I.sender)==null?void 0:T.status)==="verified"?ue.success(`${S.email} is verified! 🎉`):ue.info(`Status: ${((A=I.sender)==null?void 0:A.status)||"unknown"}`)}catch(I){ue.error(I.message)}finally{h(null)}},N=Ct({mutationFn:async S=>Cbe({action:"delete",sender_id:S}),onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ue.success("Sender removed"),x(null)},onError:S=>ue.error(S.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."})]}),v?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):y&&y.length>0?e.jsx("div",{className:"space-y-2",children:y.map(S=>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:S.email}),e.jsx(LLs,{status:S.status})]}),S.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',S.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S.status==="verified"&&t&&e.jsx(G,{size:"sm",variant:"outline",onClick:()=>t(S.email),children:"Use"}),S.status!=="verified"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>b(S),disabled:d===S.id,title:"Refresh status from AWS",children:d===S.id?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(Mi,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(S),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},S.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(he,{className:"text-xs",children:"Email Address *"}),e.jsx(Ne,{type:"email",value:n,onChange:S=>a(S.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(Ne,{value:i,onChange:S=>l(S.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(G,{size:"sm",onClick:()=>w.mutate(),disabled:!n.trim()||w.isPending,children:[w.isPending?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Ko,{open:!!m,onOpenChange:S=>!S&&x(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Remove this sender?"}),e.jsxs(Bo,{children:['"',m==null?void 0:m.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>m&&N.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function Tbe(s){const{data:{session:t}}=await V.auth.getSession();if(!t)throw new Error("Not authenticated");const r=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)}),n=await r.json();if(!r.ok)throw new Error(n.error||"Request failed");return n}function PLs({status:s}){return s==="verified"?e.jsxs(Ge,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(In,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(fn,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Ge,{variant:"destructive",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Ge,{variant:"outline",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"})," Not started"]})}function DLs({userId:s,onVerifiedSelect:t}){const r=Xt(),[n,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(null),{data:y,isLoading:v}=mt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:S,error:T}=await V.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(T)throw T;return S||[]}}),w=Ct({mutationFn:async()=>Tbe({action:"request_verification",scope:"user",email:n,display_name:i||void 0}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),ue.success("Verification email sent",{description:`Check ${n} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:S=>ue.error(S.message)}),b=async S=>{var T,A;h(S.id);try{const I=await Tbe({action:"check_status",sender_id:S.id});r.invalidateQueries({queryKey:["user-verified-senders",s]}),((T=I.sender)==null?void 0:T.status)==="verified"?ue.success(`${S.email} is verified! 🎉`):ue.info(`Status: ${((A=I.sender)==null?void 0:A.status)||"unknown"}`)}catch(I){ue.error(I.message)}finally{h(null)}},N=Ct({mutationFn:async S=>Tbe({action:"delete",sender_id:S}),onSuccess:()=>{r.invalidateQueries({queryKey:["user-verified-senders",s]}),ue.success("Sender removed"),x(null)},onError:S=>ue.error(S.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."]})]}),v?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):y&&y.length>0?e.jsx("div",{className:"space-y-2",children:y.map(S=>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:S.email}),e.jsx(PLs,{status:S.status})]}),S.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',S.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[S.status==="verified"&&t&&e.jsx(G,{size:"sm",variant:"outline",onClick:()=>t(S.email),children:"Use"}),S.status!=="verified"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>b(S),disabled:d===S.id,title:"Refresh status from AWS",children:d===S.id?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(Mi,{className:"h-4 w-4"})}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>x(S),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},S.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(he,{className:"text-xs",children:"Email Address *"}),e.jsx(Ne,{type:"email",value:n,onChange:S=>a(S.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(Ne,{value:i,onChange:S=>l(S.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(G,{size:"sm",onClick:()=>w.mutate(),disabled:!n.trim()||w.isPending,children:[w.isPending?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Ko,{open:!!m,onOpenChange:S=>!S&&x(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Remove this sender?"}),e.jsxs(Bo,{children:['"',m==null?void 0:m.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>m&&N.mutate(m.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function RLs(){var A,I,D,R,$;const{user:s,isBrokerageManager:t,isAdmin:r,managedBrokerages:n,selectedBrokerageId:a}=js(),i=a||((A=n==null?void 0:n[0])==null?void 0:A.id)||null,l=(t||r)&&!!i,o=Xt(),[c,d]=k.useState(!1),[h,m]=k.useState(""),[x,y]=k.useState(""),{data:v}=mt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await V.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(z)throw z;return F}}),{data:w}=mt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await V.from("profiles").select("email, name").eq("id",s.id).single();if(z)throw z;return F}}),b=((I=v==null?void 0:v.reply_to_email)==null?void 0:I.trim())||((D=w==null?void 0:w.email)==null?void 0:D.trim())||"",N=((R=v==null?void 0:v.display_name)==null?void 0:R.trim())||(($=w==null?void 0:w.name)==null?void 0:$.trim())||"";k.useEffect(()=>{c||(m(b),y(N))},[c,b,N]);const S=Ct({mutationFn:async()=>{if(!s||!h.trim())throw new Error("Please enter a reply-to email");const F={reply_to_email:h.trim(),display_name:x.trim()||null,updated_at:new Date().toISOString()};if(v){const{error:z}=await V.from("mass_email_settings").update(F).eq("user_id",s.id);if(z)throw z}else{const{error:z}=await V.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]}),ue.success("Reply-to email saved!"),d(!1)},onError:F=>ue.error(F.message)}),T=!!b;return e.jsxs(ke,{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(en,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Mass Email",T?e.jsxs(Ge,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(di,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Nr,{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(Pe,{className:"space-y-3",children:[T&&!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:N||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Ea,{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(he,{className:"text-xs",children:"Display Name"}),e.jsx(Ne,{placeholder:"e.g. 🏡 Karen Hall",value:x,onChange:F=>y(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(he,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(Ne,{type:"email",placeholder:"your@email.com",value:h,onChange:F=>m(F.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{size:"sm",onClick:()=>S.mutate(),disabled:S.isPending||!h.trim(),children:[e.jsx(Bl,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{d(!1),m(b),y(N)},children:[e.jsx(vr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(fo,{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(Ey,{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(DLs,{userId:s.id,onVerifiedSelect:F=>{m(F),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(fo,{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(Ey,{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(Ppt,{brokerageId:i})]})]})]})]})}function OLs(){const{isAdmin:s}=js(),t=Xt(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=mt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:A,error:I}=await V.from("gmail_integrations").select("*").maybeSingle();if(I)throw I;return A}}),{data:h}=mt({queryKey:["social-accounts"],queryFn:async()=>{const{data:{user:A}}=await V.auth.getUser();if(!A)return[];const{data:I,error:D}=await V.from("social_accounts").select("*").eq("user_id",A.id).order("created_at",{ascending:!1});if(D)throw D;return I}}),m=async()=>{n(!0);try{const{data:A,error:I}=await V.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(I)throw I;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get authorization URL")}catch(A){console.error("Gmail OAuth error:",A),ue.error("Failed to start Gmail connection"),n(!1)}},x=async A=>{i(!0);try{const{data:I,error:D}=await V.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:A}});if(D)throw D;if(I!=null&&I.authUrl)window.location.href=I.authUrl;else throw new Error("Failed to get authorization URL")}catch(I){console.error("Meta OAuth error:",I),ue.error("Failed to start connection. Make sure Meta App credentials are configured."),i(!1)}},y=async()=>{o(!0);try{const{data:A,error:I}=await V.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(I)throw I;if(A!=null&&A.authUrl)window.location.href=A.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(A){console.error("LinkedIn OAuth error:",A),ue.error("Failed to start LinkedIn connection. Please try again."),o(!1)}},v=Ct({mutationFn:async A=>{const{error:I}=await V.from("gmail_integrations").delete().eq("id",A);if(I)throw I},onSuccess:()=>{t.invalidateQueries({queryKey:["gmail-integration"]}),ue.success("Gmail disconnected")},onError:()=>{ue.error("Failed to disconnect Gmail")}}),w=Ct({mutationFn:async A=>{const{error:I}=await V.from("social_accounts").delete().eq("id",A);if(I)throw I},onSuccess:()=>{t.invalidateQueries({queryKey:["social-accounts"]}),ue.success("Account disconnected")},onError:()=>{ue.error("Failed to disconnect account")}}),b=!!(c!=null&&c.is_active),N=(h==null?void 0:h.filter(A=>A.platform==="facebook"))||[],S=(h==null?void 0:h.filter(A=>A.platform==="instagram"))||[],T=(h==null?void 0:h.filter(A=>A.platform==="linkedin"))||[];return e.jsx(ws,{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(ke,{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(Dt,{className:"text-lg flex items-center gap-2",children:["Gmail",b&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Pe,{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(di,{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(di,{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(di,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),b?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:c.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Gmail?"}),e.jsx(Bo,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>v.mutate(c.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(G,{className:"mt-4",onClick:m,disabled:r||d,children:[r?e.jsx(Mi,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Vs,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(Ha,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(ke,{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(yu,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Facebook",N.length>0&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[N.length>0&&e.jsx("div",{className:"space-y-2",children:N.map(A=>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(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:A.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(yu,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:A.page_name||A.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Facebook?"}),e.jsx(Bo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>w.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}),e.jsxs(G,{onClick:()=>x("facebook"),disabled:a,variant:"outline",className:"gap-2",children:[a?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(ke,{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(Jd,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Instagram",S.length>0&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[S.length>0&&e.jsx("div",{className:"space-y-2",children:S.map(A=>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(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:A.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Jd,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",A.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Instagram?"}),e.jsx(Bo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>w.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}),e.jsxs(G,{onClick:()=>x("instagram"),disabled:a,variant:"outline",className:"gap-2",children:[a?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{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(ke,{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(Jh,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",T.length>0&&e.jsx(Ge,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Nr,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[T.length>0&&e.jsx("div",{className:"space-y-2",children:T.map(A=>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(Nn,{className:"h-8 w-8",children:[e.jsx(ya,{src:A.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Jh,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:A.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect LinkedIn?"}),e.jsx(Bo,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>w.mutate(A.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},A.id))}),e.jsxs(G,{onClick:y,disabled:l,variant:"outline",className:"gap-2",children:[l?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(MLs,{}),e.jsx(ILs,{}),e.jsx(RLs,{}),s&&e.jsx(Lpt,{})]})})}const FLs="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function BLs(){const[s,t]=k.useState(null),[r,n]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",h=window.location.hostname.startsWith("id-preview--"),m=async b=>{const N=new Uint8Array(await b.slice(0,4).arrayBuffer());return N[0]===80&&N[1]===75&&N[2]===3&&N[3]===4||N[0]===80&&N[1]===75&&N[2]===5&&N[3]===6||N[0]===80&&N[1]===75&&N[2]===7&&N[3]===8},x=b=>{const N=document.createElement("a");N.href=b,N.download="levelup-extension.zip",N.rel="noopener noreferrer",N.target="_blank",document.body.appendChild(N),N.click(),N.remove()},y=async()=>{o(!0);try{if(h){x(`${d}?v=${Date.now()}`);return}const b=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!b.ok)throw new Error(`Download failed (${b.status})`);const N=await b.blob();if(!await m(N)){x(`${d}?v=${Date.now()}`);return}const S=new Blob([N],{type:"application/zip"}),T=URL.createObjectURL(S),A=document.createElement("a");A.href=T,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(T),1e3)}catch(b){ue.error(b.message||"Download failed")}finally{o(!1)}},v=async()=>{n(!0);try{await V.auth.refreshSession();const{data:b}=await V.auth.getSession();if(!b.session){ue.error("Your session has expired. Please sign in again.");return}const{data:N,error:S}=await V.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${b.session.access_token}`}});if(S)throw S;t(N.code),i(N.expires_in||300);const T=setInterval(()=>{i(A=>A<=1?(clearInterval(T),t(null),0):A-1)},1e3)}catch(b){console.error("generateCode error",b),ue.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{n(!1)}},w=()=>{s&&(navigator.clipboard.writeText(s),ue.success("Copied"))};return e.jsx(ws,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(nl,{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(L4,{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(ke,{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(G,{size:"lg",className:"w-full",onClick:()=>window.open(FLs,"_blank","noopener,noreferrer"),children:[e.jsx(L4,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Qr,{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(ke,{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(G,{onClick:w,variant:"outline",className:"flex-1",children:[e.jsx(Ra,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(G,{onClick:v,variant:"outline",className:"flex-1",children:[e.jsx(Mi,{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(Kn,{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(G,{onClick:v,disabled:r,size:"lg",className:"w-full",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Mi,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(ke,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Il,{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(G,{variant:"link",className:"h-auto p-0 text-sm",onClick:y,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 zLs(){const[s]=Ac(),t=br(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your Gmail account...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:m,error:x}=await V.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:h}});if(x)throw x;if(m!=null&&m.success)n("success"),i(m.message||"Gmail connected successfully!"),ue.success("Gmail connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Gmail OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Gmail"),ue.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[r==="loading"&&e.jsx(es,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(di,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Sc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"Back to Integrations":"Try Again"})})]})})}function $Ls(){const s=br();return k.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 ULs(){const[s]=Ac(),t=br(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing your connection...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:x,error:y}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(x&&x.success===!1)throw new Error(x.error||"Failed to connect accounts");if(y){let v=y.message||"Failed to connect accounts";try{const w=y.context;if(w&&typeof w.json=="function"){const b=await w.json();b!=null&&b.error&&(v=b.error)}}catch{}throw new Error(v)}if(x!=null&&x.success)n("success"),i(`Successfully connected ${((m=x.accounts)==null?void 0:m.length)||0} account(s)!`),ue.success("Social accounts connected successfully!");else throw new Error((x==null?void 0:x.error)||"Unknown error")}catch(x){console.error("OAuth callback error:",x),n("error"),i(x instanceof Error?x.message:"Failed to connect accounts"),ue.error("Failed to connect: "+(x instanceof Error?x.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[r==="loading"&&e.jsx(es,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(di,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Sc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Integrations":"Try Again"})})]})})}const Dpt=new Date().getFullYear(),qLs=Array.from({length:5},(s,t)=>Dpt-t);function VLs(){const[s,t]=k.useState(Dpt),r=br(),{data:n,isLoading:a}=W$t();return a?e.jsx(ws,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(Fs,{className:"h-24"},i))}),e.jsx(Fs,{className:"h-96"})]})}):e.jsx(ws,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(Is,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(As,{className:"w-[120px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:qLs.map(i=>e.jsx(ct,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pr,{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:(n==null?void 0:n.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ro,{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:(n==null?void 0:n.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Agents with Scorecards"}),e.jsx(Nr,{children:"Click to view individual agent scorecards"})]}),e.jsx(Pe,{children:!n||n.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ro,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:n.map(i=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:i.name}),e.jsx(dt,{className:"text-muted-foreground",children:i.email}),e.jsx(dt,{className:"text-right",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>r(`/admin/scorecard/${i.id}`),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Rpt=new Date().getFullYear(),HLs=Array.from({length:10},(s,t)=>Rpt-t);function Jqe(){var w;const{userId:s}=Ki(),t=br(),n=ec().pathname.startsWith("/mission-control"),[a,i]=k.useState(Rpt),{data:l,isLoading:o}=mt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:b,error:N}=await V.from("profiles").select("id, name, email").eq("id",s).single();if(N)throw N;return b},enabled:!!s}),{data:c,isLoading:d}=c3e(a,s),{yearStats:h,lifetimeStats:m,isLoading:x,showCommission:y}=pnt(a,s),{data:v}=fnt(a,s);return o?e.jsx(ws,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(b=>e.jsx(Fs,{className:"h-24"},b))})]})}):e.jsx(ws,{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(G,{variant:"ghost",size:"icon",onClick:()=>t(n?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:l==null?void 0:l.name}),e.jsx("p",{className:"text-muted-foreground",children:l==null?void 0:l.email})]})]}),e.jsxs(Is,{value:String(a),onValueChange:b=>i(Number(b)),children:[e.jsx(As,{className:"w-[120px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:HLs.map(b=>e.jsx(ct,{value:String(b),children:b},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(En,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:h.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.totalTransactions," lifetime"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pr,{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:[h.buyerCount,"/",h.sellerCount]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:lc(h.totalVolume,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bo,{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:lc(h.averagePrice,!0)})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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=h.topLeadSource)==null?void 0:w.name)||"-"})]})})]}),v&&e.jsx(Wht,{goals:v,stats:h,year:a,showCommission:y}),e.jsxs(On,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Rn,{children:[e.jsx(Kt,{value:"transactions",children:"Transactions"}),e.jsx(Kt,{value:"charts",children:"Charts"}),e.jsxs(Kt,{value:"map",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ts,{value:"transactions",children:e.jsx(OTe,{transactions:c||[],showCommission:y,isLoading:d})}),e.jsx(ts,{value:"charts",children:e.jsx(FTe,{stats:h,year:a})}),e.jsx(ts,{value:"map",children:e.jsx(BTe,{transactions:c||[],isLoading:d})})]})]})})}function GLs(){const s=Xt(),[t,r]=k.useState(""),[n,a]=k.useState("all"),[i,l]=k.useState(null);Dst();const{data:o,refetch:c}=mt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:F}=await V.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(F==null?void 0:F.enabled)??!1}}),{data:d,isLoading:h}=mt({queryKey:["admin-listings"],queryFn:async()=>{const{data:F,error:z}=await V.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:m}=mt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:F}=await V.from("listings").select("id, is_approved, status"),{data:z}=await V.from("listing_shares").select("id"),{data:Q}=await V.from("listing_views").select("id"),{count:K}=await V.from("listing_leads").select("id",{count:"exact",head:!0}),X=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:Z}=await V.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",X);return{total:(F==null?void 0:F.length)||0,pending:(F==null?void 0:F.filter(re=>!re.is_approved).length)||0,active:(F==null?void 0:F.filter(re=>re.status==="active").length)||0,totalShares:(z==null?void 0:z.length)||0,totalViews:(Q==null?void 0:Q.length)||0,totalLeads:K||0,leadsLast7:Z||0}}}),{data:x}=mt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const F={};let z=0;const Q=1e3;for(;;){const{data:K,error:X}=await V.from("listing_leads").select("listing_id").range(z,z+Q-1);if(X)throw X;if(!K||K.length===0)break;for(const Z of K)Z.listing_id&&(F[Z.listing_id]=(F[Z.listing_id]||0)+1);if(K.length{const{data:F,error:z}=await V.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(z)throw z;return F}}),w=async(F,z,Q="submit_url")=>{try{const{data:{session:K}}=await V.auth.getSession();if(!K)return;const{data:X,error:Z}=await V.functions.invoke("google-indexing",{body:{action:Q,listing_id:F,listing_slug:z}});if(Z)throw Z;if((X==null?void 0:X.configured)===!1)return;X!=null&&X.success&&ue.success("Submitted to Google for indexing")}catch(K){console.error("Google indexing submission failed:",K)}},b=Ct({mutationFn:async()=>{const{data:{session:F}}=await V.auth.getSession();if(!F)throw new Error("Not authenticated");const{data:z,error:Q}=await V.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(Q)throw Q;return z},onSuccess:F=>{if((F==null?void 0:F.configured)===!1){ue.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ue.success(`Submitted ${(F==null?void 0:F.succeeded)||0} URLs to Google (${(F==null?void 0:F.failed)||0} failed)`)},onError:F=>{ue.error("Failed to submit to Google"),console.error(F)}}),N=Ct({mutationFn:async({id:F,approved:z,slug:Q})=>{const{error:K}=await V.from("listings").update({is_approved:z}).eq("id",F);if(K)throw K;return{id:F,approved:z,slug:Q}},onSuccess:F=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ue.success(F.approved?"Listing approved":"Listing unapproved"),F.approved?w(F.id,F.slug||null,"submit_url"):w(F.id,F.slug||null,"remove_url")}}),S=Ct({mutationFn:async({id:F,featured:z})=>{const{error:Q}=await V.from("listings").update({is_featured:z}).eq("id",F);if(Q)throw Q},onSuccess:(F,{featured:z})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ue.success(z?"Listing featured":"Listing unfeatured")}}),T=Ct({mutationFn:async F=>{const{error:z}=await V.from("listings").delete().eq("id",F);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ue.success("Listing deleted")}}),A=Ct({mutationFn:async F=>{const{error:z}=await V.from("feature_flags").update({enabled:F}).eq("key","listing_exchange_enabled");if(z)throw z},onSuccess:()=>{c(),ue.success("Feature flag updated")}}),I=o??!1,D=d==null?void 0:d.filter(F=>{var K,X,Z,re;const z=((K=F.city)==null?void 0:K.toLowerCase().includes(t.toLowerCase()))||((Z=(X=F.agent)==null?void 0:X.name)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((re=F.property_address)==null?void 0:re.toLowerCase().includes(t.toLowerCase())),Q=n==="all"||n==="pending"&&!F.is_approved||n==="approved"&&F.is_approved;return z&&Q}),R=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F),$=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(ws,{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(G,{variant:"outline",size:"sm",onClick:()=>b.mutate(),disabled:b.isPending,className:"gap-2",children:[b.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(fc,{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(_r,{checked:I,onCheckedChange:F=>A.mutate(F)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{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:(m==null?void 0:m.total)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bo,{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:(m==null?void 0:m.active)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{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:(m==null?void 0:m.pending)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bn,{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:(m==null?void 0:m.totalViews)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ec,{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:(m==null?void 0:m.totalShares)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(m==null?void 0:m.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(m==null?void 0:m.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(ke,{children:e.jsx(Pe,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by city, address, or agent...",value:t,onChange:F=>r(F.target.value),className:"pl-9"})]}),e.jsx(On,{value:n,onValueChange:F=>a(F),children:e.jsxs(Rn,{children:[e.jsx(Kt,{value:"all",children:"All"}),e.jsx(Kt,{value:"pending",children:"Pending"}),e.jsx(Kt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{children:["Listings (",(D==null?void 0:D.length)||0,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Property"}),e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Price"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-center",children:"Approved"}),e.jsx(Nt,{className:"text-center",children:"Featured"}),e.jsx(Nt,{children:"Views"}),e.jsx(Nt,{children:"Shares"}),e.jsx(Nt,{children:"Leads"}),e.jsx(Nt,{children:"Date"}),e.jsx(Nt,{})]})}),e.jsx($n,{children:h?e.jsx(Ds,{children:e.jsx(dt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):D==null?void 0:D.map(F=>{var z,Q,K,X,Z;return e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(Q=(z=F.photos)==null?void 0:z[0])!=null&&Q.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(Sa,{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:(K=F.property_type)==null?void 0:K.replace("_"," ")})]})]})}),e.jsx(dt,{children:e.jsx("p",{className:"text-sm",children:((X=F.agent)==null?void 0:X.name)||"Unknown"})}),e.jsx(dt,{className:"font-medium",children:R(F.price)}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",className:$(F.status),children:(Z=F.status)==null?void 0:Z.replace("_"," ")})}),e.jsx(dt,{className:"text-center",children:e.jsx(_r,{checked:F.is_approved??!1,onCheckedChange:re=>N.mutate({id:F.id,approved:re,slug:F.slug})})}),e.jsx(dt,{className:"text-center",children:e.jsx(_r,{checked:F.is_featured??!1,onCheckedChange:re=>S.mutate({id:F.id,featured:re})})}),e.jsx(dt,{children:F.view_count||0}),e.jsx(dt,{children:F.share_count||0}),e.jsx(dt,{children:((x==null?void 0:x[F.id])??0)>0?e.jsx(G,{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:x==null?void 0:x[F.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:_s(new Date(F.created_at),"MMM d, yyyy")}),e.jsx(dt,{children:e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",children:e.jsx(Lp,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(Pa,{onClick:()=>window.open(`/mission-control/listings/${F.id}`,"_blank"),children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Pa,{onClick:()=>S.mutate({id:F.id,featured:!F.is_featured}),children:[e.jsx(Xn,{className:"h-4 w-4 mr-2"}),F.is_featured?"Unfeature":"Feature"]}),e.jsxs(Pa,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&T.mutate(F.id)},children:[e.jsx(vr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},F.id)})})]})})})]})]}),e.jsx(fs,{open:!!i,onOpenChange:F=>!F&&l(null),children:e.jsxs(ms,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Leads from listing"}),e.jsx(Hr,{children:i==null?void 0:i.label})]}),v?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(es,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!y||y.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Phone"}),e.jsx(Nt,{children:"Type"}),e.jsx(Nt,{children:"Captured"})]})}),e.jsx($n,{children:y.map(F=>{var z;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:[F.first_name,F.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(dt,{children:F.email}),e.jsx(dt,{children:F.phone||"—"}),e.jsx(dt,{children:e.jsx(Ge,{variant:"outline",children:(z=F.lead_type)==null?void 0:z.replace("_"," ")})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:_s(new Date(F.created_at),"MMM d, yyyy h:mm a")})]},F.id)})})]})]})})]})}const WLs=()=>{var m,x;const[s,t]=k.useState(""),[r,n]=k.useState(null),{data:a,isLoading:i}=mt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:y,error:v}=await V.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(v)throw v;const w=(y==null?void 0:y.map(S=>S.user_id))||[],{data:b}=await V.from("profiles").select("id, name, email").in("id",w);return y==null?void 0:y.map(S=>({...S,profiles:(b==null?void 0:b.find(T=>T.id===S.user_id))||null}))}}),l=a==null?void 0:a.filter(y=>{var w,b,N,S,T;const v=s.toLowerCase();return((b=(w=y.profiles)==null?void 0:w.name)==null?void 0:b.toLowerCase().includes(v))||((S=(N=y.profiles)==null?void 0:N.email)==null?void 0:S.toLowerCase().includes(v))||((T=y.review_text)==null?void 0:T.toLowerCase().includes(v))}),o=a!=null&&a.length?(a.reduce((y,v)=>y+v.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((y,v)=>(y[v.rating]=(y[v.rating]||0)+1,y),{}),d=(a==null?void 0:a.filter(y=>y.posted_to_google).length)||0,h=y=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(v=>e.jsx(Xn,{className:It("h-4 w-4",y>=v?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},v))});return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{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(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Total Reviews"}),e.jsx(Dt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Average Rating"}),e.jsxs(Dt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Xn,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"5-Star Reviews"}),e.jsx(Dt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(ke,{children:e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Nr,{children:"Posted to Google"}),e.jsxs(Dt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Qr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or review...",value:s,onChange:y=>t(y.target.value),className:"pl-9"})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Member"}),e.jsx(Nt,{children:"Rating"}),e.jsx(Nt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Nt,{children:"Google"}),e.jsx(Nt,{children:"Date"})]})}),e.jsx($n,{children:i?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(y=>{var v,w;return e.jsxs(Ds,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>n(y),children:[e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((v=y.profiles)==null?void 0:v.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(w=y.profiles)==null?void 0:w.email})]})}),e.jsx(dt,{children:h(y.rating)}),e.jsx(dt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:y.review_text||"-"})}),e.jsx(dt,{children:y.posted_to_google?e.jsx(Ge,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Ge,{variant:"outline",children:"No"})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:_s(new Date(y.created_at),"MMM d, yyyy")})]},y.id)})})]})})}),e.jsx(fs,{open:!!r,onOpenChange:()=>n(null),children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Review Details"})}),r&&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:((m=r.profiles)==null?void 0:m.name)||"Unknown Member"}),((x=r.profiles)==null?void 0:x.email)&&e.jsxs("a",{href:`mailto:${r.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"}),r.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[h(r.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[r.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:r.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(on,{className:"h-4 w-4"}),_s(new Date(r.created_at),"MMMM d, yyyy 'at' h:mm a")]}),r.posted_to_google?e.jsxs(Ge,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Qr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Ge,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},KLs=[{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"}],YLs=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 ZLs(){const s=Xt(),{user:t}=js(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=mt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:$,error:F}=await V.from("weekly_digest_settings").select("*").single();if(F)throw F;return $}}),{data:h,isLoading:m}=mt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:$,error:F}=await V.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(F)throw F;return $}}),{data:x}=mt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:$,error:F}=await V.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(F)throw F;return $||0}}),{data:y,refetch:v}=mt({queryKey:["digest-queue-status"],queryFn:async()=>{const $=new Date;$.setUTCHours(0,0,0,0);const[F,z,Q,K]=await Promise.all([V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",$.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",$.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",$.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",$.toISOString())]);return{pending:F.count||0,processing:z.count||0,sent:Q.count||0,failed:K.count||0,total:(F.count||0)+(z.count||0)+(Q.count||0)+(K.count||0)}},refetchInterval:5e3});k.useEffect(()=>{if(y&&(y.pending>0||y.processing>0)){const $=setInterval(()=>{v(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval($)}},[y,v,s]);const{data:w=0}=mt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const $=new Date;$.setUTCHours(0,0,0,0);const{count:F,error:z}=await V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",$.toISOString());if(z)throw z;return F||0}}),b=Ct({mutationFn:async $=>{const{error:F}=await V.from("weekly_digest_settings").update($).eq("id",c==null?void 0:c.id);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ue.success("Settings updated")},onError:$=>{ue.error("Failed to update settings: "+$.message)}}),N=async()=>{n(!0);try{const{data:$,error:F}=await V.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(F)throw F;$.queued?ue.success(`${$.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):$.sent!==void 0&&ue.success(`Digest sent! ${$.sent} emails delivered, ${$.failed} failed`),v(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch($){ue.error("Failed to send digest: "+$.message)}finally{n(!1)}},S=async()=>{var $,F,z,Q,K,X;if(!(t!=null&&t.email)){ue.error("No email found for your account");return}i(!0);try{const{data:Z,error:re}=await V.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(re)throw re;const le=Z==null?void 0:Z.resendId,oe=Z==null?void 0:Z.resendDetails,ne=oe==null?void 0:oe.status,ie=(($=oe==null?void 0:oe.body)==null?void 0:$.status)||((z=(F=oe==null?void 0:oe.body)==null?void 0:F.data)==null?void 0:z.status),ye=((K=(Q=oe==null?void 0:oe.body)==null?void 0:Q.error)==null?void 0:K.message)||((X=oe==null?void 0:oe.body)==null?void 0:X.message);ue.success(le?`Preview accepted by email provider (id: ${le})${ne?`, status check: ${ne}`:""}${ie?`, provider: ${ie}`:""}${ye?` (${ye})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(Z){ue.error("Failed to send preview: "+Z.message)}finally{i(!1)}},T=async()=>{o(!0);try{const{data:$,error:F}=await V.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(F)throw F;$.queued===0||$.sent===0&&$.failed===0&&!$.queued?ue.info("No failed emails to retry"):$.queued?ue.success(`${$.queued} emails queued for retry!`):ue.success(`Retry complete! ${$.sent} emails delivered, ${$.failed} failed`),v(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch($){ue.error("Failed to retry: "+$.message)}finally{o(!1)}},A=y!=null&&y.total?Math.round((y.sent+y.failed)/y.total*100):0,I=((y==null?void 0:y.pending)||0)>0||((y==null?void 0:y.processing)||0)>0,{data:D}=mt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var X,Z;const $=new Date;$.setUTCHours(0,0,0,0);const[F,z,Q,K]=await Promise.all([V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",$.toISOString()),V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",$.toISOString()),V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",$.toISOString()),V.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:F.count||0,totalFailed:z.count||0,agentOsEngaged:Q.count||0,lastSent:((Z=(X=K.data)==null?void 0:X[0])==null?void 0:Z.sent_at)||null}},refetchInterval:I?5e3:!1}),R={totalSent:(D==null?void 0:D.totalSent)||0,totalFailed:(D==null?void 0:D.totalFailed)||0,lastSent:D==null?void 0:D.lastSent,agentOsEngaged:(D==null?void 0:D.agentOsEngaged)||0};return d?e.jsx(ws,{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(ws,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(On,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(oo,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Kt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(ro,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(ts,{value:"settings",className:"space-y-6",children:[I&&y&&e.jsx(ke,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Pe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(es,{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:[y.sent.toLocaleString()," sent, ",y.pending.toLocaleString()," pending",y.failed>0&&`, ${y.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(ei,{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(y.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(ke,{children:e.jsx(Pe,{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(pr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:x}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{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(In,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{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(Sc,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(ke,{children:e.jsx(Pe,{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(fn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.lastSent?_s(new Date(R.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(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(fn,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Nr,{children:"Configure when the digest is sent"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(_r,{checked:c==null?void 0:c.is_enabled,onCheckedChange:$=>b.mutate({is_enabled:$})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Cron Frequency"}),e.jsxs(Is,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:$=>b.mutate({cron_frequency:$}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(ct,{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(he,{children:"Day of Week"}),e.jsxs(Is,{value:String(c==null?void 0:c.send_day),onValueChange:$=>b.mutate({send_day:parseInt($)}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:KLs.map($=>e.jsx(ct,{value:$.value,children:$.label},$.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Time (UTC)"}),e.jsxs(Is,{value:String(c==null?void 0:c.send_hour),onValueChange:$=>b.mutate({send_hour:parseInt($)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:YLs.map($=>e.jsx(ct,{value:$.value,children:$.label},$.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{onClick:S,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(bn,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(G,{onClick:N,disabled:r,className:"flex-1",children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),r?"Sending...":"Send to All"]})]}),w>0&&e.jsxs(G,{onClick:T,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Mi,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${w} Failed`]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Nr,{children:"Choose what to include in the digest"})]}),e.jsxs(Pe,{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(ln,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"New Resources"})]}),e.jsx(_r,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:$=>b.mutate({include_new_resources:$})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Community Highlights"})]}),e.jsx(_r,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:$=>b.mutate({include_community_posts:$})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ro,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Agent OS Stats"})]}),e.jsx(_r,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:$=>b.mutate({include_agent_os_stats:$})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Upcoming Events"})]}),e.jsx(_r,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:$=>b.mutate({include_upcoming_events:$})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pd,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(he,{children:"Goals Progress"})]}),e.jsx(_r,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:$=>b.mutate({include_goals_progress:$})})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Custom Introduction"}),e.jsx(Nr,{children:"Personalize the intro message (optional)"})]}),e.jsx(Pe,{children:e.jsx(or,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:$=>b.mutate({custom_intro_text:$.target.value||null}),rows:3})})]})]}),e.jsx(ts,{value:"stats",children:e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Nr,{children:"Recent digest emails sent to members"})]}),e.jsx(Pe,{children:m?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map($=>e.jsx("div",{className:"h-12 bg-muted rounded"},$))}):h&&h.length>0?e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Email"}),e.jsx(Nt,{children:"Sent At"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Resources"}),e.jsx(Nt,{children:"Agent OS"})]})}),e.jsx($n,{children:h.map($=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:$.email_sent_to}),e.jsx(dt,{children:_s(new Date($.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(dt,{children:e.jsx(Ge,{variant:$.delivery_status==="sent"?"default":"destructive",children:$.delivery_status})}),e.jsx(dt,{children:$.resources_count}),e.jsx(dt,{children:$.has_agent_os_activity?e.jsx(Ge,{variant:"secondary",children:"Active"}):e.jsx(Ge,{variant:"outline",children:"Not Started"})})]},$.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 XLs={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 QLs(){var ve,be,Ue;const s=Xt(),[t,r]=k.useState(""),[n,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(!0),[w,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState(null),{data:I,isLoading:D}=mt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Be,error:De}=await V.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(De)throw De;const Ae=(Be==null?void 0:Be.map(Ie=>Ie.user_id))||[],{data:He}=await V.from("profiles").select("id, name, email").in("id",Ae),Le=new Map((He==null?void 0:He.map(Ie=>[Ie.id,{name:Ie.name,email:Ie.email}]))||[]);return Be==null?void 0:Be.map(Ie=>({...Ie,profile:Le.get(Ie.user_id)||null}))}}),{data:R}=mt({queryKey:["all-profiles-for-points",I],queryFn:async()=>{const De=[];let Ae=0;for(;;){const{data:He,error:Le}=await V.from("profiles").select("id, name, email").order("name").range(Ae,Ae+1e3-1);if(Le)throw Le;if(De.push(...He),!He||He.length<1e3)break;Ae+=1e3}return De}}),F=((R==null?void 0:R.filter(Be=>!(I!=null&&I.some(De=>De.user_id===Be.id))))||[]).filter(Be=>{var Ae,He;if(!N)return!0;const De=N.toLowerCase();return((Ae=Be.name)==null?void 0:Ae.toLowerCase().includes(De))||((He=Be.email)==null?void 0:He.toLowerCase().includes(De))}),{data:z,isLoading:Q}=mt({queryKey:["agent-point-history",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Be,error:De}=await V.from("agent_points").select("*").eq("user_id",n.user_id).order("created_at",{ascending:!1});if(De)throw De;return Be},enabled:!!(n!=null&&n.user_id)&&o}),{data:K}=mt({queryKey:["agent-badges",n==null?void 0:n.user_id],queryFn:async()=>{if(!(n!=null&&n.user_id))return[];const{data:Be,error:De}=await V.from("agent_badges").select("*").eq("user_id",n.user_id).order("earned_at",{ascending:!1});if(De)throw De;return Be},enabled:!!(n!=null&&n.user_id)}),X=Ct({mutationFn:async({userId:Be,points:De,reason:Ae})=>{const{error:He}=await V.from("agent_points").insert({user_id:Be,points:De,reason:Ae});if(He)throw He;const{data:Le}=await V.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Be).maybeSingle(),Ie=((Le==null?void 0:Le.total_points)||0)+De,Te=((Le==null?void 0:Le.spendable_points)||0)+De,{error:xe}=await V.from("agent_attendance_stats").upsert({user_id:Be,total_points:Math.max(0,Ie),spendable_points:Math.max(0,Te),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(xe)throw xe},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),h(""),x(""),ue.success(y?"Points awarded successfully!":"Points deducted successfully!")},onError:Be=>{console.error("Error modifying points:",Be),ue.error("Failed to modify points")}}),Z=()=>{if(!n||!d||!m){ue.error("Please fill in all fields");return}const Be=parseInt(d);if(isNaN(Be)||Be<=0){ue.error("Please enter a valid positive number");return}X.mutate({userId:n.user_id,points:y?Be:-Be,reason:m})},re=()=>{if(!T||!d||!m){ue.error("Please fill in all fields");return}const Be=parseInt(d);if(isNaN(Be)||Be<=0){ue.error("Please enter a valid positive number");return}X.mutate({userId:T.id,points:Be,reason:m},{onSuccess:()=>{b(!1),A(null),S("")}})},le=(Be,De)=>{a(Be),v(De),l(!0)},oe=Be=>{a(Be),c(!0)},ne=I==null?void 0:I.filter(Be=>{var Le,Ie,Te,xe;const De=((Ie=(Le=Be.profile)==null?void 0:Le.name)==null?void 0:Ie.toLowerCase())||"",Ae=((xe=(Te=Be.profile)==null?void 0:Te.email)==null?void 0:xe.toLowerCase())||"",He=t.toLowerCase();return De.includes(He)||Ae.includes(He)}),ie=(I==null?void 0:I.reduce((Be,De)=>Be+De.total_points,0))||0,ye=(I==null?void 0:I.length)||0,ce=ye>0?Math.round(ie/ye):0;return D?e.jsx(ws,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Be=>e.jsx(Fs,{className:"h-24"},Be))}),e.jsx(Fs,{className:"h-96"})]})}):e.jsx(ws,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pr,{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:ye}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Gi,{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:ie.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(bo,{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:ce}),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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search agents...",value:t,onChange:Be=>r(Be.target.value),className:"pl-10"})]}),e.jsxs(G,{onClick:()=>b(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Agent Leaderboard"}),e.jsx(Nr,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Pe,{children:!ne||ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Gi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-12",children:"#"}),e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{className:"text-center",children:"Total Points"}),e.jsx(Nt,{className:"text-center",children:"Spendable"}),e.jsx(Nt,{className:"text-center",children:"Events"}),e.jsx(Nt,{className:"text-center",children:"Streak"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:ne.map((Be,De)=>{var Ae,He,Le,Ie;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:De<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${De===0?"bg-yellow-100 text-yellow-700":De===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:De+1}):e.jsx("span",{className:"text-muted-foreground",children:De+1})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Nn,{className:"h-8 w-8",children:e.jsx(kn,{children:((He=(Ae=Be.profile)==null?void 0:Ae.name)==null?void 0:He.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Le=Be.profile)==null?void 0:Le.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Ie=Be.profile)==null?void 0:Ie.email})]})]})}),e.jsx(dt,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),Be.total_points]})}),e.jsx(dt,{className:"text-center",children:e.jsxs(Ge,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(ii,{className:"h-3 w-3 mr-1"}),Be.spendable_points||0]})}),e.jsx(dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(on,{className:"h-3 w-3 text-muted-foreground"}),Be.total_events_attended]})}),e.jsx(dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(mc,{className:"h-3 w-3 text-orange-500"}),Be.current_streak]})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>le(Be,!0),title:"Award points",children:e.jsx($s,{className:"h-4 w-4 text-green-600"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>le(Be,!1),title:"Deduct points",children:e.jsx(av,{className:"h-4 w-4 text-red-600"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>oe(Be),title:"View history",children:e.jsx(gA,{className:"h-4 w-4"})})]})})]},Be.user_id)})})]})})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:y?"Award Points":"Deduct Points"}),e.jsxs(Hr,{children:[y?"Award":"Deduct"," points ",y?"to":"from"," ",((ve=n==null?void 0:n.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(he,{htmlFor:"points",children:"Points Amount"}),e.jsx(Ne,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Be=>h(Be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"reason",children:"Reason"}),e.jsx(or,{id:"reason",placeholder:"Enter reason for this adjustment...",value:m,onChange:Be=>x(Be.target.value)})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:Z,disabled:X.isPending,className:y?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:X.isPending?"Saving...":y?"Award Points":"Deduct Points"})]})]})}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsxs(gs,{children:["Point History: ",(be=n==null?void 0:n.profile)==null?void 0:be.name]}),e.jsx(Hr,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(On,{defaultValue:"history",className:"w-full",children:[e.jsxs(Rn,{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(ts,{value:"history",className:"mt-4",children:Q?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Be=>e.jsx(Fs,{className:"h-12"},Be))}):!z||z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(gA,{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(Be=>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:Be.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_s(new Date(Be.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Ge,{variant:Be.points>=0?"default":"destructive",className:Be.points>=0?"bg-green-100 text-green-800":"",children:[Be.points>=0?"+":"",Be.points]})]},Be.id))})}),e.jsx(ts,{value:"badges",className:"mt-4",children:!K||K.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Yl,{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:K.map(Be=>e.jsxs("div",{className:`p-3 rounded-lg ${XLs[Be.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Be.badge_name})]}),Be.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Be.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",_s(new Date(Be.earned_at),"MMM d, yyyy")]})]},Be.id))})})]})]})}),e.jsx(fs,{open:w,onOpenChange:Be=>{b(Be),Be||(A(null),S(""),h(""),x(""))},children:e.jsxs(ms,{className:"max-w-md",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Award Points to New Agent"}),e.jsx(Hr,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:T?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Nn,{className:"h-10 w-10",children:e.jsx(kn,{children:((Ue=T.name)==null?void 0:Ue.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:T.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:T.email})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>A(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(Ne,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Be=>h(Be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"new-reason",children:"Reason"}),e.jsx(or,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:m,onChange:Be=>x(Be.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:N,onChange:Be=>S(Be.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(pr,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:N?"No matching agents found":"All agents already have points"})]}):F.slice(0,20).map(Be=>{var De;return e.jsxs("button",{onClick:()=>A(Be),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(Nn,{className:"h-8 w-8",children:e.jsx(kn,{children:((De=Be.name)==null?void 0:De.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Be.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Be.email})]})]},Be.id)})})]})}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),T&&e.jsxs(G,{onClick:re,disabled:X.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function JLs(){const{data:s,isLoading:t}=XAt(),[r,n]=k.useState(null),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState("all"),[h,m]=k.useState("newest"),[x,y]=k.useState("table"),v=k.useMemo(()=>(s==null?void 0:s.map(T=>T.user_id))||[],[s]),w=k.useMemo(()=>(s==null?void 0:s.map(T=>T.id))||[],[s]),{data:b}=mt({queryKey:["card-profiles-lookup",v],queryFn:async()=>{if(v.length===0)return{};const{data:T}=await V.from("profiles").select("id, name, email").in("id",v),A={};return T==null||T.forEach(I=>{A[I.id]={name:I.name||"",email:I.email||""}}),A},enabled:v.length>0}),{data:N}=mt({queryKey:["card-stats-all",w],queryFn:async()=>{if(w.length===0)return{};const T={};w.forEach(D=>{T[D]={views:0,leads:0}});const{data:A}=await V.from("agent_card_interactions").select("card_id").in("card_id",w).eq("interaction_type","card_view");A==null||A.forEach(D=>{T[D.card_id]&&T[D.card_id].views++});const{data:I}=await V.from("agent_card_leads").select("card_id").in("card_id",w);return I==null||I.forEach(D=>{T[D.card_id]&&T[D.card_id].leads++}),T},enabled:w.length>0}),S=k.useMemo(()=>{if(!s)return[];let T=[...s];if(c==="live"?T=T.filter(A=>A.is_published):c==="draft"&&(T=T.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();T=T.filter(I=>{var R,$;const D=b==null?void 0:b[I.user_id];return I.slug.toLowerCase().includes(A)||((R=D==null?void 0:D.name)==null?void 0:R.toLowerCase().includes(A))||(($=D==null?void 0:D.email)==null?void 0:$.toLowerCase().includes(A))})}return h==="newest"?T.sort((A,I)=>new Date(I.created_at).getTime()-new Date(A.created_at).getTime()):h==="oldest"?T.sort((A,I)=>new Date(A.created_at).getTime()-new Date(I.created_at).getTime()):h==="name"?T.sort((A,I)=>{var D,R;return(((D=b==null?void 0:b[A.user_id])==null?void 0:D.name)||"").localeCompare(((R=b==null?void 0:b[I.user_id])==null?void 0:R.name)||"")}):h==="slug"?T.sort((A,I)=>A.slug.localeCompare(I.slug)):h==="views_desc"?T.sort((A,I)=>{var D,R;return(((D=N==null?void 0:N[I.id])==null?void 0:D.views)||0)-(((R=N==null?void 0:N[A.id])==null?void 0:R.views)||0)}):h==="views_asc"?T.sort((A,I)=>{var D,R;return(((D=N==null?void 0:N[A.id])==null?void 0:D.views)||0)-(((R=N==null?void 0:N[I.id])==null?void 0:R.views)||0)}):h==="leads_desc"?T.sort((A,I)=>{var D,R;return(((D=N==null?void 0:N[I.id])==null?void 0:D.leads)||0)-(((R=N==null?void 0:N[A.id])==null?void 0:R.leads)||0)}):h==="leads_asc"&&T.sort((A,I)=>{var D,R;return(((D=N==null?void 0:N[A.id])==null?void 0:D.leads)||0)-(((R=N==null?void 0:N[I.id])==null?void 0:R.leads)||0)}),T},[s,c,l,h,b]);return e.jsxs(ws,{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(G,{onClick:()=>i(!0),children:[e.jsx($s,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name, email, or slug...",value:l,onChange:T=>o(T.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:c,onValueChange:d,children:[e.jsx(As,{className:"w-full sm:w-36",children:e.jsx(Ls,{placeholder:"Status"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All Status"}),e.jsx(ct,{value:"live",children:"Live"}),e.jsx(ct,{value:"draft",children:"Draft"})]})]}),e.jsxs(Is,{value:h,onValueChange:m,children:[e.jsx(As,{className:"w-full sm:w-44",children:e.jsx(Ls,{placeholder:"Sort by"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"newest",children:"Newest First"}),e.jsx(ct,{value:"oldest",children:"Oldest First"}),e.jsx(ct,{value:"name",children:"Name A–Z"}),e.jsx(ct,{value:"slug",children:"Slug A–Z"}),e.jsx(ct,{value:"views_desc",children:"Most Views"}),e.jsx(ct,{value:"views_asc",children:"Fewest Views"}),e.jsx(ct,{value:"leads_desc",children:"Most Leads"}),e.jsx(ct,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(G,{variant:x==="table"?"default":"ghost",size:"sm",onClick:()=>y("table"),className:"rounded-r-none",children:e.jsx(kA,{className:"h-4 w-4"})}),e.jsx(G,{variant:x==="grid"?"default":"ghost",size:"sm",onClick:()=>y("grid"),className:"rounded-l-none",children:e.jsx(xf,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",S.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(T=>e.jsx(Fs,{className:"h-48"},T))}):S.length>0?x==="table"?e.jsx(ePs,{cards:S,cardProfiles:b,cardStats:N,onEdit:n,sortBy:h,setSortBy:m}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:S.map(T=>e.jsx(tPs,{card:T,onEdit:()=>n(T),stats:N==null?void 0:N[T.id]},T.id))}):s&&s.length>0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(yn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(pr,{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(G,{onClick:()=>i(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(sPs,{open:a,onOpenChange:i}),r&&e.jsx(rPs,{card:r,open:!!r,onOpenChange:T=>!T&&n(null)})]})}function ePs({cards:s,cardProfiles:t,cardStats:r,onEdit:n,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(Hu,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Id,{className:"h-3 w-3"}):e.jsx(Ad,{className:"h-3 w-3 opacity-40"});return e.jsx(ke,{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(Id,{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],h=r==null?void 0:r[c.id],m=`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(Ge,{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:(h==null?void 0:h.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(h==null?void 0:h.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>n(c),className:"h-8 w-8 p-0",children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(m),ue.success("Link copied!")},children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Qr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function tPs({card:s,onEdit:t,stats:r}){const[n,a]=k.useState(null);k.useEffect(()=>{(async()=>{const{data:c}=await V.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:h}=await V.storage.from("avatars").list(`${s.user_id}`);if(h&&h.length>0){const{data:m}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${h[0].name}`);d=m.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),ue.success("Link copied!")};return e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:(n==null?void 0:n.avatar_url)||void 0}),e.jsx(kn,{children:((n==null?void 0:n.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(n==null?void 0:n.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Ge,{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(bn,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),(r==null?void 0:r.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Ea,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(G,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Ra,{className:"h-3 w-3"})}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Qr,{className:"h-3 w-3"})})})]})]})})}function sPs({open:s,onOpenChange:t}){const[r,n]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(!1),h=IJe(),m=l.trim(),{data:x}=mt({queryKey:["profiles-search-for-cards",m],queryFn:async()=>{let S=V.from("profiles").select("id, name, email").order("name").limit(50);m.length>=2&&(S=S.or(`name.ilike.%${m}%,email.ilike.%${m}%`));const{data:T}=await S;return T||[]},enabled:s}),[y,v]=k.useState(null),w=(x==null?void 0:x.find(S=>S.id===r))||y,b=()=>{if(!r||!a.trim()){ue.error("Select an agent and enter a slug");return}h.mutate({user_id:r,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),n(""),i(""),o("")}})},N=S=>{var A;n(S),d(!1);const T=x==null?void 0:x.find(I=>I.id===S);T&&(v(T),i(((A=T.name)==null?void 0:A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create Agent Card"}),e.jsx(Hr,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Agent"}),e.jsxs(To,{open:c,onOpenChange:d,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[w?`${w.name} (${w.email})`:"Search for an agent...",e.jsx(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(rx,{shouldFilter:!1,children:[e.jsx(nx,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(ax,{children:[e.jsx(ix,{children:"No agents found."}),e.jsx(ox,{children:(x||[]).map(S=>e.jsxs(cf,{value:S.id,onSelect:N,children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4",r===S.id?"opacity-100":"opacity-0")}),S.name," (",S.email,")"]},S.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:a,onChange:S=>i(S.target.value),placeholder:"john-doe"})]})]}),e.jsx(G,{onClick:b,disabled:h.isPending,className:"w-full",children:h.isPending?"Creating...":"Create Card"})]})]})})}function rPs({card:s,open:t,onOpenChange:r}){const n=LJe(),{data:a}=PJe(s.id),i=Xt(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(!1),[x,y]=k.useState(""),[v,w]=k.useState(s.slug),[b,N]=k.useState(!1),[S,T]=k.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});k.useEffect(()=>{t&&(async()=>{try{const{data:z}=await V.storage.from("avatars").list(`${s.user_id}`);if(z&&z.length>0){const{data:Q}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${z[0].name}`);o(`${Q.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=F=>{var K;const z=(K=F.target.files)==null?void 0:K[0];if(!z)return;if(!z.type.startsWith("image/")){ue.error("Please select an image file");return}if(z.size>5*1024*1024){ue.error("Image must be under 5MB");return}const Q=new FileReader;Q.onloadend=()=>{y(Q.result),m(!0)},Q.readAsDataURL(z),F.target.value=""},I=async F=>{d(!0);try{const{data:z}=await V.storage.from("avatars").list(`${s.user_id}`);z&&z.length>0&&await V.storage.from("avatars").remove(z.map(re=>`${s.user_id}/${re.name}`));const Q=`${s.user_id}/avatar.jpg`,{error:K}=await V.storage.from("avatars").upload(Q,F,{upsert:!0,contentType:"image/jpeg"});if(K)throw K;const{data:X}=V.storage.from("avatars").getPublicUrl(Q),Z=`${X.publicUrl}?t=${Date.now()}`;o(Z),await V.from("profiles").update({avatar_url:Z}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ue.success("Photo updated!")}catch(z){ue.error(z.message||"Upload failed")}finally{d(!1)}},D=async()=>{const F=v.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!F){ue.error("Please enter a valid URL");return}if(F===s.slug){ue.info("No changes to save");return}N(!0);try{const{data:z}=await V.from("agent_cards").select("id").eq("slug",F).neq("id",s.id).maybeSingle();if(z){ue.error("This URL is already taken. Try another one.");return}const{error:Q}=await V.from("agent_cards").update({slug:F}).eq("id",s.id);if(Q)throw Q;w(F),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ue.success("Card address updated!")}catch{ue.error("Failed to update card address")}finally{N(!1)}},R=async(F,z)=>{var K;const Q=(K=F.target.files)==null?void 0:K[0];if(Q){if(!Q.type.startsWith("image/")){ue.error("Please select an image file");return}try{const X=Q.name.split(".").pop()||"png",Z=z==="brokerage_logo_url"?"brokerage-logo":"team-logo",re=`${s.user_id}/${Z}.${X}`,{error:le}=await V.storage.from("card-logos").upload(re,Q,{upsert:!0});if(le)throw le;const{data:oe}=V.storage.from("card-logos").getPublicUrl(re),ne=oe.publicUrl+"?t="+Date.now();T(z==="brokerage_logo_url"?ie=>({...ie,[z]:ne,brokerage_display_name:""}):ie=>({...ie,[z]:ne,team_name:""})),ue.success("Logo uploaded!")}catch{ue.error("Failed to upload logo")}finally{F.target.value=""}}},$=()=>{n.mutate({id:s.id,...S,title:S.title||null,positioning_statement:S.positioning_statement||null,bio:S.bio||null,review_snippet:S.review_snippet||null,review_source_url:S.review_source_url||null,booking_url:S.booking_url||null,custom_cta_label:S.custom_cta_label||null,custom_cta_url:S.custom_cta_url||null,brokerage_display_name:S.brokerage_display_name||null,brokerage_logo_url:S.brokerage_logo_url||null,brokerage_logo_size:S.brokerage_logo_size,team_name:S.team_name||null,team_logo_url:S.team_logo_url||null,team_logo_size:S.team_logo_size},{onSuccess:()=>r(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Edit Agent Card"}),e.jsxs(Hr,{children:["/card/",s.slug]})]}),e.jsxs(On,{defaultValue:"content",children:[e.jsxs(Rn,{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(ts,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Published"}),e.jsx(_r,{checked:S.is_published,onCheckedChange:F=>T(z=>({...z,is_published:F}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Nn,{className:"h-16 w-16",children:[e.jsx(ya,{src:l||void 0}),e.jsx(kn,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,disabled:c}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{value:v,onChange:F=>w(F.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(G,{variant:"outline",size:"sm",onClick:D,disabled:b||v===s.slug,className:"shrink-0",children:b?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Theme"}),e.jsxs(Is,{value:S.theme,onValueChange:F=>T(z=>({...z,theme:F})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(ct,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(ct,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(ct,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Title / Tagline"}),e.jsx(Ne,{value:S.title,onChange:F=>T(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(he,{children:"Positioning Statement"}),e.jsx(Ne,{value:S.positioning_statement,onChange:F=>T(z=>({...z,positioning_statement:F.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Bio"}),e.jsx(or,{value:S.bio,onChange:F=>T(z=>({...z,bio:F.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Review Snippet"}),e.jsx(Ne,{value:S.review_snippet,onChange:F=>T(z=>({...z,review_snippet:F.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Review Source URL"}),e.jsx(Ne,{value:S.review_source_url,onChange:F=>T(z=>({...z,review_source_url:F.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(Ne,{value:S.booking_url,onChange:F=>T(z=>({...z,booking_url:F.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Custom CTA Label (optional)"}),e.jsx(Ne,{value:S.custom_cta_label,onChange:F=>T(z=>({...z,custom_cta_label:F.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Custom CTA URL (optional)"}),e.jsx(Ne,{value:S.custom_cta_url,onChange:F=>T(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(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ne,{value:S.brokerage_display_name,onChange:F=>T(z=>({...z,brokerage_display_name:F.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!S.brokerage_logo_url}),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:()=>T(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(da,{className:"h-3.5 w-3.5"}),S.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>R(F,"brokerage_logo_url")})]})]}),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(he,{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(_y,{value:[S.brokerage_logo_size||56],onValueChange:([F])=>T(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(he,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ne,{value:S.team_name,onChange:F=>T(z=>({...z,team_name:F.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!S.team_logo_url}),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:()=>T(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(da,{className:"h-3.5 w-3.5"}),S.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>R(F,"team_logo_url")})]})]}),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(he,{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(_y,{value:[S.team_logo_size||56],onValueChange:([F])=>T(z=>({...z,team_logo_size:F})),min:24,max:120,step:4})]})]})]})]}),e.jsx(ts,{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:Q})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(he,{children:z}),Q&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Q," ",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(_r,{checked:S[F],onCheckedChange:K=>T(X=>({...X,[F]:K}))})]},F))}),e.jsx(ts,{value:"blocks",className:"mt-4",children:e.jsx(_pt,{cardId:s.id})}),e.jsx(ts,{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(ke,{children:e.jsxs(Pe,{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(ke,{children:e.jsxs(Pe,{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(ke,{children:e.jsxs(Pe,{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(Ge,{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(G,{onClick:$,disabled:n.isPending,className:"w-full mt-4",children:n.isPending?"Saving...":"Save Changes"})]})}),e.jsx(e5e,{open:h,onClose:()=>m(!1),imageSrc:x,onCropComplete:I,aspectRatio:1})]})}const ZA={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"},$Ee={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 UEe(s=!0){return mt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=V.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:r,error:n}=await t;if(n)throw n;return r}})}function nPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ue.success("Category created successfully")},onError:t=>{ue.error("Failed to create category: "+t.message)}})}function aPs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("marketplace_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ue.success("Category updated successfully")},onError:t=>{ue.error("Failed to update category: "+t.message)}})}function iPs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("marketplace_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ue.success("Category deleted successfully")},onError:t=>{ue.error("Failed to delete category: "+t.message)}})}function Opt(s,t=!0){return mt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let r=V.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&&(r=r.eq("category_id",s)),t&&(r=r.eq("is_active",!0));const{data:n,error:a}=await r;if(a)throw a;return n}})}function oPs(s){return mt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:r}=await V.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function lPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_products").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ue.success("Product created successfully")},onError:t=>{ue.error("Failed to create product: "+t.message)}})}function cPs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("marketplace_products").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.id]}),ue.success("Product updated successfully")},onError:t=>{ue.error("Failed to update product: "+t.message)}})}function dPs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("marketplace_products").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ue.success("Product deleted successfully")},onError:t=>{ue.error("Failed to delete product: "+t.message)}})}function uPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_product_images").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]})}})}function hPs(){const s=Xt();return Ct({mutationFn:async({id:t,productId:r})=>{const{error:n}=await V.from("marketplace_product_images").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ue.success("Image deleted successfully")},onError:t=>{ue.error("Failed to delete image: "+t.message)}})}function mPs(){const s=Xt();return Ct({mutationFn:async({imageId:t,productId:r})=>{const{error:n}=await V.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:a}=await V.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ue.success("Primary image updated")},onError:t=>{ue.error("Failed to set primary image: "+t.message)}})}function fPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("marketplace_product_variants").insert([t]).select().single();if(n)throw n;return r},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.product_id]}),ue.success("Variant added successfully")}})}function pPs(){const s=Xt();return Ct({mutationFn:async({id:t,productId:r})=>{const{error:n}=await V.from("marketplace_product_variants").delete().eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ue.success("Variant deleted successfully")}})}function xPs(){const s=Xt();return Ct({mutationFn:async({productId:t,videoUrl:r})=>{await V.from("marketplace_product_videos").delete().eq("product_id",t);const{data:n,error:a}=await V.from("marketplace_product_videos").insert({product_id:t,video_url:r}).select().single();if(a)throw a;return n},onSuccess:(t,r)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",r.productId]}),ue.success("Video updated successfully")}})}function gPs(s){const{isAdmin:t}=js();return mt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let r=V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:n,error:a}=await r;if(a)throw a;if(t&&n){const i=[...new Set(n.map(c=>c.user_id))],{data:l}=await V.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return n.map(c=>({...c,user:o.get(c.user_id)}))}return n}})}function yPs(){const{user:s}=js();return mt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!(s!=null&&s.id)})}function vPs(s){return mt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:r}=await V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(r)throw r;return t},enabled:!!s})}function bPs(){const s=Xt(),{user:t}=js();return Ct({mutationFn:async({orderId:r,status:n,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:n};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await V.from("marketplace_orders").update(c).eq("id",r);if(d)throw d;const{error:h}=await V.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:a,created_by:t==null?void 0:t.id});if(h)throw h;if(["shipped","in_production","processing","completed"].includes(n)&&n!==o)try{await V.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:i,trackingUrl:l}})}catch(x){console.error("Failed to send notification email:",x)}},onSuccess:(r,n)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Order status updated")},onError:r=>{ue.error("Failed to update order: "+r.message)}})}function _Ps(){const s=Xt();return Ct({mutationFn:async({itemId:t,proofUrl:r,proofNotes:n,orderId:a})=>{const{error:i}=await V.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",t);if(i)throw i;await V.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await V.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"]}),ue.success("Proof uploaded & customer notified")}})}function wPs(){const s=Xt();return Ct({mutationFn:async({itemId:t,orderId:r})=>{const{error:n}=await V.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(n)throw n;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Proof approved")}})}function jPs(){const s=Xt();return Ct({mutationFn:async({itemId:t,orderId:r,reason:n})=>{const{error:a}=await V.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ue.success("Proof rejected - please upload a new proof")}})}function NPs(){const{data:s,isLoading:t}=UEe(!1),r=nPs(),n=aPs(),a=iPs(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),m=()=>{h({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},x=w=>{c(w),h({name:w.name,description:w.description||"",image_url:w.image_url||"",sort_order:w.sort_order,is_active:w.is_active}),l(!0)},y=async w=>{w.preventDefault(),o?await n.mutateAsync({id:o.id,...d}):await r.mutateAsync(d),l(!1),m()},v=async w=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(w)};return t?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Fs,{className:"h-8 w-48"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(w=>e.jsx(Fs,{className:"h-12 w-full"},w))})})]}):e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"Categories"}),e.jsxs(fs,{open:i,onOpenChange:w=>{l(w),w||m()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"name",children:"Name"}),e.jsx(Ne,{id:"name",value:d.name,onChange:w=>h({...d,name:w.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",value:d.description,onChange:w=>h({...d,description:w.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"image_url",children:"Image URL"}),e.jsx(Ne,{id:"image_url",value:d.image_url,onChange:w=>h({...d,image_url:w.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(Ne,{id:"sort_order",type:"number",value:d.sort_order,onChange:w=>h({...d,sort_order:parseInt(w.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"is_active",checked:d.is_active,onCheckedChange:w=>h({...d,is_active:w})}),e.jsx(he,{htmlFor:"is_active",children:"Active"})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:r.isPending||n.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Pe,{children:s&&s.length>0?e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{children:"Sort Order"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:s.map(w=>e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium",children:w.name}),e.jsx(dt,{className:"max-w-xs truncate",children:w.description}),e.jsx(dt,{children:w.sort_order}),e.jsx(dt,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${w.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:w.is_active?"Active":"Inactive"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>x(w),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(w.id),disabled:a.isPending,children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},w.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function kPs(){var ce,ve;const{data:s,isLoading:t}=Opt(void 0,!1),{data:r}=UEe(!1),n=lPs(),a=cPs(),i=dPs(),l=uPs(),o=hPs(),c=mPs(),d=fPs(),h=pPs(),m=xPs(),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState(null),[A,I]=k.useState(null),[D,R]=k.useState(!1),[$,F]=k.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,Q]=k.useState({name:"",price_adjustment:0}),[K,X]=k.useState(""),Z=()=>{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}),T(null)},re=be=>{T(be),F({name:be.name,description:be.description||"",base_price:Number(be.base_price),shipping_fee:Number(be.shipping_fee),category_id:be.category_id||"",allow_artwork_upload:be.allow_artwork_upload,requires_proof_approval:be.requires_proof_approval,is_active:be.is_active,sort_order:be.sort_order}),y(!0)},le=async be=>{be.preventDefault();const Ue={...$,category_id:$.category_id||null};S?await a.mutateAsync({id:S.id,...Ue}):await n.mutateAsync(Ue),y(!1),Z()},oe=async be=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(be)},ne=async be=>{if(!A||!be.target.files||be.target.files.length===0)return;R(!0);const Ue=be.target.files[0],Be=Ue.name.split(".").pop(),De=`products/${A.id}/${Date.now()}.${Be}`;try{const{error:Ae}=await V.storage.from("marketplace").upload(De,Ue);if(Ae)throw Ae;const{data:{publicUrl:He}}=V.storage.from("marketplace").getPublicUrl(De);await l.mutateAsync({product_id:A.id,image_url:He,is_primary:!A.images||A.images.length===0}),ue.success("Image uploaded successfully")}catch(Ae){ue.error("Failed to upload image: "+Ae.message)}finally{R(!1)}},ie=async be=>{be.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:z.name,price_adjustment:z.price_adjustment}),Q({name:"",price_adjustment:0}))},ye=async()=>{!A||!K||(await m.mutateAsync({productId:A.id,videoUrl:K}),X(""))};return t?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Fs,{className:"h-8 w-48"})}),e.jsx(Pe,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(be=>e.jsx(Fs,{className:"h-64 w-full"},be))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"Products"}),e.jsxs(fs,{open:x,onOpenChange:be=>{y(be),be||Z()},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:S?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:le,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(he,{htmlFor:"name",children:"Product Name"}),e.jsx(Ne,{id:"name",value:$.name,onChange:be=>F({...$,name:be.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"category",children:"Category"}),e.jsxs(Is,{value:$.category_id,onValueChange:be=>F({...$,category_id:be}),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select category"})}),e.jsx(Ms,{children:r==null?void 0:r.map(be=>e.jsx(ct,{value:be.id,children:be.name},be.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"description",children:"Description"}),e.jsx(or,{id:"description",value:$.description,onChange:be=>F({...$,description:be.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(he,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(Ne,{id:"base_price",type:"number",step:"0.01",min:"0",value:$.base_price,onChange:be=>F({...$,base_price:parseFloat(be.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(Ne,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:$.shipping_fee,onChange:be=>F({...$,shipping_fee:parseFloat(be.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(Ne,{id:"sort_order",type:"number",value:$.sort_order,onChange:be=>F({...$,sort_order:parseInt(be.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"allow_artwork_upload",checked:$.allow_artwork_upload,onCheckedChange:be=>F({...$,allow_artwork_upload:be})}),e.jsx(he,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"requires_proof_approval",checked:$.requires_proof_approval,onCheckedChange:be=>F({...$,requires_proof_approval:be})}),e.jsx(he,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"is_active",checked:$.is_active,onCheckedChange:be=>F({...$,is_active:be})}),e.jsx(he,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(G,{type:"submit",className:"w-full",disabled:n.isPending||a.isPending,children:S?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Pe,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(be=>{var Ue,Be;return e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[be.images&&be.images.length>0?e.jsx("img",{src:((Ue=be.images.find(De=>De.is_primary))==null?void 0:Ue.image_url)||be.images[0].image_url,alt:be.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"}),!be.is_active&&e.jsx(Ge,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:be.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Be=be.category)==null?void 0:Be.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(be.base_price).toFixed(2)]}),Number(be.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(be.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[be.allow_artwork_upload&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),be.requires_proof_approval&&e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Proof Required"}),be.variants&&be.variants.length>0&&e.jsxs(Ge,{variant:"outline",className:"text-xs",children:[be.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>re(be),children:[e.jsx(Ea,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{I(be),w(!0)},children:[e.jsx(rv,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{I(be),N(!0)},children:[e.jsx(wh,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>oe(be.id),children:e.jsx(yr,{className:"h-3 w-3 text-destructive"})})]})]})]},be.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(fs,{open:v,onOpenChange:w,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsxs(gs,{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:(ce=A==null?void 0:A.images)==null?void 0:ce.map(be=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:be.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),be.is_primary&&e.jsx(Ge,{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:[!be.is_primary&&e.jsx(G,{variant:"secondary",size:"icon",onClick:async()=>{var Ue;await c.mutateAsync({imageId:be.id,productId:A.id}),I({...A,images:(Ue=A.images)==null?void 0:Ue.map(Be=>({...Be,is_primary:Be.id===be.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Xn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"destructive",size:"icon",onClick:async()=>{var Be;await o.mutateAsync({id:be.id,productId:A.id});const Ue=s==null?void 0:s.find(De=>De.id===A.id);Ue&&I({...Ue,images:(Be=Ue.images)==null?void 0:Be.filter(De=>De.id!==be.id)})},disabled:o.isPending,children:e.jsx(yr,{className:"h-4 w-4"})})]})]},be.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ne,className:"hidden",id:"image-upload",disabled:D}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(rv,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(he,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(Ne,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:K,onChange:be=>X(be.target.value)}),e.jsxs(G,{onClick:ye,disabled:!K,children:[e.jsx(Jr,{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(fs,{open:b,onOpenChange:N,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Manage Variants - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ie,className:"flex gap-2",children:[e.jsx(Ne,{placeholder:"Variant name (e.g., 500 count)",value:z.name,onChange:be=>Q({...z,name:be.target.value}),required:!0}),e.jsx(Ne,{type:"number",step:"0.01",placeholder:"Price adj.",value:z.price_adjustment,onChange:be=>Q({...z,price_adjustment:parseFloat(be.target.value)||0}),className:"w-32"}),e.jsx(G,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ve=A==null?void 0:A.variants)==null?void 0:ve.map(be=>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:be.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(be.price_adjustment)>=0?"+":"","$",Number(be.price_adjustment).toFixed(2)]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>h.mutateAsync({id:be.id,productId:A.id}),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]},be.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 SPs=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function CPs(){var w,b,N;const{data:s,isLoading:t}=gPs(),r=bPs(),n=_Ps(),[a,i]=k.useState(null),[l,o]=k.useState(!1),[c,d]=k.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[h,m]=k.useState(!1),x=S=>{i(S),d({status:S.status,notes:"",trackingNumber:S.tracking_number||"",trackingUrl:S.tracking_url||""}),o(!0)},y=async()=>{a&&(await r.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},v=async(S,T)=>{if(!a||!S.target.files||S.target.files.length===0)return;m(!0);const A=S.target.files[0],I=A.name.split(".").pop(),D=`proofs/${a.id}/${T}/${Date.now()}.${I}`;try{const{error:R}=await V.storage.from("marketplace").upload(D,A);if(R)throw R;const{data:{publicUrl:$}}=V.storage.from("marketplace").getPublicUrl(D);await n.mutateAsync({itemId:T,proofUrl:$,orderId:a.id}),ue.success("Proof uploaded successfully")}catch(R){ue.error("Failed to upload proof: "+R.message)}finally{m(!1)}};return t?e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Fs,{className:"h-8 w-48"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(S=>e.jsx(Fs,{className:"h-16 w-full"},S))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Orders"})}),e.jsx(Pe,{children:s&&s.length>0?e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Order #"}),e.jsx(Nt,{children:"Customer"}),e.jsx(Nt,{children:"Date"}),e.jsx(Nt,{children:"Total"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:s.map(S=>{var T,A;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-mono",children:S.order_number}),e.jsx(dt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((T=S.user)==null?void 0:T.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=S.user)==null?void 0:A.email})]})}),e.jsx(dt,{children:_s(new Date(S.created_at),"MMM d, yyyy")}),e.jsxs(dt,{className:"font-bold",children:["$",Number(S.total).toFixed(2)]}),e.jsx(dt,{children:e.jsx(Ge,{className:$Ee[S.status],children:ZA[S.status]})}),e.jsx(dt,{className:"text-right",children:e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>x(S),children:[e.jsx(bn,{className:"h-4 w-4 mr-1"}),"View"]})})]},S.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(fs,{open:l,onOpenChange:o,children:e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs(gs,{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:(w=a.user)==null?void 0:w.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(b=a.user)==null?void 0:b.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:(N=a.items)==null?void 0:N.map(S=>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:S.product_name}),S.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(S.unit_price).toFixed(2)," x ",S.quantity]})]}),S.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:S.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(Ge,{variant:S.proof_status==="approved"?"default":"secondary",children:S.proof_status||"No proof yet"})]}),S.proof_url?e.jsx("a",{href:S.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:T=>v(T,S.id),className:"hidden",id:`proof-${S.id}`,disabled:h}),e.jsx("label",{htmlFor:`proof-${S.id}`,children:e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(da,{className:"h-4 w-4 mr-1"}),h?"Uploading...":"Upload Proof"]})})})]})]})})]},S.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(he,{children:"Status"}),e.jsxs(Is,{value:c.status,onValueChange:S=>d({...c,status:S}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:SPs.map(S=>e.jsx(ct,{value:S,children:ZA[S]},S))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Tracking Number"}),e.jsx(Ne,{value:c.trackingNumber,onChange:S=>d({...c,trackingNumber:S.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Tracking URL"}),e.jsx(Ne,{value:c.trackingUrl,onChange:S=>d({...c,trackingUrl:S.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Notes (optional)"}),e.jsx(or,{value:c.notes,onChange:S=>d({...c,notes:S.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(G,{onClick:y,disabled:r.isPending,className:"w-full",children:[e.jsx(Il,{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(S=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Ge,{variant:"outline",children:ZA[S.status]}),S.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:S.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:_s(new Date(S.created_at),"MMM d, h:mm a")})]},S.id))})]})]})]})})]})}function TPs(){const[s,t]=k.useState("products"),r=br();return e.jsx(ws,{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(G,{variant:"outline",onClick:()=>r("/marketplace"),children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(On,{value:s,onValueChange:t,children:[e.jsxs(Rn,{className:"grid w-full grid-cols-3",children:[e.jsxs(Kt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Il,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Kt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(Qh,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Kt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(Hf,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(ts,{value:"products",children:e.jsx(kPs,{})}),e.jsx(ts,{value:"categories",children:e.jsx(NPs,{})}),e.jsx(ts,{value:"orders",children:e.jsx(CPs,{})})]})]})})}function Fpt(){return mt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await V.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function EPs(s){return mt({queryKey:["reward-items",s],queryFn:async()=>{let t=V.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:r,error:n}=await t;if(n)throw n;return r}})}function APs(s){return mt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=V.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:r,error:n}=await t;if(n)throw n;return r}})}function MPs(s){return mt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function IPs(){return mt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await V.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 r=[...new Set(s.map(l=>l.user_id))],{data:n,error:a}=await V.from("profiles").select("id, name, email").in("id",r);if(a)throw a;const i=new Map((n==null?void 0:n.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function LPs(s){return mt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:r}=await V.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(r&&r.code!=="PGRST116")throw r;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function PPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.rpc("purchase_reward_item",{p_item_id:t});if(n)throw n;const a=r;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 DPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("reward_store_categories").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function RPs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("reward_store_categories").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function OPs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("reward_store_categories").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function FPs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("reward_store_items").insert([t]).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function BPs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("reward_store_items").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function zPs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("reward_store_items").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function $Ps(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function Ebe(s,t){const r=$Ps(s);if(r)try{const{data:n,error:a}=await V.storage.from(r.bucket).download(r.path);if(a){console.error("Error downloading file:",a),ue.error("Failed to download file");return}const i=URL.createObjectURL(n),l=document.createElement("a");l.href=i,l.download=t||r.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(n){console.error("Download error:",n),ue.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(n){console.error("External download error:",n),ue.error("Failed to download file")}}function Bpt(){return mt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await V.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function UPs(){const s=Xt();return Ct({mutationFn:async({id:t,points:r,is_active:n})=>{const a={points:r};n!==void 0&&(a.is_active=n);const{data:i,error:l}=await V.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 qPs(){const{user:s}=js(),[t,r]=k.useState("items"),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(null),[w,b]=k.useState(!1),[N,S]=k.useState(null),[T,A]=k.useState(""),[I,D]=k.useState(""),[R,$]=k.useState(null),[F,z]=k.useState(""),[Q,K]=k.useState("file"),[X,Z]=k.useState(""),[re,le]=k.useState(""),[oe,ne]=k.useState(""),[ie,ye]=k.useState(!0),[ce,ve]=k.useState(null),[be,Ue]=k.useState(!1),[Be,De]=k.useState(!1),Ae=k.useRef(null),He=k.useRef(null),{data:Le,isLoading:Ie}=Fpt(),{data:Te,isLoading:xe}=EPs(),{data:et,isLoading:fe}=IPs(),{data:it,isLoading:Oe}=Bpt(),Ye=DPs(),We=RPs(),_e=OPs(),Re=FPs(),tt=BPs(),Ke=zPs(),Ze=UPs(),[lt,xt]=k.useState({}),Xe=yt=>{yt?(l(yt),c(yt.name),h(yt.description||""),x(yt.icon||"")):(l(null),c(""),h(""),x("")),a(!0)},Je=async()=>{if(!o.trim()){ue.error("Please enter a category name");return}try{i?(await We.mutateAsync({id:i.id,name:o,description:d||null,icon:m||null}),ue.success("Category updated successfully")):(await Ye.mutateAsync({name:o,description:d||null,icon:m||null,sort_order:((Le==null?void 0:Le.length)||0)+1}),ue.success("Category created successfully")),a(!1)}catch(yt){console.error("Error saving category:",yt),ue.error("Failed to save category")}},jt=async()=>{if(y)try{await _e.mutateAsync(y),ue.success("Category deleted successfully"),v(null)}catch(yt){console.error("Error deleting category:",yt),ue.error("Failed to delete category")}},ns=yt=>{var is;yt?(S(yt),A(yt.name),D(yt.description||""),$(yt.category_id),z(yt.points_cost.toString()),K(yt.item_type),Z(yt.file_url||""),le(yt.preview_image_url||""),ne(((is=yt.max_quantity)==null?void 0:is.toString())||""),ye(yt.is_active)):(S(null),A(""),D(""),$(null),z(""),K("file"),Z(""),le(""),ne(""),ye(!0)),b(!0)},Ns=async(yt,is)=>{is==="file"?Ue(!0):De(!0);try{const Bs=yt.name.split(".").pop(),ps=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Bs}`,lr=`${is==="file"?"items":"previews"}/${ps}`,{error:kr}=await V.storage.from("reward-store").upload(lr,yt);if(kr)throw kr;const{data:{publicUrl:Lr}}=V.storage.from("reward-store").getPublicUrl(lr);is==="file"?Z(Lr):le(Lr),ue.success("File uploaded successfully")}catch(Bs){console.error("Error uploading file:",Bs),ue.error("Failed to upload file")}finally{is==="file"?Ue(!1):De(!1)}},Ys=async()=>{if(!T.trim()){ue.error("Please enter an item name");return}if(!F||parseInt(F)<0){ue.error("Please enter a valid points cost");return}try{const yt={name:T,description:I||null,category_id:R,points_cost:parseInt(F),item_type:Q,file_url:X||null,preview_image_url:re||null,max_quantity:oe?parseInt(oe):null,current_quantity:oe?parseInt(oe):null,is_active:ie,created_by:s==null?void 0:s.id};N?(await tt.mutateAsync({id:N.id,...yt,current_quantity:N.max_quantity!==(oe?parseInt(oe):null)?oe?parseInt(oe):null:N.current_quantity}),ue.success("Item updated successfully")):(await Re.mutateAsync(yt),ue.success("Item created successfully")),b(!1)}catch(yt){console.error("Error saving item:",yt),ue.error("Failed to save item")}},rs=async()=>{if(ce)try{await Ke.mutateAsync(ce),ue.success("Item deleted successfully"),ve(null)}catch(yt){console.error("Error deleting item:",yt),ue.error("Failed to delete item")}},bt=async(yt,is)=>{const Bs=lt[yt];if(Bs===void 0||Bs===is.toString())return;const ps=parseInt(Bs);if(isNaN(ps)||ps<0){ue.error("Please enter a valid positive number");return}try{await Ze.mutateAsync({id:yt,points:ps}),ue.success("Points updated successfully"),xt(lr=>{const kr={...lr};return delete kr[yt],kr})}catch(lr){console.error("Error updating points:",lr),ue.error("Failed to update points")}};return Ie||xe||fe||Oe?e.jsx(ws,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{className:"h-8 w-64"}),e.jsx(Fs,{className:"h-96"})]})}):e.jsxs(ws,{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(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Il,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Items"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Te==null?void 0:Te.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Te==null?void 0:Te.filter(yt=>yt.is_active).length)||0," active"]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Qh,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Le==null?void 0:Le.length)||0})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Xn,{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:[Te&&Te.length>0?Math.round(Te.reduce((yt,is)=>yt+is.points_cost,0)/Te.length):0," pts"]})]})})]}),e.jsxs(On,{value:t,onValueChange:r,children:[e.jsxs(Rn,{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(ts,{value:"items",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Store Items"}),e.jsx(Nr,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(G,{onClick:()=>ns(),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Pe,{children:!Te||Te.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ii,{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(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Item"}),e.jsx(Nt,{children:"Category"}),e.jsx(Nt,{className:"text-center",children:"Cost"}),e.jsx(Nt,{className:"text-center",children:"Type"}),e.jsx(Nt,{className:"text-center",children:"Quantity"}),e.jsx(Nt,{className:"text-center",children:"Status"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:Te.map(yt=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[yt.preview_image_url?e.jsx("img",{src:yt.preview_image_url,alt:yt.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(ii,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:yt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:yt.description||"No description"})]})]})}),e.jsx(dt,{children:yt.category?e.jsx(Ge,{variant:"outline",children:yt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(dt,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),yt.points_cost]})}),e.jsx(dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[yt.item_type==="file"?e.jsx(ln,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(po,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:yt.item_type})]})}),e.jsx(dt,{className:"text-center",children:yt.max_quantity!==null?e.jsxs("span",{className:yt.current_quantity===0?"text-red-500":"",children:[yt.current_quantity,"/",yt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(dt,{className:"text-center",children:e.jsx(Ge,{variant:yt.is_active?"default":"secondary",children:yt.is_active?"Active":"Inactive"})}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ns(yt),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>ve(yt.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},yt.id))})]})})]})}),e.jsx(ts,{value:"categories",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Categories"}),e.jsx(Nr,{children:"Organize your store items into categories"})]}),e.jsxs(G,{onClick:()=>Xe(),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Pe,{children:!Le||Le.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Qh,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Name"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{className:"text-center",children:"Items"}),e.jsx(Nt,{className:"text-right",children:"Actions"})]})}),e.jsx($n,{children:Le.map(yt=>e.jsxs(Ds,{children:[e.jsxs(dt,{className:"font-medium",children:[yt.icon&&e.jsx("span",{className:"mr-2",children:yt.icon}),yt.name]}),e.jsx(dt,{className:"text-muted-foreground",children:yt.description||"—"}),e.jsx(dt,{className:"text-center",children:(Te==null?void 0:Te.filter(is=>is.category_id===yt.id).length)||0}),e.jsx(dt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Xe(yt),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>v(yt.id),children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})})]})})]},yt.id))})]})})]})}),e.jsx(ts,{value:"purchases",className:"mt-4",children:e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Hf,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Nr,{children:"View all reward redemptions by agents"})]}),e.jsx(Pe,{children:!et||et.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Hf,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Date"}),e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{children:"Item"}),e.jsx(Nt,{className:"text-center",children:"Points Spent"})]})}),e.jsx($n,{children:et.map(yt=>{var is,Bs,ps,lr;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"text-muted-foreground",children:_s(new Date(yt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(dt,{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(Di,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((is=yt.user)==null?void 0:is.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Bs=yt.user)==null?void 0:Bs.email)||"—"})]})]})}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(ps=yt.item)!=null&&ps.preview_image_url?e.jsx("img",{src:yt.item.preview_image_url,alt:yt.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(ii,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((lr=yt.item)==null?void 0:lr.name)||"Deleted item"})]})}),e.jsx(dt,{className:"text-center",children:e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),yt.points_spent]})})]},yt.id)})})]})})]})})]})]}),e.jsx(fs,{open:n,onOpenChange:a,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:i?"Edit Category":"Add Category"}),e.jsx(Hr,{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(he,{htmlFor:"categoryName",children:"Name"}),e.jsx(Ne,{id:"categoryName",value:o,onChange:yt=>c(yt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(or,{id:"categoryDescription",value:d,onChange:yt=>h(yt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(Ne,{id:"categoryIcon",value:m,onChange:yt=>x(yt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{onClick:Je,disabled:Ye.isPending||We.isPending,children:Ye.isPending||We.isPending?"Saving...":"Save"})]})]})}),e.jsx(fs,{open:w,onOpenChange:b,children:e.jsxs(ms,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:N?"Edit Item":"Add Item"}),e.jsx(Hr,{children:N?"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(he,{htmlFor:"itemName",children:"Name *"}),e.jsx(Ne,{id:"itemName",value:T,onChange:yt=>A(yt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemDescription",children:"Description"}),e.jsx(or,{id:"itemDescription",value:I,onChange:yt=>D(yt.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(he,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(Is,{value:R||"none",onValueChange:yt=>$(yt==="none"?null:yt),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select category"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No category"}),Le==null?void 0:Le.map(yt=>e.jsxs(ct,{value:yt.id,children:[yt.icon&&`${yt.icon} `,yt.name]},yt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(Ne,{id:"itemPointsCost",type:"number",min:"0",value:F,onChange:yt=>z(yt.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(he,{htmlFor:"itemType",children:"Type"}),e.jsxs(Is,{value:Q,onValueChange:K,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"file",children:"File Download"}),e.jsx(ct,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(Ne,{id:"itemMaxQuantity",type:"number",min:"1",value:oe,onChange:yt=>ne(yt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:X,onChange:yt=>Z(yt.target.value),placeholder:Q==="file"?"Upload a file or paste URL":"Paste external link"}),Q==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>{var yt;return(yt=Ae.current)==null?void 0:yt.click()},disabled:be,children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ae,type:"file",className:"hidden",onChange:yt=>{var Bs;const is=(Bs=yt.target.files)==null?void 0:Bs[0];is&&Ns(is,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:re,onChange:yt=>le(yt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(G,{type:"button",variant:"outline",size:"icon",onClick:()=>{var yt;return(yt=He.current)==null?void 0:yt.click()},disabled:Be,children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("input",{ref:He,type:"file",accept:"image/*",className:"hidden",onChange:yt=>{var Bs;const is=(Bs=yt.target.files)==null?void 0:Bs[0];is&&Ns(is,"preview")}})]}),re&&e.jsx("img",{src:re,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{id:"itemIsActive",checked:ie,onCheckedChange:ye}),e.jsx(he,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx(G,{onClick:Ys,disabled:Re.isPending||tt.isPending,children:Re.isPending||tt.isPending?"Saving...":"Save"})]})]})}),e.jsx(Ko,{open:!!y,onOpenChange:()=>v(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Category"}),e.jsx(Bo,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:jt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Ko,{open:!!ce,onOpenChange:()=>ve(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Item"}),e.jsx(Bo,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:rs,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(ke,{className:"mt-4",children:[e.jsx(Mt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oo,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Dt,{children:"Point Reward Settings"}),e.jsx(Nr,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Pe,{children:!it||it.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(oo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Action"}),e.jsx(Nt,{children:"Description"}),e.jsx(Nt,{className:"text-center w-32",children:"Points"}),e.jsx(Nt,{className:"text-right w-24",children:"Save"})]})}),e.jsx($n,{children:it.map(yt=>e.jsxs(Ds,{children:[e.jsx(dt,{children:e.jsx("p",{className:"font-medium",children:yt.action_name})}),e.jsx(dt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:yt.description})}),e.jsx(dt,{className:"text-center",children:e.jsx(Ne,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:lt[yt.id]??yt.points.toString(),onChange:is=>xt(Bs=>({...Bs,[yt.id]:is.target.value}))})}),e.jsx(dt,{className:"text-right",children:e.jsx(G,{size:"sm",variant:"outline",disabled:lt[yt.id]===void 0||lt[yt.id]===yt.points.toString()||Ze.isPending,onClick:()=>bt(yt.id,yt.points),children:e.jsx(Bl,{className:"h-4 w-4"})})})]},yt.id))})]})})]})]})}const eVe=()=>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"})]}),tVe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function VPs(){const s=Xt(),[t,r]=k.useState(!1),[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:h}=mt({queryKey:["canva-integration"],queryFn:async()=>{const{data:S,error:T}=await V.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(T)throw T;return S}}),{data:m}=mt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:S,error:T}=await V.from("brokerages").select("id, name").order("name");if(T)throw T;return S}}),{data:x}=mt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:S,error:T}=await V.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(T)throw T;return S}}),y=async()=>{var S;r(!0);try{const{data:T}=await V.auth.getSession(),A=(S=T==null?void 0:T.session)==null?void 0:S.access_token;if(!A)throw new Error("Not authenticated");const R=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"})}),$=await R.json();if(!R.ok||$!=null&&$.error)throw new Error(($==null?void 0:$.error)||"Failed to get authorization URL");if($!=null&&$.authUrl){localStorage.setItem("canva_code_verifier",$.codeVerifier),localStorage.setItem("canva_oauth_state",$.state);const F=window.open($.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!F){ue.error("Popup was blocked. Please allow popups for this site and try again."),r(!1);return}const z=K=>{var X,Z;K.origin===window.location.origin&&(((X=K.data)==null?void 0:X.type)==="canva-oauth-success"?(window.removeEventListener("message",z),ue.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1)):((Z=K.data)==null?void 0:Z.type)==="canva-oauth-error"&&(window.removeEventListener("message",z),ue.error("Canva connection failed: "+(K.data.error||"Unknown error")),r(!1)))};window.addEventListener("message",z);const Q=setInterval(()=>{F.closed&&(clearInterval(Q),window.removeEventListener("message",z),s.invalidateQueries({queryKey:["canva-integration"]}),r(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(T){console.error("Canva connect error:",T);const A=(T==null?void 0:T.message)||"";A.includes("CANVA_CLIENT_ID")?ue.error("Canva app credentials not configured yet."):ue.error(A||"Failed to start Canva connection"),r(!1)}},v=Ct({mutationFn:async S=>{var F;const{data:T}=await V.auth.getSession(),A=(F=T==null?void 0:T.session)==null?void 0:F.access_token;if(!A)throw new Error("Not authenticated");const R=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:S})}),$=await R.json();if(!R.ok||$!=null&&$.error)throw new Error(($==null?void 0:$.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ue.success("Canva disconnected")},onError:S=>{ue.error(S.message||"Failed to disconnect Canva")}}),w=Ct({mutationFn:async S=>{const{error:T}=await V.from("canva_brokerage_folders").insert({brokerage_id:S.brokerage_id,folder_id:S.folder_id.trim(),folder_name:S.folder_name.trim(),folder_type:S.folder_type,description:S.description.trim()||null,sort_order:(x==null?void 0:x.length)||0});if(T)throw T},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ue.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ue.error("Failed to add folder")}),b=Ct({mutationFn:async S=>{const{error:T}=await V.from("canva_brokerage_folders").delete().eq("id",S);if(T)throw T},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ue.success("Folder removed")},onError:()=>ue.error("Failed to remove folder")}),N=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{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(eVe,{})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",N&&e.jsx(Ge,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Nr,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Pe,{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(di,{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(di,{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(di,{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"})]}),N?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(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Canva?"}),e.jsx(Bo,{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(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>v.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(!n),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(Qh,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",x&&x.length>0&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:x.length})]}),n?e.jsx(Jf,{className:"h-4 w-4"}):e.jsx(Wi,{className:"h-4 w-4"})]}),n&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[x&&x.length>0?x.map(S=>{var T,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:S.folder_name}),e.jsx(Ge,{variant:"outline",className:"text-xs shrink-0",children:((T=tVe.find(I=>I.value===S.folder_type))==null?void 0:T.label)||S.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=S.brokerages)==null?void 0:A.name," · ID: ",e.jsx("span",{className:"font-mono",children:S.folder_id})]})]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>b.mutate(S.id),children:e.jsx(vr,{className:"h-3.5 w-3.5"})})]},S.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(G,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx($s,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(G,{className:"mt-4",onClick:y,disabled:t||h,children:[t?e.jsx(Mi,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(eVe,{})}),"Connect Canva",e.jsx(Ha,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{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(he,{children:"Brokerage"}),e.jsxs(Is,{value:o.brokerage_id,onValueChange:S=>c(T=>({...T,brokerage_id:S})),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a brokerage…"})}),e.jsx(Ms,{children:m==null?void 0:m.map(S=>e.jsx(ct,{value:S.id,children:S.name},S.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Canva Folder ID"}),e.jsx(Ne,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:S=>c(T=>({...T,folder_id:S.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(he,{children:"Folder Display Name"}),e.jsx(Ne,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:S=>c(T=>({...T,folder_name:S.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{children:"Folder Type"}),e.jsxs(Is,{value:o.folder_type,onValueChange:S=>c(T=>({...T,folder_type:S})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:tVe.map(S=>e.jsx(ct,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(Ne,{placeholder:"What's in this folder?",value:o.description,onChange:S=>c(T=>({...T,description:S.target.value}))})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>w.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||w.isPending,children:[w.isPending?e.jsx(Mi,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function HPs(){const s=br();return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(eh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(ke,{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(Ec,{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(G,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(Ha,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(VPs,{}),e.jsx(Lpt,{})]})})}const sVe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(yu,{className:t}):s==="instagram"?e.jsx(Jd,{className:t}):s==="linkedin"?e.jsx(Jh,{className:t}):s==="google"?e.jsx(Vs,{className:t}):null},GPs=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function WPs(){const[s,t]=k.useState([]),[r,n]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all");k.useEffect(()=>{(async()=>{n(!0);const{data:x,error:y}=await V.rpc("admin_get_social_connections");if(y){ue.error(y.message),n(!1);return}t(x||[]),n(!1)})()},[]);const c=k.useMemo(()=>{const x=a.trim().toLowerCase();return s.filter(y=>l!=="all"&&y.platform!==l?!1:x?(y.user_name||"").toLowerCase().includes(x)||(y.user_email||"").toLowerCase().includes(x)||(y.page_name||"").toLowerCase().includes(x)||(y.platform_username||"").toLowerCase().includes(x):!0)},[s,a,l]),d=k.useMemo(()=>{const x=new Map;return s.forEach(y=>{const v=x.get(y.user_id)||{name:y.user_name,email:y.user_email,platforms:new Set,count:0};v.platforms.add(y.platform),v.count+=1,x.set(y.user_id,v)}),Array.from(x.entries()).map(([y,v])=>({user_id:y,...v}))},[s]),h=k.useMemo(()=>{const x=new Map;return s.forEach(y=>x.set(y.platform,(x.get(y.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(x.entries())}},[s,d]),m=x=>x&&new Date(x).getTime()e.jsxs(ke,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[sVe(x)," ",x]}),e.jsx("div",{className:"text-2xl font-bold",children:y})]},x))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(Ne,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:x=>i(x.target.value),className:"md:max-w-md"}),e.jsxs(Is,{value:l,onValueChange:o,children:[e.jsx(As,{className:"md:w-48",children:e.jsx(Ls,{placeholder:"All platforms"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All platforms"}),e.jsx(ct,{value:"facebook",children:"Facebook"}),e.jsx(ct,{value:"instagram",children:"Instagram"}),e.jsx(ct,{value:"linkedin",children:"LinkedIn"}),e.jsx(ct,{value:"google",children:"Google"})]})]})]}),e.jsx(ke,{children:r?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(es,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"User"}),e.jsx(Nt,{children:"Platform"}),e.jsx(Nt,{children:"Page / Account"}),e.jsx(Nt,{children:"Status"}),e.jsx(Nt,{children:"Connected"})]})}),e.jsx($n,{children:c.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(x=>{const y=m(x.token_expires_at);return e.jsxs(Ds,{children:[e.jsxs(dt,{children:[e.jsx("div",{className:"font-medium",children:x.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.user_email})]}),e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[sVe(x.platform)," ",x.platform]})}),e.jsxs(dt,{children:[e.jsx("div",{className:"font-medium",children:x.page_name||x.platform_username||"—"}),x.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",x.instagram_business_id]})]}),e.jsx(dt,{children:x.is_active?y?e.jsxs(Ge,{variant:"destructive",className:"gap-1",children:[e.jsx(Oi,{className:"h-3 w-3"})," Expired"]}):e.jsx(Ge,{children:"Active"}):e.jsx(Ge,{variant:"secondary",children:"Inactive"})}),e.jsx(dt,{className:"text-sm text-muted-foreground",children:GPs(x.created_at)})]},x.id)})})]})})]})})}const KPs={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 yD(s,t=18,r=10){return s.length<=t+r+3?s:`${s.slice(0,t)}…${s.slice(-r)}`}function YPs(){var Q,K,X,Z,re;const s=Xt(),[t,r]=k.useState("Test Push"),[n,a]=k.useState("Testing web push notification"),[i,l]=k.useState("/community"),[o,c]=k.useState(!1),[d,h]=k.useState(!1),[m,x]=k.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[y,v]=k.useState(null),[w,b]=k.useState(null),{data:N,isLoading:S}=mt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:le,error:oe}=await V.from("push_notification_settings").select("*").order("setting_key");if(oe)throw oe;return le}}),{data:T,isLoading:A}=mt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:le,error:oe}=await V.from("push_subscriptions").select("*",{count:"exact",head:!0});if(oe)throw oe;return{totalSubscriptions:le||0}}}),I=Ct({mutationFn:async({settingKey:le,isEnabled:oe})=>{const{error:ne}=await V.from("push_notification_settings").update({is_enabled:oe}).eq("setting_key",le);if(ne)throw ne},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ue.success("Notification setting updated")},onError:le=>{ue.error("Failed to update setting: "+le.message)}}),D=k.useMemo(()=>{var le,oe;return m.isSupported?`perm=${m.permission??"unknown"} · controller=${m.controllerPresent?"yes":"no"} · sw=${((le=m.serviceWorker)==null?void 0:le.activeState)??"unknown"} · sub=${(oe=m.subscription)!=null&&oe.endpoint?"yes":"no"}`:"Push not supported in this browser."},[m]);k.useEffect(()=>{let le=!0;const oe=async()=>{var ce,ve,be,Ue,Be,De,Ae;const ie="serviceWorker"in navigator&&"PushManager"in window,ye={isSupported:ie,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((ce=navigator.serviceWorker)!=null&&ce.controller)};if(!ie){le&&x(ye);return}try{const{data:He,error:Le}=await V.functions.invoke("get-vapid-public-key",{body:{}});if(Le)throw Le;ye.vapidPublicKey=He==null?void 0:He.vapidPublicKey;const Te=(await navigator.serviceWorker.getRegistrations()).find(xe=>{var fe,it,Oe;return(((fe=xe.active)==null?void 0:fe.scriptURL)||((it=xe.waiting)==null?void 0:it.scriptURL)||((Oe=xe.installing)==null?void 0:Oe.scriptURL)||"").includes("/sw.js")});if(Te){ye.pushWorkerScriptUrl=((ve=Te.active)==null?void 0:ve.scriptURL)||((be=Te.waiting)==null?void 0:be.scriptURL)||((Ue=Te.installing)==null?void 0:Ue.scriptURL),ye.serviceWorker={scope:Te.scope,activeState:(Be=Te.active)==null?void 0:Be.state};const xe=await Te.pushManager.getSubscription();if(xe){const et=xe.toJSON();ye.subscription={endpoint:et.endpoint,p256dh:(De=et.keys)==null?void 0:De.p256dh,auth:(Ae=et.keys)==null?void 0:Ae.auth}}}}catch(He){ye.error=(He==null?void 0:He.message)||String(He)}le&&x(ye)};oe();const ne=window.setInterval(oe,4e3);return()=>{le=!1,window.clearInterval(ne)}},[]);const R=async()=>{if(typeof Notification>"u"){ue.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ue.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ue.success("Triggered a local notification (not push).")}catch(le){ue.error(`Local notification failed: ${(le==null?void 0:le.message)||String(le)}`)}},$=async()=>{c(!0),v(null);try{const{data:le,error:oe}=await V.functions.invoke("send-push-notification",{body:{title:t,body:n,url:i}});if(oe)throw oe;v({sent:le==null?void 0:le.sent,failed:le==null?void 0:le.failed,expiredCleaned:le==null?void 0:le.expiredCleaned,vapidPublicKey:le==null?void 0:le.vapidPublicKey}),(le==null?void 0:le.sent)>0?ue.success(`Test notification sent to ${le.sent} subscriber(s)`):(le==null?void 0:le.failed)>0?ue.warning(`Notification failed for ${le.failed} subscriber(s). ${le.expired||0} expired subscriptions cleaned up.`):ue.info("No active subscriptions to send to")}catch(le){console.error("Error sending test notification:",le),v({error:(le==null?void 0:le.message)||String(le)}),ue.error("Failed to send test notification: "+(le.message||"Unknown error"))}finally{c(!1)}},F=async()=>{h(!0),b(null);try{const{data:le,error:oe}=await V.functions.invoke("generate-vapid-keys",{body:{}});if(oe)throw oe;const ne=le==null?void 0:le.publicKey,ie=le==null?void 0:le.privateKey;if(!ne||!ie)throw new Error("generate-vapid-keys did not return keys");b({publicKey:ne,privateKey:ie}),ue.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(le){console.error("Error generating VAPID keys:",le),ue.error("Failed to generate VAPID keys: "+((le==null?void 0:le.message)||"Unknown error"))}finally{h(!1)}},z=Ct({mutationFn:async()=>{const{error:le}=await V.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(le)throw le},onSuccess:()=>{ue.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:le=>{ue.error("Failed to clear subscriptions: "+le.message)}});return e.jsx(ws,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Nr,{children:"Current active push notification subscriptions"})]}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(T==null?void 0:T.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(oo,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Nr,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Pe,{children:S?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:N==null?void 0:N.map(le=>{const oe=KPs[le.setting_key]||{label:le.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:oe.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:oe.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:le.description})]})]}),e.jsx(_r,{checked:le.is_enabled,onCheckedChange:ne=>I.mutate({settingKey:le.setting_key,isEnabled:ne}),disabled:I.isPending})]},le.id)})})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(_m,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Nr,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Pe,{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:D}),m.error&&e.jsx("div",{className:"mt-2 text-destructive",children:m.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:m.vapidPublicKey?yD(m.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: ",(Q=m.serviceWorker)!=null&&Q.scope?yD(m.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((K=m.serviceWorker)==null?void 0:K.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: ",(X=m.subscription)!=null&&X.endpoint?yD(m.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(Z=m.subscription)!=null&&Z.p256dh?yD(m.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(re=m.subscription)!=null&&re.auth?yD(m.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(G,{variant:"outline",onClick:R,children:"Local notification test"}),e.jsx(G,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(Ne,{id:"test-title",value:t,onChange:le=>r(le.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(or,{id:"test-body",value:n,onChange:le=>a(le.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(Ne,{id:"test-url",value:i,onChange:le=>l(le.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(G,{onClick:$,disabled:o||!t||!n,className:"w-full sm:w-auto",children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),y&&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"}),y.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",y.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",y.sent??0," sent, ",y.failed??0," failed, ",y.expiredCleaned??0," expired cleaned"]}),y.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:y.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(yr,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Nr,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Pe,{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(G,{variant:"destructive",onClick:()=>z.mutate(),disabled:z.isPending,children:[e.jsx(yr,{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(G,{variant:"outline",onClick:F,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),w&&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:w.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:w.privateKey})]})]})]})]})]})]})})}function ZPs(){const{toast:s}=Ma(),[t,r]=k.useState([]),[n,a]=k.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=k.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:h}=bB("presentation_count","desc"),m=h(t,{name:v=>{var w;return((w=v.name)==null?void 0:w.toLowerCase())||""},presentations:v=>v.presentation_count,views:v=>v.total_views,leads:v=>v.total_leads,cta_clicks:v=>v.total_cta_clicks,conversion:v=>v.total_views>0?v.total_leads/v.total_views*100:0});k.useEffect(()=>{x()},[]);const x=async()=>{try{l(!0);const{data:v,error:w}=await V.rpc("get_admin_presentation_stats");if(w)throw w;if(!v||v.length===0){l(!1);return}const b=v.map(I=>I.owner_user_id),{data:N,error:S}=await V.from("profiles").select("id, name, email, avatar_url").in("id",b);if(S)throw S;const T=new Map((N==null?void 0:N.map(I=>[I.id,I]))||[]),A=v.map(I=>{const D=T.get(I.owner_user_id);return{owner_user_id:I.owner_user_id,name:(D==null?void 0:D.name)||"Unknown",email:(D==null?void 0:D.email)||"",avatar_url:(D==null?void 0:D.avatar_url)||null,presentation_count:Number(I.presentation_count),total_views:Number(I.total_views),total_leads:Number(I.total_leads),total_cta_clicks:Number(I.total_cta_clicks)}});r(A),r(A),a({totalPresentations:A.reduce((I,D)=>I+D.presentation_count,0),totalViews:A.reduce((I,D)=>I+D.total_views,0),totalLeads:A.reduce((I,D)=>I+D.total_leads,0),totalCtaClicks:A.reduce((I,D)=>I+D.total_cta_clicks,0),agentsUsing:A.length})}catch(v){console.error("Error loading presentation stats:",v),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},y=[{label:"Agents Using",value:n.agentsUsing,icon:pr,color:"text-blue-600"},{label:"Total Presentations",value:n.totalPresentations,icon:Ty,color:"text-violet-600"},{label:"Total Views",value:n.totalViews,icon:bn,color:"text-emerald-600"},{label:"Total Leads",value:n.totalLeads,icon:sl,color:"text-amber-600"},{label:"CTA Clicks",value:n.totalCtaClicks,icon:qc,color:"text-rose-600"}];return e.jsx(ws,{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:y.map(v=>e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:v.label}),e.jsx(v.icon,{className:`h-4 w-4 ${v.color}`})]}),e.jsx(Pe,{children:i?e.jsx(Fs,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:v.value.toLocaleString()})})]},v.label))}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(bo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Pe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((v,w)=>e.jsx(Fs,{className:"h-12 w-full"},w))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(El,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(El,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(El,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(El,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(El,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(El,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx($n,{children:m.map(v=>{var b,N;const w=v.total_views>0?(v.total_leads/v.total_views*100).toFixed(1):"0.0";return e.jsxs(Ds,{children:[e.jsx(dt,{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:v.avatar_url?e.jsx("img",{src:v.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((N=(b=v.name)==null?void 0:b.charAt(0))==null?void 0:N.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:v.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.email})]})]})}),e.jsx(dt,{className:"text-center font-medium",children:v.presentation_count}),e.jsx(dt,{className:"text-center",children:v.total_views.toLocaleString()}),e.jsx(dt,{className:"text-center",children:v.total_leads>0?e.jsx(Ge,{variant:"secondary",children:v.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(dt,{className:"text-center",children:v.total_cta_clicks}),e.jsx(dt,{className:"text-center",children:e.jsxs("span",{className:Number(w)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[w,"%"]})})]},v.owner_user_id)})})]})})]})]})})}function XPs(){const{toast:s}=Ma(),[t,r]=k.useState([]),[n,a]=k.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=k.useState(!0);k.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:h}=await V.rpc("get_admin_guest_book_stats");if(h)throw h;if(!d||d.length===0){l(!1);return}const m=d.map(b=>b.agent_id),{data:x,error:y}=await V.from("profiles").select("id, name, email, avatar_url").in("id",m);if(y)throw y;const v=new Map((x==null?void 0:x.map(b=>[b.id,b]))||[]),w=d.map(b=>{const N=v.get(b.agent_id);return{agent_id:b.agent_id,name:(N==null?void 0:N.name)||"Unknown",email:(N==null?void 0:N.email)||"",avatar_url:(N==null?void 0:N.avatar_url)||null,open_house_count:Number(b.open_house_count),total_visitors:Number(b.total_visitors),total_leads:Number(b.total_leads),active_count:Number(b.active_count)}});w.sort((b,N)=>N.total_visitors-b.total_visitors),r(w),a({totalOpenHouses:w.reduce((b,N)=>b+N.open_house_count,0),totalVisitors:w.reduce((b,N)=>b+N.total_visitors,0),totalLeads:w.reduce((b,N)=>b+N.total_leads,0),activeOpenHouses:w.reduce((b,N)=>b+N.active_count,0),agentsUsing:w.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:n.agentsUsing,icon:pr,color:"text-blue-600"},{label:"Total Open Houses",value:n.totalOpenHouses,icon:En,color:"text-violet-600"},{label:"Active Now",value:n.activeOpenHouses,icon:di,color:"text-emerald-600"},{label:"Total Visitors",value:n.totalVisitors,icon:bn,color:"text-amber-600"},{label:"Leads Created",value:n.totalLeads,icon:sl,color:"text-rose-600"}];return e.jsx(ws,{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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Dt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Pe,{children:i?e.jsx(Fs,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(bo,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Pe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,h)=>e.jsx(Fs,{className:"h-12 w-full"},h))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Agent"}),e.jsx(Nt,{className:"text-center",children:"Open Houses"}),e.jsx(Nt,{className:"text-center",children:"Active"}),e.jsx(Nt,{className:"text-center",children:"Visitors"}),e.jsx(Nt,{className:"text-center",children:"Leads"}),e.jsx(Nt,{className:"text-center",children:"Conversion"})]})}),e.jsx($n,{children:t.map(d=>{var m,x;const h=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(Ds,{children:[e.jsx(dt,{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:((x=(m=d.name)==null?void 0:m.charAt(0))==null?void 0:x.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(dt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(dt,{className:"text-center",children:d.active_count>0?e.jsx(Ge,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(dt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(dt,{className:"text-center",children:d.total_leads>0?e.jsx(Ge,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(dt,{className:"text-center",children:e.jsxs("span",{className:Number(h)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[h,"%"]})})]},d.agent_id)})})]})})]})]})})}function QPs(){const[s]=Ac(),t=br(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing connection...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Failed to connect: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("Failed to connect: No authorization code");return}try{const{data:m,error:x}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(x){let y=x.message||"Failed to connect accounts";try{const v=x.context;if(v&&typeof v.json=="function"){const w=await v.json();w!=null&&w.error&&(y=w.error)}}catch{}throw new Error(y)}if(m!=null&&m.success)n("success"),i(m.message||"Accounts connected successfully!"),ue.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),n("error"),i(m.message||"Failed to complete connection"),ue.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[r==="loading"&&e.jsx(es,{className:"h-12 w-12 animate-spin text-primary"}),r==="success"&&e.jsx(di,{className:"h-12 w-12 text-green-500"}),r==="error"&&e.jsx(Sc,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Dt,{children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:e.jsx(G,{onClick:()=>t("/admin/integrations"),children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function JPs(){const s=Xt(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState([]),o=k.useRef(null),{data:c,isLoading:d}=mt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:N}=await V.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(N)throw N;return b}}),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,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=Ct({mutationFn:async b=>{const{data:N,error:S}=await V.functions.invoke("send-prospect-email",{body:{emails:b}});if(S)throw S;return N},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ue.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),r(""),a(""),l([])},onError:b=>{ue.error("Failed to send: "+b.message)}}),x=Ct({mutationFn:async()=>{var T,A;const{data:{user:b}}=await V.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:N,error:S}=await V.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(A=(T=b.user_metadata)==null?void 0:T.name)==null?void 0:A.split(" ")[0]}],test_mode:!0}});if(S)throw S;return N},onSuccess:()=>{ue.success("Test email sent to your inbox!")},onError:b=>{ue.error("Failed to send test: "+b.message)}}),y=()=>{if(!t.trim()){ue.error("Please enter an email address");return}if(c==null?void 0:c.find(N=>N.email.toLowerCase()===t.trim().toLowerCase())){ue.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:n.trim()||void 0}])},v=b=>{var T;const N=(T=b.target.files)==null?void 0:T[0];if(!N)return;const S=new FileReader;S.onload=A=>{var F,z;const D=((F=A.target)==null?void 0:F.result).split(` `).filter(Q=>Q.trim()),R=[],$=(z=D[0])!=null&&z.toLowerCase().includes("email")?1:0;for(let Q=$;Qre.trim().replace(/"/g,"")),X=K[0],Z=K[1];X&&X.includes("@")&&R.push({email:X,first_name:Z||void 0})}l(R),ue.success(`${R.length} entries loaded from CSV`)},S.readAsText(N),o.current&&(o.current.value="")},w=()=>{if(i.length===0){ue.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(S=>S.email.toLowerCase()))||[]),N=i.filter(S=>!b.has(S.email.toLowerCase()));if(N.length===0){ue.error("All emails have already been prospected");return}N.lengthx.mutate(),disabled:x.isPending,className:"gap-2 ml-4 shrink-0",children:[x.isPending?e.jsx(es,{className:"h-3 w-3 animate-spin"}):e.jsx(Vs,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Pe,{children:e.jsxs(On,{defaultValue:"single",children:[e.jsxs(Rn,{className:"mb-4",children:[e.jsxs(Kt,{value:"single",children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Kt,{value:"bulk",children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(ts,{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(he,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(Ne,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>r(b.target.value),onKeyDown:b=>b.key==="Enter"&&y()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(he,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(Ne,{id:"prospect-name",placeholder:"First name (optional)",value:n,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&y()})]}),e.jsxs(G,{onClick:y,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(ts,{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(G,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(ln,{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(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(vr,{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,N)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},N)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(G,{onClick:w,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Nr,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Pe,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,N)=>e.jsx(Fs,{className:"h-12 w-full"},N))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(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:_s(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Ge,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"Converted"]}):e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?_s(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Pd,{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 WB(s){const t=Xt(),{toast:r}=Ma(),n=mt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await V.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=mt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],h=0,m=!0;for(;m;){const{data:x,error:y}=await V.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(h,h+c-1);if(y)throw y;d=d.concat(x),m=x.length===c,h+=c}return d},enabled:!!s}),i=Ct({mutationFn:async c=>{const{data:{user:d}}=await V.auth.getUser();if(!d)throw new Error("Not authenticated");const h={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:m,error:x}=await V.from("recruit_prospects").insert(h).select().single();if(x)throw x;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect added"})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),l=Ct({mutationFn:async({id:c,...d})=>{const{data:h,error:m}=await V.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>r({title:"Error",description:c.message,variant:"destructive"})}),o=Ct({mutationFn:async c=>{const{error:d}=await V.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),r({title:"Prospect removed"})}});return{stages:n.data||[],prospects:a.data||[],isLoading:n.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function e6s(s){const t=Xt(),{toast:r}=Ma(),n=mt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await V.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=Ct({mutationFn:async i=>{const{data:{user:l}}=await V.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await V.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),r({title:"Activity logged"})},onError:i=>r({title:"Error",description:i.message,variant:"destructive"})});return{activities:n.data||[],isLoading:n.isLoading,addActivity:a}}const rVe=(s,t)=>{var r;return{first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",license_number:"",experience_years:"",annual_production:"",source:"manual",notes:"",stage_id:s||((r=t==null?void 0:t[0])==null?void 0:r.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 zpt({open:s,onOpenChange:t,stages:r,defaultStageId:n,onSubmit:a,isSubmitting:i}){const[l,o]=k.useState(rVe(n,r)),c=h=>m=>o(x=>({...x,[h]:m.target.value})),d=h=>{h.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(rVe(n,r)),t(!1)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(On,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Rn,{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(ts,{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(he,{children:"First Name *"}),e.jsx(Ne,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Last Name"}),e.jsx(Ne,{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(he,{children:"Email"}),e.jsx(Ne,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(Ne,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Current Brokerage"}),e.jsx(Ne,{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(he,{children:"License #"}),e.jsx(Ne,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Experience (years)"}),e.jsx(Ne,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Address"}),e.jsx(Ne,{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(he,{children:"City"}),e.jsx(Ne,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"State"}),e.jsx(Ne,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Zip"}),e.jsx(Ne,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Pipeline Stage"}),e.jsxs(Is,{value:l.stage_id,onValueChange:h=>o(m=>({...m,stage_id:h})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:r.map(h=>e.jsx(ct,{value:h.id,children:h.name},h.id))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Referred By"}),e.jsx(Ne,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(ts,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Annual Production Volume"}),e.jsx(Ne,{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(he,{children:"Last Year Volume"}),e.jsx(Ne,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Last Year Transactions"}),e.jsx(Ne,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Avg Sale Price"}),e.jsx(Ne,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Specialties / Niche"}),e.jsx(Ne,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(ts,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"LinkedIn URL"}),e.jsx(Ne,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Website URL"}),e.jsx(Ne,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Instagram Handle"}),e.jsx(Ne,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Facebook URL"}),e.jsx(Ne,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(ts,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Birthday"}),e.jsx(Ne,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Spouse / Partner Name"}),e.jsx(Ne,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Interests / Hobbies"}),e.jsx(Ne,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Notes"}),e.jsx(or,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function t6s(){const{user:s}=js();return mt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,r]=await Promise.all([V.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),V.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:r.data?{email:r.data.gmail_email}:null}}})}function qEe({value:s,onChange:t}){const{data:r,isLoading:n}=t6s();return e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Send from"}),e.jsxs(Is,{value:s,onValueChange:a=>t(a),disabled:n,children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(ct,{value:"mass_email",disabled:!(r!=null&&r.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ej,{className:"h-3.5 w-3.5"}),"Mass Email",r!=null&&r.massEmail?` (${r.massEmail.email})`:" — not configured"]})}),e.jsx(ct,{value:"gmail",disabled:!(r!=null&&r.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Gmail",r!=null&&r.gmail?` (${r.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 $pt({open:s,onOpenChange:t,recruitVideoId:r,brokerageId:n,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState("default"),[w,b]=k.useState(!1),N=Xt();k.useEffect(()=>{s&&(h(`${c}, I made you a quick video 🎥`),x(o||""))},[s,c,o]);const S=async()=>{var T,A;if(!i){ue.error("This prospect has no email address on file.");return}b(!0);try{const{data:I,error:D}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[r],brokerage_id:n,subject_override:d.trim()||void 0,message_override:m.trim()||void 0,send_via:y}});if(D)throw D;if(((I==null?void 0:I.sent)??0)>0)ue.success(`Email sent to ${i}`),N.invalidateQueries({queryKey:["recruit-videos"]}),N.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const $=((A=(T=I==null?void 0:I.results)==null?void 0:T[0])==null?void 0:A.error)||"Failed to send";ue.error($)}}catch(I){ue.error((I==null?void 0:I.message)||"Failed to send email")}finally{b(!1)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsx(ys,{children:e.jsxs(gs,{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(he,{className:"text-xs",children:"To"}),e.jsx(Ne,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(qEe,{value:y,onChange:v}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subject"}),e.jsx(Ne,{value:d,onChange:T=>h(T.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(or,{value:m,onChange:T=>x(T.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(an,{children:[e.jsx(G,{variant:"ghost",onClick:()=>t(!1),disabled:w,children:"Cancel"}),e.jsxs(G,{onClick:S,disabled:w||!i,children:[w?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(en,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}const Dke=[{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 s6s(s){return mt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function r6s(s){return mt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function Upt(){const s=Xt(),{toast:t}=Ma();return Ct({mutationFn:async r=>{const{data:{user:n}}=await V.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("recruit_videos").insert({prospect_id:r.prospect_id,video_id:r.video_id,brokerage_id:r.brokerage_id,message:r.message||null,created_by:n.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)").single();if(i)throw i;return a},onSuccess:r=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",r.prospect_id]}),t({title:"Video linked to prospect"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function qpt(){const s=Xt();return Ct({mutationFn:async({id:t,sent_via:r})=>{const{error:n}=await V.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:r,updated_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function Vpt(s){return mt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(r)throw r;return t},enabled:!!s})}function n6s(){const s=Xt(),{toast:t}=Ma();return Ct({mutationFn:async r=>{const{data:{user:n}}=await V.auth.getUser();if(!n)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("recruit_video_scripts").insert({...r,created_by:n.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:r=>t({title:"Error",description:r.message,variant:"destructive"})})}function a6s(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("recruit_video_scripts").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function i6s({prospectId:s,prospectName:t,prospectEmail:r,brokerageId:n}){var re;const{data:a=[],isLoading:i}=r6s(s),{data:l=[]}=Vpt(n),o=Upt(),c=Yb();qpt();const[d,h]=k.useState("idle"),[m,x]=k.useState(0),[y,v]=k.useState(0),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(!1),[I,D]=k.useState(null),[R,$]=k.useState(null),[F,z]=k.useState(null),Q=((re=l.find(le=>le.id===w))==null?void 0:re.script_text)||"",K=()=>{h("idle"),x(0),v(0),b(""),S("")},X=k.useCallback(async(le,oe)=>{h("uploading");try{const ne=`Recruiting: ${t}`,{videoId:ie,libraryId:ye}=await h5(ne),{uploadUrl:ce,apiKey:ve}=await m5(ie),be=new XMLHttpRequest;be.upload.onprogress=Te=>{Te.lengthComputable&&x(Te.loaded/Te.total*100)},await new Promise((Te,xe)=>{be.onload=()=>be.status>=200&&be.status<300?Te():xe(new Error("Upload failed")),be.onerror=()=>xe(new Error("Upload failed")),be.open("PUT",ce),be.setRequestHeader("AccessKey",ve),be.send(le)}),h("processing");let Ue=0;const Be=Date.now(),De=9e4,Ae=`https://iframe.mediadelivery.net/embed/${ye}/${ie}`;for(;Ue<4&&(await new Promise(xe=>setTimeout(xe,3e3)),!(Date.now()-Be>De));){const Te=await Ev(ie);if(Ue=Te.status,v(Te.encodeProgress||0),Ue===5||Ue===6)throw new Error("Video processing failed")}const He=await Ev(ie),Le=(He.storageSize||le.size)/(1024*1024),Ie=await c.mutateAsync({bunny_video_id:ie,playback_url:He.directPlayUrl||Ae,thumbnail_url:He.thumbnailUrl,preview_url:He.previewUrl||null,duration_seconds:He.length||oe,file_size_mb:Le,title:ne,status:Ue>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Ie.id,brokerage_id:n,message:N||void 0}),h("done"),ue.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),K()},1500)}catch(ne){ue.error(ne.message||"Failed to upload video"),h("record")}},[s,t,n,N,c,o]),Z=le=>{le&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${le}`),ue.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(Jr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(fs,{open:T,onOpenChange:le=>{!le&&(d==="uploading"||d==="processing")||(A(le),le||K())},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>h("script"),children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsxs(gs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(Is,{value:w,onValueChange:b,children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{placeholder:"No script — speak freely"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"none",children:"No script"}),l.map(le=>{var oe;return e.jsx(ct,{value:le.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[le.title,e.jsx(Ge,{variant:"outline",className:"text-[9px] ml-1",children:(oe=Dke.find(ne=>ne.value===le.category))==null?void 0:oe.label})]})},le.id)})]})]}),Q&&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:Q})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(or,{value:N,onChange:le=>S(le.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(G,{onClick:()=>h("record"),className:"w-full",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(IL,{maxDurationSeconds:600,onRecordingComplete:X,teleprompterContent:Q||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(ei,{value:m,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(m),"%"]})]}),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(ei,{value:y,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(y),"%"]})]}),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(Uo,{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(le=>{var oe,ne;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md border text-sm",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:(oe=le.video)!=null&&oe.thumbnail_url?e.jsx("img",{src:le.video.thumbnail_url,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(Jr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs truncate",children:((ne=le.video)==null?void 0:ne.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[le.view_count>0?e.jsxs(Ge,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(bn,{className:"h-2.5 w-2.5 mr-0.5"}),le.view_count]}):le.sent_at?e.jsxs(Ge,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(en,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Ge,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(fn,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:_s(new Date(le.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Z(le.share_token),title:"Copy link",children:e.jsx(Ra,{className:"h-3 w-3"})}),e.jsxs(G,{variant:le.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!r,onClick:()=>{var ie;D(le.id),$(((ie=le.video)==null?void 0:ie.title)||null),z(le.message||null)},title:r?"Email video to prospect":"No email on file",children:[e.jsx(Vs,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:le.sent_at?"Resend":"Email"})]})]})]},le.id)})}),I&&e.jsx($pt,{open:!!I,onOpenChange:le=>{le||D(null)},recruitVideoId:I,brokerageId:n,prospectName:t,prospectEmail:r,videoTitle:R,defaultMessage:F})]})}function o6s({brokerageId:s,onSelect:t}){const{data:r=[],isLoading:n}=mt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=V.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=r.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(ln,{className:"h-4 w-4"}),"Use Template",e.jsx(Wi,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(xd,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:n?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(es,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):r.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(_v,{}),e.jsx(m8,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(Pa,{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(Ge,{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 l6s({open:s,onOpenChange:t,prospectId:r,brokerageId:n,prospectName:a,prospectEmail:i}){const{user:l}=js(),o=(a||"").split(" ")[0]||"there",[c,d]=k.useState(""),[h,m]=k.useState(""),[x,y]=k.useState("default"),[v,w]=k.useState(!1),[b,N]=k.useState(null),[S,T]=k.useState(!1),A=Xt();k.useEffect(()=>{s&&(d(`Hi ${o}`),m(""),y("default"),N(null),T(!1))},[s,o]);const{data:I=[],isLoading:D}=mt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:z,error:Q}=await V.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Q)throw Q;return z??[]},enabled:s&&!!(l!=null&&l.id)}),R=I.find(z=>z.id===b)||null,$=async()=>{var z,Q;if(!i){ue.error("This prospect has no email address on file.");return}if(!c.trim()||!h.trim()){ue.error("Subject and message are required.");return}w(!0);try{if(b){const{data:K}=await V.from("recruit_videos").select("id").eq("prospect_id",r).eq("video_id",b).maybeSingle();let X=K==null?void 0:K.id;if(!X){const{data:oe,error:ne}=await V.from("recruit_videos").insert({prospect_id:r,video_id:b,brokerage_id:n,message:h.trim(),created_by:l.id}).select("id").single();if(ne)throw ne;X=oe.id}const{data:Z,error:re}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[X],brokerage_id:n,subject_override:c.trim(),message_override:h.trim(),send_via:x}});if(re)throw re;if(((Z==null?void 0:Z.sent)??0)>0)ue.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-videos"]}),A.invalidateQueries({queryKey:["recruit-videos-prospect",r]}),A.invalidateQueries({queryKey:["recruit-activities",r]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const oe=((Q=(z=Z==null?void 0:Z.results)==null?void 0:z[0])==null?void 0:Q.error)||"Failed to send";ue.error(oe)}}else{const{data:K,error:X}=await V.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:r,brokerage_id:n,subject:c.trim(),message:h.trim(),send_via:x}});if(X)throw X;K!=null&&K.success?(ue.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-activities",r]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ue.error((K==null?void 0:K.error)||"Failed to send")}}catch(K){ue.error((K==null?void 0:K.message)||"Failed to send email")}finally{w(!1)}},F=z=>{const Q=K=>K.replace(/\[First Name\]/gi,o);d(Q(z.subject)),m(Q(z.body)),ue.success(`Loaded "${z.title}"`)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs(gs,{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(he,{className:"text-xs",children:"To"}),e.jsx(Ne,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(qEe,{value:x,onChange:y}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(he,{className:"text-xs",children:"Subject"}),e.jsx(o6s,{brokerageId:n,onSelect:F})]}),e.jsx(Ne,{value:c,onChange:z=>d(z.target.value)}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Message"}),e.jsx(or,{value:h,onChange:z=>m(z.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(he,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"})," Include a video"]}),R?e.jsxs(G,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{N(null),T(!1)},children:[e.jsx(vr,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>T(z=>!z),children:S?"Hide library":"Pick from library"})]}),R&&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:R.thumbnail_url?e.jsx("img",{src:R.thumbnail_url,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(Jr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:R.title||"Untitled video"})]}),!R&&S&&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(es,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):I.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."}):I.map(z=>e.jsxs("button",{type:"button",onClick:()=>{N(z.id),T(!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:z.thumbnail_url?e.jsx("img",{src:z.thumbnail_url,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(Jr,{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:z.title||"Untitled video"}),z.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(z.duration_seconds/60),":",String(Math.floor(z.duration_seconds%60)).padStart(2,"0")]})]})]},z.id))}),R&&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(an,{children:[e.jsx(G,{variant:"ghost",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs(G,{onClick:$,disabled:v||!i,children:[v?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(en,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function c6s(s){return mt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.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(r)throw r;return t},enabled:!!s})}const nVe=[{value:"call",label:"Phone Call",icon:Cn},{value:"email",label:"Email",icon:Vs},{value:"text",label:"Text Message",icon:xi},{value:"meeting",label:"Meeting",icon:on},{value:"note",label:"Note",icon:ln},{value:"campaign_email",label:"Campaign Email",icon:en}];function wp({label:s,value:t,icon:r}){return t?e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[r&&e.jsx(r,{className:"h-3 w-3"})," ",s]}),e.jsx("p",{className:"font-medium text-sm",children:t})]}):null}function W$({label:s,url:t,icon:r}){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(r,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(Qr,{className:"h-3 w-3 opacity-50"})]}):null}function _c({label:s,value:t,onChange:r,type:n="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:s}),e.jsx(Ne,{type:n,value:t,onChange:i=>r(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Hpt({prospect:s,stages:t,brokerageId:r,open:n,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=e6s((s==null?void 0:s.id)||null),{data:d=[]}=c6s((s==null?void 0:s.id)||null),[h,m]=k.useState({type:"note",title:"",description:""}),[x,y]=k.useState(!1),[v,w]=k.useState(!1),[b,N]=k.useState({}),[S,T]=k.useState(!1);if(!s)return null;const A=()=>{var Z,re;N({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:((Z=s.experience_years)==null?void 0:Z.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:((re=s.last_year_transactions)==null?void 0:re.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||""}),w(!0)},I=()=>{const Z={id:s.id};for(const[re,le]of Object.entries(b))re==="experience_years"||re==="last_year_transactions"?Z[re]=le?parseInt(le):null:Z[re]=le||null;i(Z),w(!1)},D=()=>w(!1),R=Z=>re=>N(le=>({...le,[Z]:re})),$=()=>{h.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:h.type,title:h.title,description:h.description||null}),m({type:"note",title:"",description:""}),y(!1))},F=t.find(Z=>Z.id===s.stage_id),z=s.address||s.city||s.state,Q=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,K=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,X=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(Jj,{open:n,onOpenChange:Z=>{Z||w(!1),a(Z)},children:[e.jsx(Vb,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Qa,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(e2,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(t2,{className:"text-xl",children:[s.first_name," ",s.last_name]}),F&&e.jsx(Ge,{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:[v?e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:D,children:e.jsx(vr,{className:"h-4 w-4"})}),e.jsx(G,{variant:"default",size:"icon",onClick:I,children:e.jsx(Bl,{className:"h-4 w-4"})})]}):e.jsx(G,{variant:"ghost",size:"icon",onClick:A,title:"Edit prospect",children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete prospect?"}),e.jsx(Bo,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!v&&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(G,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>T(!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(Cn,{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(Ca,{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(he,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(Is,{value:s.stage_id||"",onValueChange:Z=>i({id:s.id,stage_id:Z}),children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:t.map(Z=>e.jsx(ct,{value:Z.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:Z.color}}),Z.name]})},Z.id))})]})]}),e.jsxs(On,{defaultValue:"details",className:"w-full",children:[e.jsxs(Rn,{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"})]}),v?e.jsxs(e.Fragment,{children:[e.jsxs(ts,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_c,{label:"First Name",value:b.first_name,onChange:R("first_name")}),e.jsx(_c,{label:"Last Name",value:b.last_name,onChange:R("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_c,{label:"Email",value:b.email,onChange:R("email"),type:"email"}),e.jsx(_c,{label:"Phone",value:b.phone,onChange:R("phone")})]}),e.jsx(_c,{label:"Current Brokerage",value:b.current_brokerage,onChange:R("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_c,{label:"License #",value:b.license_number,onChange:R("license_number")}),e.jsx(_c,{label:"Experience (years)",value:b.experience_years,onChange:R("experience_years"),type:"number"})]}),e.jsx(_c,{label:"Address",value:b.address,onChange:R("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(_c,{label:"City",value:b.city,onChange:R("city")}),e.jsx(_c,{label:"State",value:b.state,onChange:R("state")}),e.jsx(_c,{label:"Zip",value:b.zip_code,onChange:R("zip_code")})]}),e.jsx(_c,{label:"Source",value:b.source,onChange:R("source")}),e.jsx(_c,{label:"Referred By",value:b.referred_by,onChange:R("referred_by")}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Notes"}),e.jsx(or,{value:b.notes,onChange:Z=>N(re=>({...re,notes:Z.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(ts,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(_c,{label:"Annual Production",value:b.annual_production,onChange:R("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_c,{label:"Last Year Volume",value:b.last_year_volume,onChange:R("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(_c,{label:"Last Year Transactions",value:b.last_year_transactions,onChange:R("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(_c,{label:"Avg Sale Price",value:b.avg_sale_price,onChange:R("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(_c,{label:"Specialties / Niche",value:b.specialties,onChange:R("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(ts,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(_c,{label:"LinkedIn URL",value:b.linkedin_url,onChange:R("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(_c,{label:"Website URL",value:b.website_url,onChange:R("website_url"),type:"url",placeholder:"https://..."}),e.jsx(_c,{label:"Instagram Handle",value:b.instagram_handle,onChange:R("instagram_handle"),placeholder:"@handle"}),e.jsx(_c,{label:"Facebook URL",value:b.facebook_url,onChange:R("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(ts,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(_c,{label:"Birthday",value:b.birthday,onChange:R("birthday"),type:"date"}),e.jsx(_c,{label:"Spouse / Partner",value:b.spouse_name,onChange:R("spouse_name")}),e.jsx(_c,{label:"Interests / Hobbies",value:b.interests,onChange:R("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ts,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(wp,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(wp,{label:"License #",value:s.license_number}),e.jsx(wp,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(wp,{label:"Referred By",value:s.referred_by}),e.jsx(wp,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(ts,{value:"production",className:"mt-3",children:Q?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(wp,{label:"Annual Production",value:s.annual_production}),e.jsx(wp,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(wp,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(wp,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(wp,{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(ts,{value:"social",className:"mt-3",children:K?e.jsxs("div",{className:"space-y-2",children:[e.jsx(W$,{label:"LinkedIn",url:s.linkedin_url,icon:Jh}),e.jsx(W$,{label:"Website",url:s.website_url,icon:fc}),s.instagram_handle&&e.jsx(W$,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Jd}),e.jsx(W$,{label:"Facebook",url:s.facebook_url,icon:yu})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(ts,{value:"personal",className:"mt-3",children:X?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(wp,{label:"Birthday",value:s.birthday?_s(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:ii}),e.jsx(wp,{label:"Spouse / Partner",value:s.spouse_name,icon:ci}),e.jsx("div",{className:"col-span-2",children:e.jsx(wp,{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(i6s,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:r}),e.jsx(fo,{}),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(G,{size:"sm",variant:"outline",onClick:()=>y(!x),children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),x&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(Is,{value:h.type,onValueChange:Z=>m(re=>({...re,type:Z})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:nVe.map(Z=>e.jsx(ct,{value:Z.value,children:Z.label},Z.value))})]}),e.jsx(Ne,{placeholder:"Subject / Title",value:h.title,onChange:Z=>m(re=>({...re,title:Z.target.value}))}),e.jsx(or,{placeholder:"Details (optional)",value:h.description,onChange:Z=>m(re=>({...re,description:Z.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>y(!1),children:"Cancel"}),e.jsx(G,{size:"sm",onClick:$,disabled:!h.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const Z=[...o.map(re=>({type:"manual",data:re,date:re.created_at})),...d.map(re=>({type:"campaign_email",data:re,date:re.sent_at||re.created_at}))].sort((re,le)=>new Date(le.date).getTime()-new Date(re.date).getTime());return Z.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):Z.map(re=>{if(re.type==="manual"){const oe=re.data,ne=nVe.find(ye=>ye.value===oe.activity_type),ie=(ne==null?void 0:ne.icon)||ln;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(ie,{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:oe.title}),oe.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:oe.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:_s(new Date(oe.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${oe.id}`)}const le=re.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(en,{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 #",le.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:le.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[le.status==="failed"?e.jsx(Ge,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(en,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),le.opened_at?e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(bn,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",_s(new Date(le.opened_at),"MMM d, h:mm a")]}):le.status!=="failed"?e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,le.clicked_at&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(Bu,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",_s(new Date(le.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:_s(new Date(le.sent_at||le.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${le.id}`)})})()})]})]})})}),e.jsx(l6s,{open:S,onOpenChange:T,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const d6s=["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 Gpt({open:s,onOpenChange:t,brokerageId:r,stages:n}){var z;const{toast:a}=Ma(),i=Xt(),l=k.useRef(null),[o,c]=k.useState([]),[d,h]=k.useState([]),[m,x]=k.useState({}),[y,v]=k.useState(((z=n[0])==null?void 0:z.id)||""),[w,b]=k.useState(!1),[N,S]=k.useState("upload"),[T,A]=k.useState(0),I=()=>{c([]),h([]),x({}),S("upload"),A(0)},D=Q=>{var Z;const K=(Z=Q.target.files)==null?void 0:Z[0];if(!K)return;const X=new FileReader;X.onload=re=>{var ve;const oe=((ve=re.target)==null?void 0:ve.result).split(/\r?\n/).filter(be=>be.trim());if(oe.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ne=R(oe[0]);h(ne);const ie={},ye=new Set;ne.forEach((be,Ue)=>{const Be=be.toLowerCase().replace(/[^a-z0-9]/g,"");let De=null;/^firstname$/.test(Be)||Be==="first"?De="first_name":/^lastname$/.test(Be)||Be==="last"?De="last_name":/^email$/.test(Be)||Be==="emailaddress"?De="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Be)?De="phone":/officename|currentbrokerage|brokerage|company/.test(Be)?De="current_brokerage":/membernumber|licensenumber|license/.test(Be)?De="license_number":/experienceyears|yearsexperience/.test(Be)?De="experience_years":/^totalvolume$|annualproduction/.test(Be)?De="annual_production":/^address$/.test(Be)?De="address":/^city$/.test(Be)?De="city":/^state$/.test(Be)?De="state":/^postalcode$|^zip$|^zipcode$/.test(Be)?De="zip_code":/listsidevolume|lastyearvolume/.test(Be)?De="last_year_volume":/^totalcount$|lastyeartransactions/.test(Be)?De="last_year_transactions":/avgsaleprice|averageprice/.test(Be)?De="avg_sale_price":/linkedin/.test(Be)?De="linkedin_url":/website/.test(Be)?De="website_url":/specialt/.test(Be)?De="specialties":/referr/.test(Be)?De="referred_by":/^notes$|^note$/.test(Be)&&(De="notes"),De&&!ye.has(De)&&(ie[String(Ue)]=De,ye.add(De))}),x(ie);const ce=oe.slice(1).map(be=>{const Ue=R(be),Be={};return ne.forEach((De,Ae)=>{Be[String(Ae)]=Ue[Ae]||""}),Be});c(ce),S("map")},X.readAsText(K)},R=Q=>{const K=[];let X="",Z=!1;for(const re of Q)re==='"'?Z=!Z:re===","&&!Z?(K.push(X.trim()),X=""):X+=re;return K.push(X.trim()),K},$=async()=>{b(!0);try{const{data:{user:Q}}=await V.auth.getUser();if(!Q)throw new Error("Not authenticated");const K=o.map(Z=>{const re={brokerage_id:r,created_by:Q.id,stage_id:y,source:"csv_import",first_name:"Unknown"},le=re;return Object.entries(m).forEach(([oe,ne])=>{var ye;const ie=(ye=Z[oe])==null?void 0:ye.trim();ie&&(ne==="experience_years"||ne==="last_year_transactions"?le[ne]=parseInt(ie.replace(/[^0-9.-]/g,""))||null:ne==="annual_production"||ne==="last_year_volume"||ne==="avg_sale_price"?le[ne]=ie.replace(/[^0-9.$,.-]/g,""):le[ne]=ie)}),re});let X=0;for(let Z=0;Z{const Q=`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`,K=new Blob([Q],{type:"text/csv"}),X=URL.createObjectURL(K),Z=document.createElement("a");Z.href=X,Z.download="recruit-prospects-template.csv",Z.click(),URL.revokeObjectURL(X)};return e.jsx(fs,{open:s,onOpenChange:Q=>{Q||I(),t(Q)},children:e.jsxs(ms,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Import Prospects from CSV"})}),N==="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(mb,{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:D}),e.jsxs(G,{onClick:()=>{var Q;return(Q=l.current)==null?void 0:Q.click()},children:[e.jsx(da,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(G,{variant:"link",className:"text-xs",onClick:F,children:"Download CSV template"})]}),N==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(Is,{value:y,onValueChange:v,children:[e.jsx(As,{className:"w-[180px]",children:e.jsx(Ls,{})}),e.jsx(Ms,{children:n.map(Q=>e.jsx(ct,{value:Q.id,children:Q.name},Q.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Nt,{className:"w-[160px]",children:"Map To"}),e.jsx(Nt,{children:"Preview"})]})}),e.jsx($n,{children:d.map((Q,K)=>{var X;return e.jsxs(Ds,{children:[e.jsx(dt,{className:"font-medium text-xs",children:Q}),e.jsx(dt,{children:e.jsxs(Is,{value:m[String(K)]||"skip",onValueChange:Z=>x(re=>({...re,[String(K)]:Z==="skip"?"":Z})),children:[e.jsx(As,{className:"h-8 text-xs",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"skip",children:"— Skip —"}),d6s.map(Z=>e.jsx(ct,{value:Z,children:Z.replace(/_/g," ")},Z))]})]})}),e.jsx(dt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((X=o[0])==null?void 0:X[String(K)])||"—"})]},K)})})]})}),!Object.values(m).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Oi,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{variant:"outline",onClick:()=>{I()},children:"Back"}),e.jsx(G,{onClick:$,disabled:w||!Object.values(m).includes("first_name"),children:w?"Importing...":`Import ${o.length} Prospects`})]})]}),N==="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(Kn,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[T," prospects imported successfully!"]}),e.jsx(G,{onClick:()=>{I(),t(!1)},children:"Close"})]})]})})}function Wpt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=WB(s),[o,c]=k.useState(!1),[d,h]=k.useState(),[m,x]=k.useState(null),[y,v]=k.useState(!1),[w,b]=k.useState(!1),[N,S]=k.useState(null);if(n)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 T=F=>r.filter(z=>z.stage_id===F),A=(F,z)=>{S(z),F.dataTransfer.effectAllowed="move"},I=F=>{F.preventDefault(),F.dataTransfer.dropEffect="move"},D=(F,z)=>{F.preventDefault(),N&&(i.mutate({id:N,stage_id:z}),S(null))},R=F=>{h(F),c(!0)},$=F=>{x(F),v(!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:[r.length," prospect",r.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(da,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(G,{onClick:()=>{h(void 0),c(!0)},children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(Qa,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(F=>{const z=T(F.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:I,onDrop:Q=>D(Q,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(Ge,{variant:"secondary",className:"text-xs h-5 px-1.5",children:z.length})]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>R(F.id),children:e.jsx($s,{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(Q=>e.jsx(ke,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:F.color},draggable:!0,onDragStart:K=>A(K,Q.id),onClick:()=>$(Q),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(vu,{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(Di,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[Q.first_name," ",Q.last_name]})]}),Q.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Sa,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:Q.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Q.email&&e.jsx(Vs,{className:"h-3 w-3 text-muted-foreground"}),Q.phone&&e.jsx(Cn,{className:"h-3 w-3 text-muted-foreground"}),Q.experience_years!=null&&e.jsxs(Ge,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[Q.experience_years,"yr"]})]})]})]})},Q.id))})]},F.id)})}),e.jsx(wfe,{orientation:"horizontal"})]}),e.jsx(zpt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:F=>a.mutate(F),isSubmitting:a.isPending}),e.jsx(Hpt,{prospect:m,stages:t,brokerageId:s,open:y,onOpenChange:v,onUpdate:F=>{i.mutate(F),x(z=>z?{...z,...F}:null)},onDelete:F=>l.mutate(F)}),e.jsx(Gpt,{open:w,onOpenChange:b,brokerageId:s,stages:t})]})}function sme({brokerageId:s}){const{stages:t,prospects:r,isLoading:n,addProspect:a,updateProspect:i,deleteProspect:l}=WB(s),{user:o}=js(),c=Xt(),[d,h]=k.useState(!1),[m,x]=k.useState(null),[y,v]=k.useState(!1),[w,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState("all"),[I,D]=k.useState("all"),[R,$]=k.useState("all"),[F,z]=k.useState(null),[Q,K]=k.useState("asc"),[X,Z]=k.useState(new Set),[re,le]=k.useState(!1),[oe,ne]=k.useState(""),ie=k.useMemo(()=>{const xe=new Set;return r.forEach(et=>{et.current_brokerage&&xe.add(et.current_brokerage)}),Array.from(xe).sort()},[r]),{data:ye=[]}=mt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:xe,error:et}=await V.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(et)throw et;return xe}}),{data:ce=[]}=mt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let et=[],fe=0;for(;;){const{data:it,error:Oe}=await V.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(fe,fe+1e3-1);if(Oe)throw Oe;if(et=et.concat(it??[]),!it||it.length<1e3)break;fe+=1e3}return et}}),ve=k.useMemo(()=>{const xe=new Map;return ce.forEach(et=>{xe.has(et.prospect_id)||xe.set(et.prospect_id,new Set),xe.get(et.prospect_id).add(et.campaign_id)}),xe},[ce]),be=xe=>{F===xe?K(et=>et==="asc"?"desc":"asc"):(z(xe),K("asc"))},Ue=({column:xe})=>F!==xe?e.jsx(Ad,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):Q==="asc"?e.jsx(Id,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(Hu,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Be=xe=>t.find(et=>et.id===xe),De=k.useMemo(()=>{let xe=r.filter(et=>{var We,_e,Re;const fe=!N||`${et.first_name} ${et.last_name}`.toLowerCase().includes(N.toLowerCase())||((We=et.email)==null?void 0:We.toLowerCase().includes(N.toLowerCase()))||((_e=et.current_brokerage)==null?void 0:_e.toLowerCase().includes(N.toLowerCase())),it=T==="all"||et.stage_id===T,Oe=I==="all"||et.current_brokerage===I;let Ye=!0;return R==="in_campaign"?Ye=ve.has(et.id):R==="not_in_campaign"?Ye=!ve.has(et.id):R!=="all"&&(Ye=((Re=ve.get(et.id))==null?void 0:Re.has(R))??!1),fe&&it&&Oe&&Ye});return F&&(xe=[...xe].sort((et,fe)=>{var We,_e;let it=null,Oe=null;switch(F){case"name":it=`${et.first_name} ${et.last_name||""}`.toLowerCase(),Oe=`${fe.first_name} ${fe.last_name||""}`.toLowerCase();break;case"stage":it=((We=Be(et.stage_id))==null?void 0:We.sort_order)??999,Oe=((_e=Be(fe.stage_id))==null?void 0:_e.sort_order)??999;break;case"brokerage":it=(et.current_brokerage||"").toLowerCase(),Oe=(fe.current_brokerage||"").toLowerCase();break;case"experience":it=et.experience_years??-1,Oe=fe.experience_years??-1;break;case"production":it=(et.annual_production||"").toLowerCase(),Oe=(fe.annual_production||"").toLowerCase();break;case"source":it=(et.source||"").toLowerCase(),Oe=(fe.source||"").toLowerCase();break;default:return 0}if(it===Oe)return 0;if(it==null)return 1;if(Oe==null)return-1;const Ye=it0&&De.every(xe=>X.has(xe.id)),He=De.some(xe=>X.has(xe.id)),Le=()=>{Z(Ae?new Set:new Set(De.map(xe=>xe.id)))},Ie=xe=>{Z(et=>{const fe=new Set(et);return fe.has(xe)?fe.delete(xe):fe.add(xe),fe})},Te=Ct({mutationFn:async()=>{if(!oe||!(o!=null&&o.id))throw new Error("Select a campaign");const xe=new Set(ce.filter(it=>it.campaign_id===oe).map(it=>it.prospect_id)),et=Array.from(X).filter(it=>!xe.has(it)).map(it=>({prospect_id:it,campaign_id:oe,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(et.length===0)throw new Error("All selected prospects are already in this campaign");const{error:fe}=await V.from("recruit_campaign_assignments").insert(et);if(fe)throw fe;return et.length},onSuccess:xe=>{ue.success(`${xe} prospect(s) added to campaign`),le(!1),Z(new Set),ne(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:xe=>ue.error(xe.message)});return 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"})}):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(yn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search prospects...",value:N,onChange:xe=>S(xe.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[X.size>0&&e.jsxs(G,{variant:"secondary",onClick:()=>le(!0),className:"gap-1.5",children:[e.jsx(en,{className:"h-4 w-4"})," Add ",X.size," to Campaign"]}),e.jsxs(G,{variant:"outline",onClick:()=>b(!0),children:[e.jsx(da,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(G,{onClick:()=>h(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Sy,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(Is,{value:T,onValueChange:A,children:[e.jsx(As,{className:"w-[160px] h-8 text-xs",children:e.jsx(Ls,{placeholder:"All stages"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All stages"}),t.map(xe=>e.jsx(ct,{value:xe.id,children:xe.name},xe.id))]})]}),e.jsxs(Is,{value:I,onValueChange:D,children:[e.jsxs(As,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Sa,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Ls,{placeholder:"All brokerages"})]}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All brokerages"}),ie.map(xe=>e.jsx(ct,{value:xe,children:xe},xe))]})]}),e.jsxs(Is,{value:R,onValueChange:$,children:[e.jsxs(As,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Vs,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(Ls,{placeholder:"Campaign status"})]}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All contacts"}),e.jsx(ct,{value:"in_campaign",children:"In any campaign"}),e.jsx(ct,{value:"not_in_campaign",children:"Not in any campaign"}),ye.map(xe=>e.jsxs(ct,{value:xe.id,children:["In: ",xe.name]},xe.id))]})]}),(T!=="all"||I!=="all"||R!=="all")&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),D("all"),$("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{className:"w-[40px]",children:e.jsx(Si,{checked:Ae,onCheckedChange:Le,"aria-label":"Select all",...He&&!Ae?{"data-state":"indeterminate"}:{}})}),e.jsx(Nt,{className:"cursor-pointer select-none",onClick:()=>be("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(Ue,{column:"name"})]})}),e.jsx(Nt,{className:"cursor-pointer select-none",onClick:()=>be("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(Ue,{column:"stage"})]})}),e.jsx(Nt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>be("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(Ue,{column:"brokerage"})]})}),e.jsx(Nt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Nt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>be("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(Ue,{column:"experience"})]})}),e.jsx(Nt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>be("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(Ue,{column:"production"})]})}),e.jsx(Nt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Nt,{className:"w-[50px]"})]})}),e.jsx($n,{children:De.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):De.map(xe=>{const et=Be(xe.stage_id),fe=ve.get(xe.id),it=(fe==null?void 0:fe.size)??0;return e.jsxs(Ds,{className:"cursor-pointer",onClick:()=>{x(xe),v(!0)},children:[e.jsx(dt,{onClick:Oe=>Oe.stopPropagation(),children:e.jsx(Si,{checked:X.has(xe.id),onCheckedChange:()=>Ie(xe.id),"aria-label":`Select ${xe.first_name}`})}),e.jsxs(dt,{className:"font-medium",children:[xe.first_name," ",xe.last_name]}),e.jsx(dt,{children:et?e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:et.color,color:et.color,backgroundColor:`${et.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:et.color}}),et.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(dt,{className:"hidden md:table-cell",children:xe.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Sa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:xe.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(dt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[xe.email&&e.jsx(Vs,{className:"h-3.5 w-3.5 text-muted-foreground"}),xe.phone&&e.jsx(Cn,{className:"h-3.5 w-3.5 text-muted-foreground"}),!xe.email&&!xe.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(dt,{className:"hidden lg:table-cell",children:xe.experience_years!=null?`${xe.experience_years} yr`:"—"}),e.jsx(dt,{className:"hidden lg:table-cell",children:xe.annual_production||"—"}),e.jsx(dt,{className:"hidden lg:table-cell",children:it>0?e.jsxs(Ge,{variant:"secondary",className:"text-xs",children:[it," campaign",it>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(dt,{children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Oe=>{Oe.stopPropagation(),l.mutate(xe.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})})})]},xe.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[X.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[X.size," selected · "]}),De.length," of ",r.length," prospects"]}),e.jsx(fs,{open:re,onOpenChange:le,children:e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{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:X.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Campaign"}),e.jsxs(Is,{value:oe,onValueChange:ne,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a campaign..."})}),e.jsx(Ms,{children:ye.map(xe=>e.jsxs(ct,{value:xe.id,children:[xe.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",xe.warmth_level,")"]})]},xe.id))})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>Te.mutate(),disabled:!oe||Te.isPending,children:Te.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(zpt,{open:d,onOpenChange:h,stages:t,onSubmit:xe=>a.mutate(xe),isSubmitting:a.isPending}),e.jsx(Hpt,{prospect:m,stages:t,brokerageId:s,open:y,onOpenChange:v,onUpdate:xe=>{i.mutate(xe),x(et=>et?{...et,...xe}:null)},onDelete:xe=>l.mutate(xe)}),e.jsx(Gpt,{open:w,onOpenChange:b,brokerageId:s,stages:t})]})}function Kpt({brokerageId:s}){const{stages:t,prospects:r,isLoading:n}=WB(s),a=k.useMemo(()=>{if(!t.length||!r.length)return null;const i=r.length,l=t.find(N=>N.name==="Signed"),o=t.find(N=>N.name==="Onboarded"),c=r.filter(N=>N.stage_id===(l==null?void 0:l.id)||N.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",h=new Date,m=i>0?Math.round(r.reduce((N,S)=>N+pg(h,new Date(S.created_at)),0)/i):0,x=t.map(N=>({...N,count:r.filter(S=>S.stage_id===N.id).length})),y={};r.forEach(N=>{const S=N.source||"unknown";y[S]=(y[S]||0)+1});const v=Object.entries(y).sort((N,S)=>S[1]-N[1]),w=new Date;w.setDate(w.getDate()-30);const b=r.filter(N=>new Date(N.created_at)>=w).length;return{total:i,signed:c,conversionRate:d,avgDays:m,byStage:x,bySrc:v,recentCount:b}},[t,r]);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"})}):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(ke,{children:e.jsx(Pe,{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(pr,{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(ke,{children:e.jsx(Pe,{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(bo,{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(ke,{children:e.jsx(Pe,{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(fn,{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(ke,{children:e.jsx(Pe,{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(Pd,{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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Pe,{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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Pe,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ge,{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 u6s=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function Ypt({brokerageId:s}){const{toast:t}=Ma(),{user:r}=js(),n=Xt(),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(null),{data:x=[],isLoading:y}=mt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:A,error:I}=await V.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(I)throw I;return A}}),v=Ct({mutationFn:async A=>{if(A.id){const{error:I}=await V.from("recruit_email_templates").update({category:A.category,title:A.title,subject:A.subject,body:A.body}).eq("id",A.id);if(I)throw I}else{const{error:I}=await V.from("recruit_email_templates").insert({brokerage_id:s,category:A.category||"Outreach",title:A.title,subject:A.subject,body:A.body,created_by:r==null?void 0:r.id,sort_order:100});if(I)throw I}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),n.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),m(null)},onError:A=>t({title:"Save failed",description:A.message,variant:"destructive"})}),w=Ct({mutationFn:async A=>{const{error:I}=await V.from("recruit_email_templates").delete().eq("id",A);if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),n.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:A=>t({title:"Delete failed",description:A.message,variant:"destructive"})}),b=(A,I)=>{navigator.clipboard.writeText(A),i(I),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},N=()=>{m({category:"Outreach",title:"",subject:"",body:""}),d(!0)},S=A=>{m(A),d(!0)},T=Array.from(new Set(x.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(G,{onClick:N,size:"sm",className:"gap-1.5",children:[e.jsx($s,{className:"h-4 w-4"})," New Template"]})]}),y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(es,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):T.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]}),x.filter(I=>I.category===A).map(I=>{const D=I.brokerage_id!==null;return e.jsxs(ke,{className:`transition-all ${l===I.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Mt,{className:"pb-2 cursor-pointer",onClick:()=>o(l===I.id?null:I.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Dt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:I.title}),!D&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),D&&e.jsx(Ge,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",I.subject]})]}),e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:I.category})]})}),l===I.id&&e.jsxs(Pe,{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:I.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:I.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>b(I.subject,I.id+"-s"),children:[a===I.id+"-s"?e.jsx(Kn,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>b(I.body,I.id+"-b"),children:[a===I.id+"-b"?e.jsx(Kn,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>S(I),children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(G,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&w.mutate(I.id)},children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},I.id)})]},A)),e.jsx(fs,{open:c,onOpenChange:d,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsx(ys,{children:e.jsx(gs,{children:h!=null&&h.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(he,{className:"text-xs",children:"Title"}),e.jsx(Ne,{value:(h==null?void 0:h.title)||"",onChange:A=>m(I=>({...I,title:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(h==null?void 0:h.category)||"Outreach",onChange:A=>m(I=>({...I,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:u6s.map(A=>e.jsx("option",{value:A,children:A},A))})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subject"}),e.jsx(Ne,{value:(h==null?void 0:h.subject)||"",onChange:A=>m(I=>({...I,subject:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Body"}),e.jsx(or,{value:(h==null?void 0:h.body)||"",onChange:A=>m(I=>({...I,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(an,{children:[e.jsx(G,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>v.mutate(h||{}),disabled:v.isPending||!(h!=null&&h.title)||!(h!=null&&h.subject)||!(h!=null&&h.body),children:[v.isPending&&e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const aVe={call:Cn,email:Vs,text:xi,meeting:on,note:ln};function Zpt({brokerageId:s}){const{data:t,isLoading:r}=mt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:n,error:a}=await V.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(n==null?void 0:n.map(y=>y.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await V.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...n.map(y=>y.created_by),...(l||[]).map(y=>y.created_by)])],{data:d}=await V.from("profiles").select("id, name, email").in("id",c),h=Object.fromEntries((d||[]).map(y=>[y.id,y])),m=ace(new Date,30);return{recruiters:c.map(y=>{var S,T;const v=(l||[]).filter(A=>A.created_by===y),w=v.filter(A=>new Date(A.created_at)>=m),b={};w.forEach(A=>{b[A.activity_type]=(b[A.activity_type]||0)+1});const N=n.filter(A=>A.created_by===y).length;return{id:y,name:((S=h[y])==null?void 0:S.name)||"Unknown",email:((T=h[y])==null?void 0:T.email)||"",totalActivities:v.length,recentActivities:w.length,byType:b,prospectsCreated:N}}).sort((y,v)=>v.recentActivities-y.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});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"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Pe,{className:"space-y-4",children:t.recruiters.map((n,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(Di,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:n.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(n.byType).map(([i,l])=>{const o=aVe[i]||ln;return e.jsxs(Ge,{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:n.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:n.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},n.id))})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Recent Activity"})}),e.jsx(Pe,{className:"space-y-3",children:t.recentActivities.map(n=>{const a=aVe[n.activity_type]||ln;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:n.title}),n.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:_s(new Date(n.created_at),"MMM d, h:mm a")})]})]},n.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function Xpt({brokerageId:s}){const{toast:t}=Ma(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=mt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:b,error:N}=await V.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(N)throw N;return b}}),d=[...new Set(o.map(b=>b.referred_by))],{data:h=[]}=mt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:b}=await V.from("profiles").select("id, name, email").in("id",d);return b||[]},enabled:d.length>0}),m=Object.fromEntries(h.map(b=>[b.id,b])),x=Ct({mutationFn:async b=>{const{data:{user:N}}=await V.auth.getUser();if(!N)throw new Error("Not authenticated");const{error:S}=await V.from("recruit_referrals").insert({brokerage_id:s,referred_by:N.id,referee_first_name:b.first_name,referee_last_name:b.last_name||null,referee_email:b.email||null,referee_phone:b.phone||null,referee_current_brokerage:b.current_brokerage||null,notes:b.notes||null});if(S)throw S},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),y=Ct({mutationFn:async({id:b,status:N,incentive_status:S})=>{const T={updated_at:new Date().toISOString()};N&&(T.status=N),S&&(T.incentive_status=S);const{error:A}=await V.from("recruit_referrals").update(T).eq("id",b);if(A)throw A},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-referrals",s]})}),v=b=>b==="approved"||b==="signed"?e.jsx(Kn,{className:"h-3 w-3"}):b==="rejected"?e.jsx(Sc,{className:"h-3 w-3"}):e.jsx(fn,{className:"h-3 w-3"}),w=b=>b==="approved"||b==="signed"||b==="paid"?"bg-green-500/10 text-green-600 border-green-200":b==="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(G,{onClick:()=>a(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(ke,{className:"py-12 text-center",children:[e.jsx(sl,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(b=>{var N;return e.jsx(ke,{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:[b.referee_first_name," ",b.referee_last_name]}),e.jsxs(Ge,{variant:"outline",className:w(b.status),children:[v(b.status)," ",b.status]}),b.incentive_status&&e.jsxs(Ge,{variant:"outline",className:w(b.incentive_status),children:[e.jsx(ii,{className:"h-3 w-3 mr-1"})," ",b.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[b.referee_email&&e.jsx("p",{children:b.referee_email}),b.referee_phone&&e.jsx("p",{children:b.referee_phone}),b.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",b.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((N=m[b.referred_by])==null?void 0:N.name)||"Unknown"," • ",_s(new Date(b.created_at),"MMM d, yyyy")]})]}),b.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:b.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(Is,{value:b.status,onValueChange:S=>y.mutate({id:b.id,status:S}),children:[e.jsx(As,{className:"h-7 text-xs w-[110px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"pending",children:"Pending"}),e.jsx(ct,{value:"contacted",children:"Contacted"}),e.jsx(ct,{value:"approved",children:"Approved"}),e.jsx(ct,{value:"signed",children:"Signed"}),e.jsx(ct,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(Is,{value:b.incentive_status||"pending",onValueChange:S=>y.mutate({id:b.id,incentive_status:S}),children:[e.jsx(As,{className:"h-7 text-xs w-[100px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"pending",children:"Unpaid"}),e.jsx(ct,{value:"paid",children:"Paid"}),e.jsx(ct,{value:"n/a",children:"N/A"})]})]})]})]})},b.id)})}),e.jsx(fs,{open:n,onOpenChange:a,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),x.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"First Name *"}),e.jsx(Ne,{required:!0,value:i.first_name,onChange:b=>l(N=>({...N,first_name:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Last Name"}),e.jsx(Ne,{value:i.last_name,onChange:b=>l(N=>({...N,last_name:b.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(Ne,{type:"email",value:i.email,onChange:b=>l(N=>({...N,email:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(Ne,{value:i.phone,onChange:b=>l(N=>({...N,phone:b.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Current Brokerage"}),e.jsx(Ne,{value:i.current_brokerage,onChange:b=>l(N=>({...N,current_brokerage:b.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Notes"}),e.jsx(or,{value:i.notes,onChange:b=>l(N=>({...N,notes:b.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:x.isPending,children:"Submit"})]})]})]})})]})}function Qpt({brokerageId:s}){const{toast:t}=Ma(),r=Xt(),[n,a]=k.useState(!1),{data:i}=mt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:x,error:y}=await V.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(y)throw y;return x}}),{data:l=[]}=mt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:x,error:y}=await V.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(y)throw y;return x}}),o=Ct({mutationFn:async x=>{const{error:y}=await V.from("brokerages").update({recruit_form_enabled:x}).eq("id",s);if(y)throw y},onSuccess:()=>{r.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=Ct({mutationFn:async({id:x,status:y})=>{const{error:v}=await V.from("recruit_interest_submissions").update({status:y}).eq("id",x);if(v)throw v},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,h=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},m=x=>x==="contacted"||x==="converted"?"bg-green-500/10 text-green-600":x==="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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:x=>o.mutate(x)})]}),(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(G,{size:"sm",variant:"outline",onClick:h,children:n?e.jsx(Kn,{className:"h-3.5 w-3.5"}):e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Qr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Pe,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(x=>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:[x.first_name," ",x.last_name]}),e.jsx(Ge,{variant:"outline",className:m(x.status),children:x.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[x.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{className:"h-3 w-3"}),x.email]}),x.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),x.phone]}),x.current_brokerage&&e.jsxs("span",{children:["From: ",x.current_brokerage]}),x.experience_years&&e.jsxs("span",{children:[x.experience_years,"yr exp"]})]}),x.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',x.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:_s(new Date(x.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Is,{value:x.status,onValueChange:y=>c.mutate({id:x.id,status:y}),children:[e.jsx(As,{className:"h-7 text-xs w-[110px]",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"new",children:"New"}),e.jsx(ct,{value:"contacted",children:"Contacted"}),e.jsx(ct,{value:"converted",children:"Converted"}),e.jsx(ct,{value:"dismissed",children:"Dismissed"})]})]})]},x.id))})})]})]})}function Jpt({brokerageId:s}){const{toast:t}=Ma(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState({prospect_id:"",title:"",description:"",due_date:_s(Vl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=k.useState("pending"),{data:d=[]}=mt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:I,error:D}=await V.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(D)throw D;return I}}),{data:h=[],isLoading:m}=mt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const I=d.map($=>$.id);if(!I.length)return[];const{data:D,error:R}=await V.from("recruit_follow_ups").select("*").in("prospect_id",I).order("due_date");if(R)throw R;return D},enabled:d.length>0}),x=Object.fromEntries(d.map(I=>[I.id,I])),y=Ct({mutationFn:async I=>{const{data:{user:D}}=await V.auth.getUser();if(!D)throw new Error("Not authenticated");const{error:R}=await V.from("recruit_follow_ups").insert({prospect_id:I.prospect_id,assigned_to:D.id,title:I.title,description:I.description||null,due_date:new Date(I.due_date).toISOString()});if(R)throw R},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:_s(Vl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:I=>t({title:"Error",description:I.message,variant:"destructive"})}),v=Ct({mutationFn:async({id:I,completed:D})=>{const{error:R}=await V.from("recruit_follow_ups").update({completed_at:D?new Date().toISOString():null}).eq("id",I);if(R)throw R},onSuccess:()=>r.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),w=h.filter(I=>o==="pending"?!I.completed_at:o==="completed"?!!I.completed_at:!0),b=w.filter(I=>!I.completed_at&&hv(new Date(I.due_date))&&!zu(new Date(I.due_date))),N=w.filter(I=>!I.completed_at&&zu(new Date(I.due_date))),S=w.filter(I=>!I.completed_at&&!hv(new Date(I.due_date))&&!zu(new Date(I.due_date))),T=w.filter(I=>!!I.completed_at),A=I=>{const D=x[I.prospect_id],R=!I.completed_at&&hv(new Date(I.due_date))&&!zu(new Date(I.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Si,{checked:!!I.completed_at,onCheckedChange:$=>v.mutate({id:I.id,completed:$}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${I.completed_at?"line-through text-muted-foreground":""}`,children:I.title}),I.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:I.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[D&&e.jsxs(Ge,{variant:"secondary",className:"text-[10px]",children:[D.first_name," ",D.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${R?"text-destructive font-medium":""}`,children:[R?e.jsx(Oi,{className:"h-3 w-3"}):e.jsx(on,{className:"h-3 w-3"}),_s(new Date(I.due_date),"MMM d, h:mm a")]}),I.is_automated&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},I.id)};return m?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(I=>e.jsxs(G,{size:"sm",variant:o===I?"default":"outline",onClick:()=>c(I),className:"capitalize text-xs",children:[I," ",I==="pending"&&b.length+N.length+S.length>0&&`(${b.length+N.length+S.length})`]},I))}),e.jsxs(G,{size:"sm",onClick:()=>a(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&b.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(Oi,{className:"h-3.5 w-3.5"})," Overdue (",b.length,")"]}),b.map(A)]}),o!=="completed"&&N.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(fn,{className:"h-3.5 w-3.5"})," Today (",N.length,")"]}),N.map(A)]}),o!=="completed"&&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(on,{className:"h-3.5 w-3.5"})," Upcoming (",S.length,")"]}),S.map(A)]}),o!=="pending"&&T.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(Kn,{className:"h-3.5 w-3.5"})," Completed (",T.length,")"]}),T.map(A)]}),w.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(fs,{open:n,onOpenChange:a,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:I=>{I.preventDefault(),y.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{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:I=>l(D=>({...D,prospect_id:I.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(I=>e.jsxs("option",{value:I.id,children:[I.first_name," ",I.last_name]},I.id))]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Task *"}),e.jsx(Ne,{required:!0,value:i.title,onChange:I=>l(D=>({...D,title:I.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Details"}),e.jsx(or,{value:i.description,onChange:I=>l(D=>({...D,description:I.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Due Date *"}),e.jsx(Ne,{type:"datetime-local",required:!0,value:i.due_date,onChange:I=>l(D=>({...D,due_date:I.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:y.isPending,children:"Schedule"})]})]})]})})]})}const h6s=[{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 ext({brokerageId:s}){const{toast:t}=Ma(),r=Xt(),[n,a]=k.useState(null),{data:i,isLoading:l}=mt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:b,error:N}=await V.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(N)throw N;return b}}),[o,c]=k.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:h6s,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});k.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=Ct({mutationFn:async()=>{const b={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:N}=await V.from("recruit_landing_page_settings").update(b).eq("id",o.id);if(N)throw N}else{const{error:N}=await V.from("recruit_landing_page_settings").insert(b);if(N)throw N}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:b=>t({title:"Error",description:b.message,variant:"destructive"})}),h=async(b,N)=>{const S=b.name.split(".").pop(),T=`${s}/${N}-${Date.now()}.${S}`,{error:A}=await V.storage.from("recruit-landing").upload(T,b);if(A)throw A;const{data:{publicUrl:I}}=V.storage.from("recruit-landing").getPublicUrl(T);return I},m=async(b,N)=>{var T;const S=(T=b.target.files)==null?void 0:T[0];if(S){a(N);try{const A=await h(S,N);c(I=>({...I,[N]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},x=async b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];if(N){a("gallery");try{const T=await h(N,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,T]})),t({title:"Gallery image added!"})}catch(T){t({title:"Upload failed",description:T.message,variant:"destructive"})}finally{a(null)}}},y=async(b,N)=>{var T;const S=(T=b.target.files)==null?void 0:T[0];if(S){a(`testimonial-${N}`);try{const A=await h(S,`testimonial-${N}`);c(I=>{const D=[...I.testimonials];return D[N]={...D[N],photo_url:A},{...I,testimonials:D}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:v}=mt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:b,error:N}=await V.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(N)throw N;return b}}),w=`https://bestbrokerage.relevelup.com/join-brokerage/${(v==null?void 0:v.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:[(v==null?void 0:v.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:w}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Branding"})}),e.jsx(Pe,{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(he,{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(G,{variant:"outline",size:"sm",asChild:!0,disabled:n==="logo_url",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),n==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(he,{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:b=>c(N=>({...N,primary_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:o.primary_color,onChange:b=>c(N=>({...N,primary_color:b.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(he,{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:b=>c(N=>({...N,accent_color:b.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:o.accent_color,onChange:b=>c(N=>({...N,accent_color:b.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Headline"}),e.jsx(Ne,{value:o.hero_headline,onChange:b=>c(N=>({...N,hero_headline:b.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Subtext"}),e.jsx(or,{value:o.hero_subtext,onChange:b=>c(N=>({...N,hero_subtext:b.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(he,{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(G,{variant:"outline",size:"sm",asChild:!0,disabled:n==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),n==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:b=>m(b,"hero_image_url")})]}),o.hero_image_url&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,hero_image_url:null})),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,benefits:[...b.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Pe,{className:"space-y-3",children:[o.benefits.map((b,N)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(vu,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(Ne,{value:b.icon,onChange:S=>{const T=[...o.benefits];T[N]={...b,icon:S.target.value},c(A=>({...A,benefits:T}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ne,{value:b.title,onChange:S=>{const T=[...o.benefits];T[N]={...b,title:S.target.value},c(A=>({...A,benefits:T}))},placeholder:"Benefit title"}),e.jsx(Ne,{value:b.description,onChange:S=>{const T=[...o.benefits];T[N]={...b,description:S.target.value},c(A=>({...A,benefits:T}))},placeholder:"Short description"})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(S=>({...S,benefits:S.benefits.filter((T,A)=>A!==N)})),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]},N)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:"Testimonials"}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>c(b=>({...b,testimonials:[...b.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Pe,{className:"space-y-3",children:[o.testimonials.map((b,N)=>{var S;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:[b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.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:((S=b.name)==null?void 0:S[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:n===`testimonial-${N}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:T=>y(T,N)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ne,{value:b.name,onChange:T=>{const A=[...o.testimonials];A[N]={...b,name:T.target.value},c(I=>({...I,testimonials:A}))},placeholder:"Name"}),e.jsx(Ne,{value:b.role,onChange:T=>{const A=[...o.testimonials];A[N]={...b,role:T.target.value},c(I=>({...I,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(or,{value:b.quote,onChange:T=>{const A=[...o.testimonials];A[N]={...b,quote:T.target.value},c(I=>({...I,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(T=>({...T,testimonials:T.testimonials.filter((A,I)=>I!==N)})),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]},N)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{size:"sm",variant:"outline",asChild:!0,disabled:n==="gallery",children:e.jsxs("span",{children:[e.jsx(ml,{className:"h-3.5 w-3.5 mr-1"}),n==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x})]})]}),e.jsx(Pe,{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((b,N)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b,alt:`Gallery ${N+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(G,{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(S=>({...S,gallery_images:S.gallery_images.filter((T,A)=>A!==N)})),children:e.jsx(yr,{className:"h-3 w-3"})})]},N))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(jr,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Application Form Style"}),e.jsxs(Is,{value:o.form_style,onValueChange:b=>c(N=>({...N,form_style:b})),children:[e.jsx(As,{className:"mt-1.5",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(ct,{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(Hc,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(he,{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(_r,{checked:o.confidential_messaging,onCheckedChange:b=>c(N=>({...N,confidential_messaging:b}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(dA,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(_r,{checked:o.calculator_enabled,onCheckedChange:b=>c(N=>({...N,calculator_enabled:b}))})]}),o.calculator_enabled&&e.jsxs(Pe,{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(he,{className:"text-xs",children:"Calculator Headline"}),e.jsx(Ne,{value:o.calculator_config.headline||"",onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,headline:b.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subtext"}),e.jsx(Ne,{value:o.calculator_config.subtext||"",onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,subtext:b.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(he,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,commission_split_pct:parseFloat(b.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(he,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,cap_amount:parseFloat(b.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(he,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,post_cap_split_pct:parseFloat(b.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(he,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,monthly_fee:parseFloat(b.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(Ne,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,transaction_fee:parseFloat(b.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(he,{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(_r,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:b=>c(N=>({...N,calculator_config:{...N.calculator_config,show_email_capture:b}}))})]})]})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(O4,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(_r,{checked:o.lead_magnet_enabled,onCheckedChange:b=>c(N=>({...N,lead_magnet_enabled:b}))})]}),o.lead_magnet_enabled&&e.jsxs(Pe,{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(he,{className:"text-xs",children:"Title"}),e.jsx(Ne,{value:o.lead_magnet_config.title||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,title:b.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Description"}),e.jsx(or,{rows:2,value:o.lead_magnet_config.description||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,description:b.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(he,{className:"text-xs",children:"Button Text"}),e.jsx(Ne,{value:o.lead_magnet_config.button_text||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,button_text:b.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ne,{value:o.lead_magnet_config.pdf_url||"",onChange:b=>c(N=>({...N,lead_magnet_config:{...N.lead_magnet_config,pdf_url:b.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:n==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),n==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async b=>{var S;const N=(S=b.target.files)==null?void 0:S[0];if(N){a("lead_magnet_pdf");try{const T=await h(N,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:T}})),t({title:"PDF uploaded!"})}catch(T){t({title:"Upload failed",description:T.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(m6s,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(G,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Bl,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function m6s({brokerageId:s}){const{data:t=[]}=mt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:r,error:n}=await V.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(n)throw n;return r}});return t.length===0?null:e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ya,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(r=>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:[r.first_name||"—"," · ",r.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[_s(new Date(r.created_at),"MMM d, yyyy h:mm a")," · via ",r.source]})]})},r.id))})})]})}function txt({brokerageId:s,trigger:t,initialProspectId:r,open:n,onOpenChange:a}){const[i,l]=k.useState(!1),o=n??i,c=a??l,[d,h]=k.useState("pick-recipients"),[m,x]=k.useState(new Set(r?[r]:[])),[y,v]=k.useState("all"),[w,b]=k.useState(""),[N,S]=k.useState(null),[T,A]=k.useState(""),[I,D]=k.useState(0),[R,$]=k.useState(0),[F,z]=k.useState(""),[Q,K]=k.useState(""),[X,Z]=k.useState("default"),[re,le]=k.useState(null),{prospects:oe,stages:ne}=WB(s),ie=Upt(),ye=Yb(),{data:ce=[]}=mt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:Te,error:xe}=await V.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(xe)throw xe;return Te??[]},enabled:o&&d==="pick-video"}),ve=k.useCallback(()=>{h("pick-recipients"),x(new Set(r?[r]:[])),v("all"),b(""),S(null),A(""),D(0),$(0),z(""),K(""),Z("default"),le(null)},[r]),be=Te=>{!Te&&(d==="uploading"||d==="processing"||d==="sending")||(c(Te),Te||setTimeout(ve,200))},Ue=k.useMemo(()=>oe.filter(Te=>{if(!Te.email||y!=="all"&&Te.stage_id!==y)return!1;if(w){const xe=w.toLowerCase();if(!`${Te.first_name} ${Te.last_name??""}`.toLowerCase().includes(xe)&&!Te.email.toLowerCase().includes(xe))return!1}return!0}),[oe,y,w]),Be=Te=>{x(xe=>{const et=new Set(xe);return et.has(Te)?et.delete(Te):et.add(Te),et})},De=()=>{m.size===Ue.length?x(new Set):x(new Set(Ue.map(Te=>Te.id)))},Ae=k.useCallback(async(Te,xe)=>{h("uploading");try{const et=`Recruiting blast (${m.size} recipients)`,{videoId:fe,libraryId:it}=await h5(et),{uploadUrl:Oe,apiKey:Ye}=await m5(fe),We=new XMLHttpRequest;We.upload.onprogress=Xe=>{Xe.lengthComputable&&D(Xe.loaded/Xe.total*100)},await new Promise((Xe,Je)=>{We.onload=()=>We.status>=200&&We.status<300?Xe():Je(new Error("Upload failed")),We.onerror=()=>Je(new Error("Upload failed")),We.open("PUT",Oe),We.setRequestHeader("AccessKey",Ye),We.send(Te)}),h("processing");const _e=`https://iframe.mediadelivery.net/embed/${it}/${fe}`;let Re=0;const tt=Date.now(),Ke=9e4;for(;Re<4&&(await new Promise(Je=>setTimeout(Je,3e3)),!(Date.now()-tt>Ke));){const Xe=await Ev(fe);if(Re=Xe.status,$(Xe.encodeProgress||0),Re===5||Re===6)throw new Error("Video processing failed")}const Ze=await Ev(fe),lt=(Ze.storageSize||Te.size)/(1024*1024),xt=await ye.mutateAsync({bunny_video_id:fe,playback_url:Ze.directPlayUrl||_e,thumbnail_url:Ze.thumbnailUrl,preview_url:Ze.previewUrl||null,duration_seconds:Ze.length||xe,file_size_mb:lt,title:et,status:Re>=4?"ready":"processing",touch_type:"recruiting"});S(xt.id),A(et),h("compose")}catch(et){ue.error((et==null?void 0:et.message)||"Failed to upload video"),h("pick-video")}},[m.size,ye]),He=k.useCallback(async()=>{if(!(!N||m.size===0)){h("sending");try{const Te=[];for(const fe of m){const it=await ie.mutateAsync({prospect_id:fe,video_id:N,brokerage_id:s,message:Q||void 0});Te.push(it.id)}const{data:xe,error:et}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:Te,brokerage_id:s,subject_override:F||void 0,message_override:Q||void 0,send_via:X}});if(et)throw new Error(et.message);le({sent:(xe==null?void 0:xe.sent)??0,total:(xe==null?void 0:xe.total)??Te.length}),h("done"),ue.success(`Sent ${(xe==null?void 0:xe.sent)??0} of ${(xe==null?void 0:xe.total)??Te.length} videos`)}catch(Te){ue.error((Te==null?void 0:Te.message)||"Failed to send"),h("compose")}}},[N,m,s,Q,F,X,ie]),Le=m.size,Ie=oe.filter(Te=>!Te.email).length;return e.jsxs(fs,{open:o,onOpenChange:be,children:[t&&e.jsx(vi,{asChild:!0,children:t}),e.jsxs(ms,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Le>0&&e.jsxs(Ge,{variant:"secondary",className:"ml-2",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),Le," ",Le===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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search prospects...",value:w,onChange:Te=>b(Te.target.value),className:"pl-9"})]}),e.jsxs(Is,{value:y,onValueChange:v,children:[e.jsx(As,{className:"w-48",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All stages"}),ne.map(Te=>e.jsx(ct,{value:Te.id,children:Te.name},Te.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:De,className:"hover:underline",children:[m.size===Ue.length&&Ue.length>0?"Deselect all":"Select all"," ","(",Ue.length,")"]}),Ie>0&&e.jsxs("span",{children:[Ie," prospect(s) hidden — no email on file"]})]}),e.jsx(Qa,{className:"flex-1 border rounded-md",children:Ue.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:Ue.map(Te=>{const xe=m.has(Te.id),et=ne.find(fe=>fe.id===Te.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(Si,{checked:xe,onCheckedChange:()=>Be(Te.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:[Te.first_name," ",Te.last_name]}),et&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",style:{borderColor:et.color,color:et.color},children:et.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Te.email," ",Te.current_brokerage&&`· ${Te.current_brokerage}`]})]})]},Te.id)})})}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>be(!1),children:"Cancel"}),e.jsx(G,{disabled:Le===0,onClick:()=>h("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(On,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Rn,{className:"self-start",children:[e.jsxs(Kt,{value:"record",children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Kt,{value:"library",children:[e.jsx(q4,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(ts,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(gh,{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 ",Le," ",Le===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(G,{onClick:()=>h("record"),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(ts,{value:"library",className:"flex-1 overflow-auto",children:ce.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:ce.map(Te=>e.jsxs("button",{onClick:()=>{S(Te.id),A(Te.title||"Untitled"),h("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:Te.thumbnail_url?e.jsx("img",{src:Te.thumbnail_url,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(Jr,{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:Te.title||"Untitled"})})]},Te.id))})})]}),e.jsx(an,{children:e.jsx(G,{variant:"outline",onClick:()=>h("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(IL,{maxDurationSeconds:600,onRecordingComplete:Ae}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>h("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(es,{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(ei,{value:d==="uploading"?I:R,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?I:R),"%"]})]}),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(In,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:T})," selected · sending to ",e.jsx("strong",{children:Le})," recipient",Le===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(Ne,{value:F,onChange:Te=>z(Te.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(he,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(or,{value:Q,onChange:Te=>K(Te.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(qEe,{value:X,onChange:Z}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>h("pick-video"),children:"Back"}),e.jsxs(G,{onClick:He,disabled:!N||Le===0,children:[e.jsx(en,{className:"h-4 w-4 mr-2"})," Send to ",Le," ",Le===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(es,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Le," recipient",Le===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&re&&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 ${re.sent===re.total?"bg-primary/10":"bg-muted"}`,children:re.sent===re.total?e.jsx(In,{className:"h-8 w-8 text-primary"}):e.jsx(Oi,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[re.sent," of ",re.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(G,{onClick:()=>be(!1),children:"Done"})]})]})]})}function f6s(s){if(!s)return"—";const t=Math.floor(s/60),r=s%60;return t>0?`${t}m ${r}s`:`${r}s`}function p6s({video:s}){return s.cta_clicked_at?e.jsx(Ge,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Ge,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(bn,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Ge,{variant:"secondary",children:[e.jsx(en,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Ge,{variant:"outline",children:[e.jsx(fn,{className:"h-3 w-3 mr-1"}),"Draft"]})}function sxt({brokerageId:s}){var T,A,I,D;const{data:t=[],isLoading:r}=s6s(s),{data:n=[]}=Vpt(s),a=n6s(),i=a6s(),l=qpt(),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState({title:"",script_text:"",category:"general"}),[y,v]=k.useState(null),w=t.filter(R=>{var F,z,Q,K;return o?`${((F=R.prospect)==null?void 0:F.first_name)||""} ${((z=R.prospect)==null?void 0:z.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((K=(Q=R.video)==null?void 0:Q.title)==null?void 0:K.toLowerCase().includes(o.toLowerCase())):!0}),b={total:t.length,sent:t.filter(R=>R.sent_at).length,viewed:t.filter(R=>R.view_count>0).length,ctaClicked:t.filter(R=>R.cta_clicked_at).length},N=k.useCallback(R=>{if(!R)return;const $=`${window.location.origin}/recruit-video/${R}`;navigator.clipboard.writeText($),ue.success("Share link copied")},[]);k.useCallback((R,$)=>{l.mutate({id:R,sent_via:$})},[l]);const S=()=>{!m.title.trim()||!m.script_text.trim()||a.mutate({brokerage_id:s,...m},{onSuccess:()=>{x({title:"",script_text:"",category:"general"}),h(!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:b.total,icon:Jr,color:"text-primary"},{label:"Sent",value:b.sent,icon:en,color:"text-blue-500"},{label:"Viewed",value:b.viewed,icon:bn,color:"text-amber-500"},{label:"CTA Clicked",value:b.ctaClicked,icon:In,color:"text-emerald-500"}].map(R=>e.jsx(ke,{children:e.jsxs(Pe,{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 ${R.color}`,children:e.jsx(R.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:R.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:R.label})]})]})},R.label))}),e.jsxs(On,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"videos",children:[e.jsx(Jr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Kt,{value:"scripts",children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Kt,{value:"analytics",children:[e.jsx(ro,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(ts,{value:"videos",children:e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Dt,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or title...",value:o,onChange:R=>c(R.target.value),className:"pl-9"})]}),e.jsx(txt,{brokerageId:s,trigger:e.jsxs(G,{size:"sm",className:"gap-1.5",children:[e.jsx(Vs,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Pe,{children: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"})}):w.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Jr,{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:w.map(R=>{var $,F,z,Q,K,X,Z,re;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:[($=R.video)!=null&&$.thumbnail_url?e.jsx("img",{src:R.video.thumbnail_url,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(Jr,{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:f6s(((F=R.video)==null?void 0:F.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:[(z=R.prospect)==null?void 0:z.first_name," ",(Q=R.prospect)==null?void 0:Q.last_name]}),e.jsx(p6s,{video:R})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((K=R.video)==null?void 0:K.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[_s(new Date(R.created_at),"MMM d, yyyy"),((X=R.prospect)==null?void 0:X.current_brokerage)&&` · ${R.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>N(R.share_token),title:"Copy share link",children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsxs(G,{variant:R.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>v(R),disabled:!((Z=R.prospect)!=null&&Z.email),title:(re=R.prospect)!=null&&re.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(Vs,{className:"h-4 w-4"}),R.sent_at?"Resend":"Email"]}),R.share_token&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${R.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Qr,{className:"h-4 w-4"})})]})]},R.id)})})})]})}),e.jsx(ts,{value:"scripts",children:e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Dt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(fs,{open:d,onOpenChange:h,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"sm",children:[e.jsx($s,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(Ne,{value:m.title,onChange:R=>x($=>({...$,title:R.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Category"}),e.jsxs(Is,{value:m.category,onValueChange:R=>x($=>({...$,category:R})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:Dke.map(R=>e.jsx(ct,{value:R.value,children:R.label},R.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Script"}),e.jsx(or,{value:m.script_text,onChange:R=>x($=>({...$,script_text:R.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(G,{onClick:S,disabled:!m.title.trim()||!m.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Pe,{children:n.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ln,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No 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:n.map(R=>{var F;const $=((F=Dke.find(z=>z.value===R.category))==null?void 0:F.label)||R.category;return e.jsx(ke,{className:"relative group",children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ge,{variant:"outline",className:"text-[10px] mb-2",children:$}),e.jsx("h4",{className:"font-medium text-sm",children:R.title})]}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(R.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:R.script_text}),R.is_global&&e.jsx(Ge,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},R.id)})})})]})}),e.jsx(ts,{value:"analytics",children:e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Pe,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:b.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:b.sent,pct:b.total?Math.round(b.sent/b.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:b.viewed,pct:b.sent?Math.round(b.viewed/b.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:b.ctaClicked,pct:b.viewed?Math.round(b.ctaClicked/b.viewed*100):0,color:"bg-emerald-500"}].map(R=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:R.label}),e.jsxs("span",{className:"font-medium",children:[R.count," (",R.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${R.color} rounded-full transition-all`,style:{width:`${R.pct}%`}})})]},R.label))}),t.filter(R=>R.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(R=>R.view_count>0).sort((R,$)=>$.view_count-R.view_count).slice(0,5).map(R=>{var $,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:[($=R.prospect)==null?void 0:$.first_name," ",(F=R.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(bn,{className:"h-3.5 w-3.5"})," ",R.view_count]}),R.cta_clicked_at&&e.jsx(In,{className:"h-4 w-4 text-emerald-500"})]})]},R.id)})})]})]})]})})]}),y&&e.jsx($pt,{open:!!y,onOpenChange:R=>{R||v(null)},recruitVideoId:y.id,brokerageId:s,prospectName:`${((T=y.prospect)==null?void 0:T.first_name)||""} ${((A=y.prospect)==null?void 0:A.last_name)||""}`.trim(),prospectEmail:(I=y.prospect)==null?void 0:I.email,videoTitle:(D=y.video)==null?void 0:D.title,defaultMessage:y.message})]})}function rxt({brokerageId:s}){const{toast:t}=Ma(),r=Xt(),{stages:n,prospects:a}=WB(s),[i,l]=k.useState(!1),[o,c]=k.useState({title:"",target_count:"10",target_stage_id:"",period_start:_s(new Date,"yyyy-MM-dd"),period_end:_s(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:h}=mt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:v,error:w}=await V.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(w)throw w;return v}}),m=Ct({mutationFn:async v=>{const{data:{user:w}}=await V.auth.getUser();if(!w)throw new Error("Not authenticated");const{error:b}=await V.from("recruit_goals").insert({brokerage_id:s,title:v.title,target_count:parseInt(v.target_count),target_stage_id:v.target_stage_id||null,period_start:v.period_start,period_end:v.period_end,created_by:w.id});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),x=Ct({mutationFn:async v=>{const{error:w}=await V.from("recruit_goals").delete().eq("id",v);if(w)throw w},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),y=v=>{const w=n.find(N=>N.id===v.target_stage_id);return{count:a.filter(N=>dy(new Date(N.created_at),{start:new Date(v.period_start),end:new Date(v.period_end)})?v.target_stage_id?N.stage_id===v.target_stage_id:!0:!1).length,stage:w}};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.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs(G,{size:"sm",onClick:()=>l(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(ke,{className:"py-12 text-center",children:[e.jsx(Pd,{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(v=>{const{count:w,stage:b}=y(v),N=Math.min(100,w/v.target_count*100),S=dy(new Date,{start:new Date(v.period_start),end:new Date(v.period_end)});return e.jsxs(ke,{className:S?"":"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(Dt,{className:"text-sm",children:v.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[_s(new Date(v.period_start),"MMM d")," – ",_s(new Date(v.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[S?e.jsx(Ge,{className:"text-[10px]",children:"Active"}):e.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>x.mutate(v.id),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Pe,{className:"space-y-2",children:[b&&e.jsxs(Ge,{variant:"outline",className:"text-[10px]",style:{borderColor:b.color,color:b.color},children:["Stage: ",b.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:w}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",v.target_count]})]}),e.jsx(ei,{value:N,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[N.toFixed(0),"% complete"]})]})]},v.id)})}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),m.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Goal Title *"}),e.jsx(Ne,{required:!0,value:o.title,onChange:v=>c(w=>({...w,title:v.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Target Count *"}),e.jsx(Ne,{type:"number",min:"1",required:!0,value:o.target_count,onChange:v=>c(w=>({...w,target_count:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{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:v=>c(w=>({...w,target_stage_id:v.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),n.map(v=>e.jsx("option",{value:v.id,children:v.name},v.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(he,{children:"Start Date"}),e.jsx(Ne,{type:"date",required:!0,value:o.period_start,onChange:v=>c(w=>({...w,period_start:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"End Date"}),e.jsx(Ne,{type:"date",required:!0,value:o.period_end,onChange:v=>c(w=>({...w,period_end:v.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(G,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{type:"submit",disabled:m.isPending,children:"Create Goal"})]})]})]})})]})}const x6s={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function nxt({email:s,mergeValues:t=x6s,selectedSubjectIndex:r,onClose:n}){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=r??0,o=i[l]||s.subject_line;return e.jsx(fs,{open:!0,onOpenChange:()=>n(),children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(ys,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(gs,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Ge,{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,h)=>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 ${h===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:h===l?"Selected":h===0?"Primary":`Alt ${h}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},h))})]}),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 VEe({brokerageId:s}){const t=Xt(),[r,n]=k.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:a}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:c,error:d}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(d)throw d;return c}}),{data:i}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:c,error:d}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(d)throw d;return c}});k.useEffect(()=>{a?n({...a,merge_fields:a.merge_fields||{city:"",broker_name:""}}):i&&n(c=>({...c,merge_fields:{...c.merge_fields,brokerage_name:i.name,city:i.city||""}}))},[a,i]);const l=Ct({mutationFn:async()=>{const c={brokerage_id:s,sender_name:r.sender_name,sender_email:r.sender_email,reply_to_email:r.reply_to_email||null,merge_fields:r.merge_fields,updated_at:new Date().toISOString()};if(a!=null&&a.id){const{error:d}=await V.from("brokerage_recruit_settings").update(c).eq("id",a.id);if(d)throw d}else{const{error:d}=await V.from("brokerage_recruit_settings").insert(c);if(d)throw d}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ue.success("Recruiting email settings saved!")},onError:c=>ue.error(c.message)}),o=(c,d)=>{n(h=>({...h,merge_fields:{...h.merge_fields,[c]:d}}))};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:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Sender Display Name"}),e.jsx(Ne,{value:r.sender_name,onChange:c=>n({...r,sender_name:c.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"Sender Email Address"}),e.jsx(Ne,{value:r.sender_email,onChange:c=>n({...r,sender_email:c.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(he,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(Ne,{value:r.reply_to_email,onChange:c=>n({...r,reply_to_email:c.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(Ey,{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(Ppt,{brokerageId:s,onVerifiedSelect:c=>{n(d=>({...d,sender_email:c})),ue.success(`Sender set to ${c}`)}})]}),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(he,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(Ne,{value:r.merge_fields.brokerage_name||"",onChange:c=>o("brokerage_name",c.target.value),placeholder:(i==null?void 0:i.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"{{city}}"}),e.jsx(Ne,{value:r.merge_fields.city||"",onChange:c=>o("city",c.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(Ne,{value:r.merge_fields.sender_name||"",onChange:c=>o("sender_name",c.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(G,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",children:[e.jsx(Bl,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const g6s=Oy.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",Wc(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()}}}),iVe=[{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 Oh({onClick:s,active:t,disabled:r,icon:n,tooltip:a}){return e.jsxs(cc,{children:[e.jsx(dc,{asChild:!0,children:e.jsx(G,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:r,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(n,{className:"h-4 w-4"})})}),e.jsx(Gl,{side:"bottom",className:"text-xs",children:a})]})}function y6s({content:s,onChange:t}){const r=O3e({extensions:[B3e.configure({heading:{levels:[1,2,3]}}),g6s,Y3e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),Z3e.configure({types:["heading","paragraph"]}),X3e,dht],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())}});k.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const n=k.useCallback(()=>{if(!r)return;const i=r.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[r]),a=k.useCallback(i=>{r&&r.chain().focus().insertContent(`{{${i}}}`).run()},[r]);return r?e.jsx(Ub,{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(Oh,{onClick:()=>r.chain().focus().toggleBold().run(),active:r.isActive("bold"),icon:Yw,tooltip:"Bold"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleItalic().run(),active:r.isActive("italic"),icon:tj,tooltip:"Italic"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleUnderline().run(),active:r.isActive("underline"),icon:CA,tooltip:"Underline"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleStrike().run(),active:r.isActive("strike"),icon:qR,tooltip:"Strikethrough"}),e.jsx(fo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleHeading({level:1}).run(),active:r.isActive("heading",{level:1}),icon:pA,tooltip:"Heading 1"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleHeading({level:2}).run(),active:r.isActive("heading",{level:2}),icon:xA,tooltip:"Heading 2"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleHeading({level:3}).run(),active:r.isActive("heading",{level:3}),icon:_R,tooltip:"Heading 3"}),e.jsx(fo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleBulletList().run(),active:r.isActive("bulletList"),icon:em,tooltip:"Bullet List"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleOrderedList().run(),active:r.isActive("orderedList"),icon:Cy,tooltip:"Numbered List"}),e.jsx(Oh,{onClick:()=>r.chain().focus().toggleBlockquote().run(),active:r.isActive("blockquote"),icon:X4,tooltip:"Blockquote"}),e.jsx(Oh,{onClick:()=>r.chain().focus().setHorizontalRule().run(),icon:av,tooltip:"Divider"}),e.jsx(fo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Oh,{onClick:()=>r.chain().focus().setTextAlign("left").run(),active:r.isActive({textAlign:"left"}),icon:E4,tooltip:"Align Left"}),e.jsx(Oh,{onClick:()=>r.chain().focus().setTextAlign("center").run(),active:r.isActive({textAlign:"center"}),icon:T4,tooltip:"Align Center"}),e.jsx(Oh,{onClick:()=>r.chain().focus().setTextAlign("right").run(),active:r.isActive({textAlign:"right"}),icon:A4,tooltip:"Align Right"}),e.jsx(fo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Oh,{onClick:n,active:r.isActive("link"),icon:po,tooltip:"Insert Link"}),e.jsx(fo,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Oh,{onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),icon:cj,tooltip:"Undo"}),e.jsx(Oh,{onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),icon:oj,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(G,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{r&&r.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(TA,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(xd,{align:"end",className:"w-56",children:iVe.map(i=>e.jsxs(Pa,{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(D3e,{editor:r,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:"}),iVe.map(i=>e.jsx(Ge,{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 v6s({open:s,onClose:t,campaignName:r,stat:n}){return e.jsx(fs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(ms,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(bo,{className:"h-5 w-5 text-primary"}),r," — Engagement Stats"]}),e.jsx(Hr,{children:"Per-email breakdown of sends, opens, and clicks for this campaign at your brokerage."})]}),!n||n.sent===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(en,{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(K$,{icon:Vs,color:"text-blue-500",label:"Total Sent",value:n.sent.toLocaleString()}),e.jsx(K$,{icon:bn,color:"text-amber-500",label:"Opens",value:`${n.opened.toLocaleString()}`,sub:`${n.openRate.toFixed(1)}% open rate`}),e.jsx(K$,{icon:qc,color:"text-green-500",label:"Clicks",value:`${n.clicked.toLocaleString()}`,sub:`${n.clickRate.toFixed(1)}% click rate`}),e.jsx(K$,{icon:id,color:"text-destructive",label:"Failed",value:n.failed.toLocaleString()})]}),n.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(fn,{className:"h-3 w-3"})," Last sent: ",_s(new Date(n.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:n.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(ke,{className:"overflow-hidden",children:e.jsxs(Pe,{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(Ge,{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(Ge,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(bn,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(qc,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(id,{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 K$({icon:s,color:t,label:r,value:n,sub:a}){return e.jsx(ke,{children:e.jsx(Pe,{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:n}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:r}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function axt(s){return mt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:r}=await V.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(r)throw r;const n=t??[],a={};for(const i of n){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 oVe={cold:{icon:H0,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:mc,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function ixt({brokerageId:s}){var Ae,He,Le,Ie;const{user:t}=js(),r=Xt(),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[y,v]=k.useState("editor"),[w,b]=k.useState(null),[N,S]=k.useState(null),{data:T={}}=axt(s),[A,I]=k.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:D}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Te,error:xe}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(xe)throw xe;return Te}}),{data:R}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Te,error:xe}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(xe)throw xe;return Te}}),$={first_name:"Sarah",brokerage_name:((Ae=R==null?void 0:R.merge_fields)==null?void 0:Ae.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:((He=R==null?void 0:R.merge_fields)==null?void 0:He.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Le=R==null?void 0:R.merge_fields)==null?void 0:Le.sender_name)||(R==null?void 0:R.sender_name)||"Your Name"},F=Te=>Te.replace(/\{\{first_name\}\}/g,$.first_name).replace(/\{\{brokerage_name\}\}/g,$.brokerage_name).replace(/\{\{city\}\}/g,$.city).replace(/\{\{sender_name\}\}/g,$.sender_name),{data:z=[],isLoading:Q}=mt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Te,error:xe}=await V.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(xe)throw xe;return Te}}),{data:K={}}=mt({queryKey:["recruit-campaign-emails",s],enabled:z.length>0,queryFn:async()=>{const Te=z.map(it=>it.id),{data:xe,error:et}=await V.from("recruit_campaign_emails").select("*").in("campaign_id",Te).order("email_number");if(et)throw et;const fe={};return xe.forEach(it=>{fe[it.campaign_id]||(fe[it.campaign_id]=[]),fe[it.campaign_id].push(it)}),fe}}),X=Object.values(K).flat().map(Te=>Te.id),{data:Z=[]}=mt({queryKey:["recruit-subject-overrides",s],enabled:X.length>0,queryFn:async()=>{const{data:Te,error:xe}=await V.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(xe)throw xe;return Te}}),re={};Z.forEach(Te=>{re[Te.campaign_email_id]=Te.selected_subject_index});const le=Ct({mutationFn:async({campaignEmailId:Te,selectedIndex:xe})=>{const{error:et}=await V.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Te,selected_subject_index:xe,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(et)throw et},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ue.success("Subject line updated for your brokerage")},onError:Te=>ue.error(Te.message)}),oe=Ct({mutationFn:async Te=>{const{error:xe}=await V.from("recruit_campaign_emails").update({title:Te.title,subject_line:Te.subject_line,subject_line_options:Te.subject_line_options,body_html:Te.body_html,body_text:Te.body_text,delay_days:Te.delay_days,updated_at:new Date().toISOString()}).eq("id",Te.id);if(xe)throw xe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Email template saved!"),l(null)},onError:Te=>ue.error(Te.message)}),ne=Ct({mutationFn:async()=>{const Te=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:xe,error:et}=await V.from("recruit_campaigns").insert({name:A.name,slug:Te,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(et)throw et;const fe=[{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 V.from("recruit_campaign_emails").insert(fe.map(Oe=>({campaign_id:xe.id,...Oe,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 xe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Campaign created with 4 starter emails!"),x(!1),I({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Te=>ue.error(Te.message)}),ie=Ct({mutationFn:async Te=>{const{error:xe}=await V.from("recruit_campaigns").update({name:Te.name,description:Te.description,theme:Te.theme,goal:Te.goal,primary_cta:Te.primary_cta,warmth_level:Te.warmth_level,sender_name:Te.sender_name,sender_email:Te.sender_email,reply_to_email:Te.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Te.id);if(xe)throw xe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),ue.success("Campaign settings saved!"),b(null)},onError:Te=>ue.error(Te.message)}),ye=Ct({mutationFn:async Te=>{var Ye,We;const{data:xe}=await V.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Te).order("email_number",{ascending:!1}).limit(1),et=((Ye=xe==null?void 0:xe[0])==null?void 0:Ye.email_number)??0,fe=((We=xe==null?void 0:xe[0])==null?void 0:We.delay_days)??0,it=et+1,{error:Oe}=await V.from("recruit_campaign_emails").insert({campaign_id:Te,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:fe+7,is_active:!0});if(Oe)throw Oe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Email added to campaign!")},onError:Te=>ue.error(Te.message)}),ce=Ct({mutationFn:async Te=>{const{error:xe}=await V.from("recruit_campaigns").delete().eq("id",Te);if(xe)throw xe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaigns"]}),r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Campaign deleted")},onError:Te=>ue.error(Te.message)}),ve=Ct({mutationFn:async Te=>{const{error:xe}=await V.from("recruit_campaign_emails").delete().eq("id",Te);if(xe)throw xe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Email removed from campaign")},onError:Te=>ue.error(Te.message)}),be=Ct({mutationFn:async({emailId:Te,delay_days:xe})=>{const{error:et}=await V.from("recruit_campaign_emails").update({delay_days:xe,updated_at:new Date().toISOString()}).eq("id",Te);if(et)throw et},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ue.success("Send delay updated")},onError:Te=>ue.error(Te.message)});if(Q)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 Ue=z.filter(Te=>!Te.brokerage_id),Be=z.filter(Te=>Te.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(G,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-1.5",children:[e.jsx(oo,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(G,{size:"sm",onClick:()=>x(!0),className:"gap-1.5",children:[e.jsx($s,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(ke,{className:"border-primary/20 bg-primary/5",children:e.jsx(Pe,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(jr,{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(oo,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),Be.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(kR,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Be.map(Te=>De(Te,!0))})]}),Ue.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(jr,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Ue.map(Te=>De(Te,!1))})]}),z.length===0&&e.jsx(ke,{children:e.jsxs(Pe,{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(G,{className:"mt-4",onClick:()=>x(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(v6s,{open:!!N,onClose:()=>S(null),campaignName:(N==null?void 0:N.name)||"",stat:N&&T[N.id]||null}),o&&e.jsx(nxt,{email:o,mergeValues:$,selectedSubjectIndex:re[o.id],onClose:()=>c(null)}),e.jsx(fs,{open:!!i,onOpenChange:Te=>!Te&&l(null),children:e.jsxs(ms,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(ys,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Jw,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Hr,{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(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(Ne,{value:i.title,onChange:Te=>l({...i,title:Te.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(Ne,{type:"number",min:0,max:90,value:i.delay_days,onChange:Te=>l({...i,delay_days:parseInt(Te.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(Ne,{value:i.subject_line,onChange:Te=>l({...i,subject_line:Te.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(he,{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(or,{value:((Ie=i.subject_line_options)==null?void 0:Ie.join(` `))||"",onChange:Te=>l({...i,subject_line_options:Te.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(he,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(On,{value:y,onValueChange:Te=>v(Te),children:e.jsxs(Rn,{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"})]})})]}),y==="editor"?e.jsx(y6s,{content:i.body_html,onChange:Te=>l({...i,body_html:Te})}):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:[$.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:[$.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(G,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(G,{size:"sm",onClick:()=>oe.mutate(i),disabled:oe.isPending,className:"gap-1.5",children:[e.jsx(Bl,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(fs,{open:m,onOpenChange:x,children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx($s,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Hr,{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(he,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(Ne,{value:A.name,onChange:Te=>I({...A,name:Te.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(he,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Is,{value:A.warmth_level,onValueChange:Te=>I({...A,warmth_level:Te}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(ct,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(ct,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(Ne,{value:A.primary_cta,onChange:Te=>I({...A,primary_cta:Te.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Description"}),e.jsx(or,{value:A.description,onChange:Te=>I({...A,description:Te.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Goal"}),e.jsx(Ne,{value:A.goal,onChange:Te=>I({...A,goal:Te.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(Gp,{children:[e.jsx(Wp,{asChild:!0,children:e.jsxs(G,{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(Wi,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Kp,{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(he,{className:"text-xs",children:"Sender Name"}),e.jsx(Ne,{value:A.sender_name,onChange:Te=>I({...A,sender_name:Te.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Sender Email"}),e.jsx(Ne,{value:A.sender_email,onChange:Te=>I({...A,sender_email:Te.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(he,{className:"text-xs",children:"Reply-To Email"}),e.jsx(Ne,{value:A.reply_to_email,onChange:Te=>I({...A,reply_to_email:Te.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(G,{className:"w-full",disabled:!A.name.trim()||ne.isPending,onClick:()=>ne.mutate(),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(fs,{open:!!w,onOpenChange:Te=>!Te&&b(null),children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(oo,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Hr,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),w&&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(he,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(Ne,{value:w.name,onChange:Te=>b({...w,name:Te.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(Is,{value:w.warmth_level,onValueChange:Te=>b({...w,warmth_level:Te}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"cold",children:"❄️ Cold"}),e.jsx(ct,{value:"warm",children:"☀️ Warm"}),e.jsx(ct,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-medium",children:"Goal"}),e.jsx(Ne,{value:w.goal||"",onChange:Te=>b({...w,goal:Te.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(he,{className:"text-xs",children:"Sender Name"}),e.jsx(Ne,{value:w.sender_name||"",onChange:Te=>b({...w,sender_name:Te.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs",children:"Sender Email"}),e.jsx(Ne,{value:w.sender_email||"",onChange:Te=>b({...w,sender_email:Te.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(he,{className:"text-xs",children:"Reply-To Email"}),e.jsx(Ne,{value:w.reply_to_email||"",onChange:Te=>b({...w,reply_to_email:Te.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(G,{className:"w-full",onClick:()=>ie.mutate(w),disabled:ie.isPending,children:[e.jsx(Bl,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(fs,{open:d,onOpenChange:h,children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Default Recruiting Email Settings"}),e.jsx(Hr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(VEe,{brokerageId:s})]})})]});function De(Te,xe){const et=oVe[Te.warmth_level]||oVe.cold,fe=et.icon,it=K[Te.id]||[],Oe=n===Te.id,Ye=!!(Te.sender_name||Te.sender_email||Te.reply_to_email),We=T[Te.id];return e.jsxs(ke,{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(Oe?null:Te.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 ${et.bg} flex items-center justify-center`,children:e.jsx(fe,{className:`h-5 w-5 ${et.color}`})}),e.jsxs("div",{children:[e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[Te.name,e.jsx(Ge,{variant:Te.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Te.is_active?"Active":"Draft"}),xe&&e.jsx(Ge,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Ye&&e.jsxs(Ge,{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(Nr,{className:"text-xs mt-0.5",children:Te.theme||Te.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:_e=>{_e.stopPropagation(),b({...Te})},children:e.jsx(oo,{className:"h-4 w-4 text-muted-foreground"})}),xe&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:_e=>{_e.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&ce.mutate(Te.id)},children:e.jsx(yr,{className:"h-4 w-4"})}),We&&We.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"})," ",We.sent.toLocaleString()]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${We.openRate.toFixed(1)}% open rate`,children:[e.jsx(bn,{className:"h-2.5 w-2.5"})," ",We.opened.toLocaleString()," (",We.openRate.toFixed(0),"%)"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${We.clickRate.toFixed(1)}% click rate`,children:[e.jsx(qc,{className:"h-2.5 w-2.5"})," ",We.clicked.toLocaleString()," (",We.clickRate.toFixed(1),"%)"]})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:_e=>{_e.stopPropagation(),S(Te)},title:"View detailed engagement stats",children:[e.jsx(ro,{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:Oe?e.jsx(Jf,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Oe&&e.jsxs(Pe,{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:Te.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:Te.primary_cta||"—"})]})]}),Ye&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(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:[Te.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Te.sender_name]}),Te.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Te.sender_email]}),Te.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Te.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:it.map((_e,Re)=>{var tt,Ke;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[ReZe.stopPropagation(),onBlur:Ze=>{const lt=parseInt(Ze.target.value)||0;lt!==_e.delay_days&&be.mutate({emailId:_e.id,delay_days:lt})},onKeyDown:Ze=>{Ze.key==="Enter"&&Ze.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),_e.email_number===1?"Sent immediately":`Day ${_e.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",F(((tt=_e.subject_line_options)==null?void 0:tt.length)>0&&_e.subject_line_options[re[_e.id]??0]||_e.subject_line)]})]}),((Ke=_e.subject_line_options)==null?void 0:Ke.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(Is,{value:String(re[_e.id]??0),onValueChange:Ze=>le.mutate({campaignEmailId:_e.id,selectedIndex:parseInt(Ze)}),children:[e.jsx(As,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(Ls,{placeholder:"Choose subject line"})}),e.jsx(Ms,{children:_e.subject_line_options.map((Ze,lt)=>e.jsxs(ct,{value:String(lt),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[lt===0?"Primary":`Alt ${lt}`,":"]}),F(Ze)]},lt))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(_e),children:e.jsx(bn,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({..._e}),v("editor")},children:e.jsx(Ea,{className:"h-4 w-4"})}),xe&&it.length>1&&e.jsx(G,{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(_e.id)},children:e.jsx(yr,{className:"h-4 w-4"})})]})]})})]},_e.id)})}),xe&&e.jsxs(G,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ye.mutate(Te.id),disabled:ye.isPending,children:[e.jsx($s,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Te.id)}}const lVe={active:{icon:Uo,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:tm,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:di,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Sc,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},cVe={sent:{icon:Vs,color:"text-blue-500"},opened:{icon:bn,color:"text-amber-500"},clicked:{icon:qc,color:"text-green-500"},failed:{icon:id,color:"text-destructive"}};function oxt({brokerageId:s}){var Ae,He,Le,Ie,Te;const{user:t}=js(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(new Set),[d,h]=k.useState("assignments"),[m,x]=k.useState(null),[y,v]=k.useState(""),[w,b]=k.useState("all"),[N,S]=k.useState("all"),{data:T={}}=mt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:xe,error:et}=await V.from("recruit_campaign_emails").select("*").order("email_number");if(et)throw et;const fe={};return(xe??[]).forEach(it=>{fe[it.campaign_id]||(fe[it.campaign_id]=[]),fe[it.campaign_id].push(it)}),fe}}),{data:A}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(et)throw et;return xe}}),{data:I}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:xe,error:et}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(et)throw et;return xe}}),{data:D=[]}=mt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:xe,error:et}=await V.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(et)throw et;return xe}}),R={};D.forEach(xe=>{R[xe.campaign_email_id]=xe.selected_subject_index});const $={first_name:((Ae=m==null?void 0:m.prospect)==null?void 0:Ae.first_name)||"Sarah",brokerage_name:((He=I==null?void 0:I.merge_fields)==null?void 0:He.brokerage_name)||(A==null?void 0:A.name)||"Your Brokerage",city:((Le=I==null?void 0:I.merge_fields)==null?void 0:Le.city)||(A==null?void 0:A.city)||"Your City",sender_name:((Ie=I==null?void 0:I.merge_fields)==null?void 0:Ie.sender_name)||(I==null?void 0:I.sender_name)||"Your Name"},F=xe=>{const et=T[xe.campaign_id]||[],fe=xe.current_email_number+1;return et.find(it=>it.email_number===fe)||null},{data:z=[],isLoading:Q}=mt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let et=[],fe=0;for(;;){const{data:it,error:Oe}=await V.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(fe,fe+1e3-1);if(Oe)throw Oe;if(et=et.concat(it??[]),!it||it.length<1e3)break;fe+=1e3}return et}}),{data:K=[]}=mt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:xe,error:et}=await V.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(et)throw et;return xe}}),{data:X=[]}=mt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:xe,error:et}=await V.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(et)throw et;return xe}}),{data:Z=[]}=mt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let et=[],fe=0;for(;;){const{data:it,error:Oe}=await V.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(fe,fe+1e3-1);if(Oe)throw Oe;if(et=et.concat(it??[]),!it||it.length<1e3)break;fe+=1e3}return et}}),re=new Set(z.map(xe=>`${xe.prospect_id}-${xe.campaign_id}`)),le=Ct({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const xe=new Date,et=Array.from(o).filter(it=>!re.has(`${it}-${i}`)).map(it=>({prospect_id:it,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:xe.toISOString(),started_at:xe.toISOString()}));if(et.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:fe}=await V.from("recruit_campaign_assignments").insert(et);if(fe)throw fe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ue.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:xe=>ue.error(xe.message)}),oe=Ct({mutationFn:async({id:xe,newStatus:et})=>{const{error:fe}=await V.from("recruit_campaign_assignments").update({status:et,updated_at:new Date().toISOString()}).eq("id",xe);if(fe)throw fe},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ue.success("Assignment updated")}}),ne=Ct({mutationFn:async()=>{const{data:xe,error:et}=await V.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(et)throw et;return xe},onSuccess:xe=>{r.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),r.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ue.success(`Wave sent! ${xe.sent} emails delivered, ${xe.skipped} skipped, ${xe.failed} failed`)},onError:xe=>ue.error(`Send failed: ${xe.message}`)}),ie=z.filter(xe=>xe.status==="active").length;z.filter(xe=>xe.status==="completed").length;const ye=z.filter(xe=>xe.status==="active"&&xe.next_send_at&&new Date(xe.next_send_at)<=new Date).length,{data:ce={}}=axt(s),ve=z.reduce((xe,et)=>xe+Math.max(0,et.current_email_number||0),0),be=Object.values(ce).reduce((xe,et)=>xe+et.opened,0),Ue=Object.values(ce).reduce((xe,et)=>xe+et.clicked,0);Object.values(ce).reduce((xe,et)=>xe+et.failed,0);const Be=ve>0?Math.round(be/ve*100):0,De=ve>0?Ue/ve*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:[ye>0&&e.jsxs(G,{variant:"outline",onClick:()=>ne.mutate(),disabled:ne.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(Ku,{className:"h-4 w-4 mr-1"}),ne.isPending?"Sending...":`Send Next Wave (${ye})`]}),e.jsxs(G,{onClick:()=>a(!0),children:[e.jsx(en,{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(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(pr,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:z.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Uo,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ie}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{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:ve.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(bn,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Be,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",be.toLocaleString(),")"]})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(qc,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[De.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Ue.toLocaleString(),")"]})]})]})})]}),e.jsxs(On,{value:d,onValueChange:h,children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"assignments",children:["Active Drips (",ie,")"]}),e.jsxs(Kt,{value:"history",children:["Send History (",ve.toLocaleString(),")"]})]}),e.jsx(ts,{value:"assignments",className:"mt-4",children:Q?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"})}):z.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(en,{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:z.map(xe=>{var We,_e,Re,tt;const et=lVe[xe.status]||lVe.active,fe=et.icon,Oe=(T[xe.campaign_id]||[]).length||4,Ye=F(xe);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(Ge,{className:`text-xs ${et.color} border-0`,children:[e.jsx(fe,{className:"h-3 w-3 mr-1"}),et.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(We=xe.prospect)==null?void 0:We.first_name," ",(_e=xe.prospect)==null?void 0:_e.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(Re=xe.prospect)==null?void 0:Re.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(tt=xe.campaign)==null?void 0:tt.name," · Email ",xe.current_email_number,"/",Oe,xe.next_send_at&&xe.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(fn,{className:"h-3 w-3 inline"})," Next: ",_s(new Date(xe.next_send_at),"MMM d, h:mm a"),new Date(xe.next_send_at)<=new Date&&e.jsx(Ge,{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:[Ye&&e.jsx(G,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>x(xe),children:e.jsx(bn,{className:"h-3.5 w-3.5"})}),xe.status==="active"&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>oe.mutate({id:xe.id,newStatus:"paused"}),children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),xe.status==="paused"&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>oe.mutate({id:xe.id,newStatus:"active"}),children:e.jsx(Uo,{className:"h-3.5 w-3.5"})}),(xe.status==="active"||xe.status==="paused")&&e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>oe.mutate({id:xe.id,newStatus:"cancelled"}),children:e.jsx(Sc,{className:"h-3.5 w-3.5"})})]})]},xe.id)})})}),e.jsxs(ts,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(Is,{value:w,onValueChange:b,children:[e.jsx(As,{className:"w-[220px] h-8 text-xs",children:e.jsx(Ls,{placeholder:"All campaigns"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All campaigns"}),X.map(xe=>e.jsx(ct,{value:xe.id,children:xe.name},xe.id))]})]}),e.jsxs(Is,{value:N,onValueChange:S,children:[e.jsx(As,{className:"w-[160px] h-8 text-xs",children:e.jsx(Ls,{placeholder:"All statuses"})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"all",children:"All statuses"}),e.jsx(ct,{value:"sent",children:"Sent (no engagement)"}),e.jsx(ct,{value:"opened",children:"Opened"}),e.jsx(ct,{value:"clicked",children:"Clicked"})]})]}),(w!=="all"||N!=="all")&&e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{b("all"),S("all")},children:"Clear"})]}),(()=>{var et;const xe=K.filter(fe=>{var it;return!(w!=="all"&&((it=fe.campaign_email)==null?void 0:it.campaign_id)!==w||N==="opened"&&!fe.opened_at||N==="clicked"&&!fe.clicked_at||N==="sent"&&(fe.opened_at||fe.clicked_at))});return xe.length===0?e.jsx(ke,{children:e.jsxs(Pe,{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:K.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:K.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",xe.length," of ",K.length," recent sends",w!=="all"&&` · ${(et=X.find(fe=>fe.id===w))==null?void 0:et.name}`]}),e.jsx("div",{className:"space-y-1",children:xe.map(fe=>{var We,_e,Re;const it=cVe[fe.status]||cVe.sent,Oe=it.icon,Ye=(We=X.find(tt=>{var Ke;return tt.id===((Ke=fe.campaign_email)==null?void 0:Ke.campaign_id)}))==null?void 0:We.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(Oe,{className:`h-4 w-4 flex-shrink-0 ${it.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(_e=fe.prospect)==null?void 0:_e.first_name," ",(Re=fe.prospect)==null?void 0:Re.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",fe.email_number]}),Ye&&e.jsx(Ge,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Ye})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:fe.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[fe.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(bn,{className:"h-3 w-3"})," ",_s(new Date(fe.opened_at),"MMM d")]}),fe.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(qc,{className:"h-3 w-3"})," ",_s(new Date(fe.clicked_at),"MMM d")]}),e.jsx("span",{children:_s(new Date(fe.sent_at),"MMM d, h:mm a")})]})]},fe.id)})})]})})()]})]}),e.jsx(fs,{open:n,onOpenChange:xe=>{a(xe),xe||(v(""),c(new Set),l(""))},children:e.jsxs(ms,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(ys,{className:"px-6 pt-6 pb-4",children:[e.jsx(gs,{children:"Assign Campaign to Prospects"}),e.jsx(Hr,{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(he,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(Is,{value:i,onValueChange:l,children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Choose a campaign..."})}),e.jsx(Ms,{children:X.map(xe=>e.jsx(ct,{value:xe.id,children:xe.name},xe.id))})]})]}),i&&(()=>{const xe=y.toLowerCase(),et=Z.filter(Oe=>`${Oe.first_name} ${Oe.last_name}`.toLowerCase().includes(xe)||Oe.email.toLowerCase().includes(xe)),fe=et.filter(Oe=>!re.has(`${Oe.id}-${i}`)),it=fe.length>0&&fe.every(Oe=>o.has(Oe.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{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(yn,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:y,onChange:Oe=>v(Oe.target.value),className:"pl-9 h-9"})]}),e.jsxs(G,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(it){const Oe=new Set(o);fe.forEach(Ye=>Oe.delete(Ye.id)),c(Oe)}else{const Oe=new Set(o);fe.forEach(Ye=>Oe.add(Ye.id)),c(Oe)}},children:[e.jsx(uR,{className:"h-3.5 w-3.5 mr-1"}),it?"Deselect All":`Select All (${fe.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:et.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:y?"No prospects match your search":"No prospects found for this brokerage"}):et.map(Oe=>{const Ye=re.has(`${Oe.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Ye?"opacity-40":""}`,children:[e.jsx(Si,{checked:o.has(Oe.id),disabled:Ye,onCheckedChange:We=>{const _e=new Set(o);We?_e.add(Oe.id):_e.delete(Oe.id),c(_e)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Oe.first_name," ",Oe.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Oe.email})]}),Ye&&e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Oe.id)})}),et.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",et.length," of ",Z.length," prospects",fe.length0&&e.jsx(ke,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Pe,{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:(Te=X.find(xe=>xe.id===i))==null?void 0:Te.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(an,{className:"px-6 py-4 border-t",children:[e.jsx(G,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(G,{onClick:()=>le.mutate(),disabled:le.isPending||!i||o.size===0,children:[e.jsx(en,{className:"h-4 w-4 mr-1"}),le.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),m&&(()=>{const xe=F(m);return xe?e.jsx(nxt,{email:xe,mergeValues:$,selectedSubjectIndex:R[xe.id],onClose:()=>x(null)}):null})()]})}function lxt({brokerageId:s}){const t=Xt(),[r,n]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=k.useRef(!1),{data:d,isLoading:h}=mt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:b,error:N}=await V.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(N)throw N;return b},enabled:!!s});k.useEffect(()=>{if(d){if(c.current){c.current=!1;return}n(d.map(b=>({id:b.id,name:b.name,color:b.color,sort_order:b.sort_order}))),i([]),o(!1)}},[d]);const m=Ct({mutationFn:async()=>{for(const S of a){const{error:T}=await V.from("recruit_pipeline_stages").delete().eq("id",S);if(T)throw T}const b=r.filter(S=>S.id&&!S.isNew),N=r.filter(S=>!S.id||S.isNew);for(const S of b){const{error:T}=await V.from("recruit_pipeline_stages").update({name:S.name,color:S.color,sort_order:S.sort_order}).eq("id",S.id);if(T)throw T}if(N.length>0){const{error:S}=await V.from("recruit_pipeline_stages").insert(N.map(T=>({brokerage_id:s,name:T.name,color:T.color,sort_order:T.sort_order})));if(S)throw S}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ue.success("Pipeline stages saved!"),o(!1)},onError:b=>ue.error(b.message)}),x=(b,N,S)=>{n(T=>T.map((A,I)=>I===b?{...A,[N]:S}:A)),o(!0)},y=()=>{const b=r.length>0?Math.max(...r.map(N=>N.sort_order)):0;n(N=>[...N,{name:"",color:"#6366f1",sort_order:b+1,isNew:!0}]),o(!0)},v=b=>{const N=r[b];N.id&&!N.isNew&&i(S=>[...S,N.id]),n(S=>S.filter((T,A)=>A!==b)),o(!0)},w=(b,N)=>{const S=b+N;if(S<0||S>=r.length)return;const T=[...r];[T[b],T[S]]=[T[S],T[b]],T.forEach((A,I)=>A.sort_order=I+1),n(T),o(!0)};return h?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:r.map((b,N)=>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:()=>w(N,-1),disabled:N===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>w(N,1),disabled:N===r.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(vu,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:b.color,onChange:S=>x(N,"color",S.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(Ne,{value:b.name,onChange:S=>x(N,"name",S.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:N+1}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>v(N),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(yr,{className:"h-4 w-4"})})]},b.id||`new-${N}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:y,className:"gap-1",children:[e.jsx($s,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(G,{size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,className:"gap-1",children:[e.jsx(Bl,{className:"h-4 w-4"})," Save Changes"]})]}),r.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 b6s({brokerageId:s}){const{data:t=[],isLoading:r}=mt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:n,error:a}=await V.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 n||[]},enabled:!!s});return r?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(e3,{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(Ge,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(e3,{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(n=>e.jsxs(ke,{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(Dt,{className:"text-base",children:[n.first_name," ",n.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"}),n.email]}),n.current_brokerage&&e.jsxs("span",{children:["· ",n.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(on,{className:"h-3 w-3"}),n.unsubscribed_at&&_s(new Date(n.unsubscribed_at),"MMM d, yyyy")]})]})}),n.unsubscribe_reason&&e.jsx(Pe,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',n.unsubscribe_reason,'"']})})]},n.id))})]})}function _6s(){var o;const[s,t]=k.useState(""),[r,n]=k.useState("board"),{data:a=[],isLoading:i}=mt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await V.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(ws,{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(ws,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(Is,{value:l,onValueChange:t,children:[e.jsxs(As,{className:"w-[280px]",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),e.jsx(Ls,{placeholder:"Select brokerage"})]}),e.jsx(Ms,{children:a.map(c=>e.jsx(ct,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(txt,{brokerageId:l,trigger:e.jsxs(G,{size:"sm",className:"gap-1.5",children:[e.jsx(Jr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(On,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Rn,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Kt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Kt,{value:"video-outreach",children:[e.jsx(Jr,{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(en,{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(oo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Kt,{value:"pipeline-stages",children:[e.jsx(s3,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Kt,{value:"unsubscribed",children:[e.jsx(e3,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(ts,{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(G,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("board"),children:[e.jsx(xf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(G,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>n("table"),children:[e.jsx(SA,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(Wpt,{brokerageId:l}):e.jsx(sme,{brokerageId:l})]}),e.jsx(ts,{value:"contacts",children:e.jsx(sme,{brokerageId:l})}),e.jsx(ts,{value:"video-outreach",children:e.jsx(sxt,{brokerageId:l})}),e.jsx(ts,{value:"follow-ups",children:e.jsx(Jpt,{brokerageId:l})}),e.jsx(ts,{value:"referrals",children:e.jsx(Xpt,{brokerageId:l})}),e.jsx(ts,{value:"interest",children:e.jsx(Qpt,{brokerageId:l})}),e.jsx(ts,{value:"landing-page",children:e.jsx(ext,{brokerageId:l})}),e.jsx(ts,{value:"goals",children:e.jsx(rxt,{brokerageId:l})}),e.jsx(ts,{value:"metrics",children:e.jsx(Kpt,{brokerageId:l})}),e.jsx(ts,{value:"templates",children:e.jsx(Ypt,{brokerageId:l})}),e.jsx(ts,{value:"campaigns",children:e.jsx(ixt,{brokerageId:l})}),e.jsx(ts,{value:"drip-assignments",children:e.jsx(oxt,{brokerageId:l})}),e.jsx(ts,{value:"activity",children:e.jsx(Zpt,{brokerageId:l})}),e.jsx(ts,{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(VEe,{brokerageId:l})]})}),e.jsx(ts,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(lxt,{brokerageId:l})})}),e.jsx(ts,{value:"unsubscribed",children:e.jsx(b6s,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Sa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function w6s({brokerageId:s}){const[t,r]=k.useState(""),[n,a]=k.useState("all"),{data:i,isLoading:l}=mt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var b;const{data:d,error:h}=await V.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(h)throw h;const m=new Map((d||[]).map(N=>[N.id,N]));if(Array.from(m.keys()).length===0)return[];const{data:y}=await V.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:v}=await V.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}),w=[];for(const N of y||[]){const S=m.get(N.prospect_id);S&&w.push({id:`v-${N.id}`,kind:"video",prospect_id:N.prospect_id,prospect_name:`${S.first_name||""} ${S.last_name||""}`.trim()||"—",prospect_email:S.email,subject:(b=N.video)!=null&&b.title?`Video: ${N.video.title}`:"Recruiting Video",status:N.cta_clicked_at?"clicked":N.first_viewed_at?"viewed":"sent",sent_at:N.sent_at,opened_at:N.first_viewed_at,clicked_at:N.cta_clicked_at,view_count:N.view_count,share_token:N.share_token})}for(const N of v||[]){if(!N.sent_at)continue;const S=m.get(N.prospect_id);S&&w.push({id:`c-${N.id}`,kind:"campaign",prospect_id:N.prospect_id,prospect_name:`${S.first_name||""} ${S.last_name||""}`.trim()||"—",prospect_email:S.email,subject:N.subject||`Email #${N.email_number}`,status:N.status||"sent",sent_at:N.sent_at,opened_at:N.opened_at,clicked_at:N.clicked_at,error:N.error_message})}return w.sort((N,S)=>new Date(S.sent_at).getTime()-new Date(N.sent_at).getTime()),w}}),o=k.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(h=>h.kind==="video").length,campaigns:d.filter(h=>h.kind==="campaign").length,opened:d.filter(h=>h.opened_at).length,clicked:d.filter(h=>h.clicked_at).length}},[i]),c=k.useMemo(()=>(i||[]).filter(h=>{if(n!=="all"&&h.kind!==n)return!1;if(!t)return!0;const m=t.toLowerCase();return h.prospect_name.toLowerCase().includes(m)||(h.prospect_email||"").toLowerCase().includes(m)||h.subject.toLowerCase().includes(m)}),[i,t,n]);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:en,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:Jr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:Vs,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:bn,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:qc,color:"text-emerald-500"}].map(d=>e.jsx(ke,{children:e.jsxs(Pe,{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(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Dt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{value:n,onValueChange:d=>a(d),children:e.jsxs(Rn,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search recruit, subject...",value:t,onChange:d=>r(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Pe,{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(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Ge,{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(Ge,{variant:"destructive",className:"gap-1",children:[e.jsx(Oi,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Ge,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(qc,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Ge,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(bn,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Ge,{variant:"secondary",className:"gap-1",children:[e.jsx(en,{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:[_s(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:_s(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(bn,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(G,{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(Qr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function j6s(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:r}=js(),[n,a]=k.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(ws,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Sa,{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(ws,{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(Is,{value:i,onValueChange:r,children:[e.jsxs(As,{className:"w-[280px]",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),e.jsx(Ls,{placeholder:"Select brokerage"})]}),e.jsx(Ms,{children:s.map(o=>e.jsx(ct,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(On,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Rn,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Kt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Kt,{value:"contacts",children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Kt,{value:"video-outreach",children:[e.jsx(Jr,{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(en,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(Kt,{value:"sent-emails",children:[e.jsx(ej,{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(oo,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Kt,{value:"pipeline-stages",children:[e.jsx(s3,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(ts,{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(G,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(xf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(G,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(SA,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(Wpt,{brokerageId:i}):e.jsx(sme,{brokerageId:i})]}),e.jsx(ts,{value:"contacts",children:e.jsx(sme,{brokerageId:i})}),e.jsx(ts,{value:"video-outreach",children:e.jsx(sxt,{brokerageId:i})}),e.jsx(ts,{value:"follow-ups",children:e.jsx(Jpt,{brokerageId:i})}),e.jsx(ts,{value:"referrals",children:e.jsx(Xpt,{brokerageId:i})}),e.jsx(ts,{value:"interest",children:e.jsx(Qpt,{brokerageId:i})}),e.jsx(ts,{value:"landing-page",children:e.jsx(ext,{brokerageId:i})}),e.jsx(ts,{value:"goals",children:e.jsx(rxt,{brokerageId:i})}),e.jsx(ts,{value:"metrics",children:e.jsx(Kpt,{brokerageId:i})}),e.jsx(ts,{value:"templates",children:e.jsx(Ypt,{brokerageId:i})}),e.jsx(ts,{value:"campaigns",children:e.jsx(ixt,{brokerageId:i})}),e.jsx(ts,{value:"drip-assignments",children:e.jsx(oxt,{brokerageId:i})}),e.jsx(ts,{value:"sent-emails",children:e.jsx(w6s,{brokerageId:i})}),e.jsx(ts,{value:"activity",children:e.jsx(Zpt,{brokerageId:i})}),e.jsx(ts,{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(VEe,{brokerageId:i})]})}),e.jsx(ts,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(lxt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Sa,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function N6s(){const[s,t]=k.useState(""),{data:r,isLoading:n}=mt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await V.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await V.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await V.from("brokerage_content_categories").select("id, brokerage_id"),h=c||[],m=d||[],x=o.map(y=>{const v=h.filter(N=>N.brokerage_id===y.id),w=m.filter(N=>N.brokerage_id===y.id),b=v.length>0?v.reduce((N,S)=>S.created_at>N?S.created_at:N,v[0].created_at):null;return{brokerage_id:y.id,brokerage_name:y.name,total_items:v.length,videos:v.filter(N=>N.content_type==="video").length,pdfs:v.filter(N=>N.content_type==="pdf").length,links:v.filter(N=>N.content_type==="link"||N.content_type==="canva_link").length,events:v.filter(N=>N.content_type==="event").length,graphics:v.filter(N=>N.content_type==="graphic").length,latest_item_date:b,categories:w.length}});return x.sort((y,v)=>v.total_items-y.total_items),x}}),a=(r||[]).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(ws,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(eh,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Pe,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Pe,{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(ke,{children:[e.jsx(Mt,{className:"pb-2",children:e.jsx(Dt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Pe,{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(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(ke,{children:e.jsx(Pe,{className:"p-0",children:e.jsxs(Bn,{children:[e.jsx(zn,{children:e.jsxs(Ds,{children:[e.jsx(Nt,{children:"Brokerage"}),e.jsx(Nt,{className:"text-center",children:"Total"}),e.jsx(Nt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Nt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Nt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(tl,{className:"h-3 w-3"})," Links"]})}),e.jsx(Nt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(hd,{className:"h-3 w-3"})," Events"]})}),e.jsx(Nt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ml,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Nt,{className:"text-center",children:"Categories"}),e.jsx(Nt,{children:"Last Upload"})]})}),e.jsx($n,{children:n?e.jsx(Ds,{children:e.jsx(dt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(Ds,{children:e.jsx(dt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(Ds,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(dt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(dt,{className:"text-center",children:o.total_items>0?e.jsx(Ge,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(dt,{className:"text-center",children:o.videos||"–"}),e.jsx(dt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(dt,{className:"text-center",children:o.links||"–"}),e.jsx(dt,{className:"text-center",children:o.events||"–"}),e.jsx(dt,{className:"text-center",children:o.graphics||"–"}),e.jsx(dt,{className:"text-center",children:o.categories||"–"}),e.jsx(dt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:_s(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}function k6s(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 r=document.implementation.createHTMLDocument(),n=r.createElement("base"),a=r.createElement("a");return r.head.appendChild(n),r.body.appendChild(a),t&&(n.href=t),a.href=s,a.href}const S6s=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function _j(s){const t=[];for(let r=0,n=s.length;rjp||s.height>jp)&&(s.width>jp&&s.height>jp?s.width>s.height?(s.height*=jp/s.width,s.width=jp):(s.width*=jp/s.height,s.height=jp):s.width>jp?(s.height*=jp/s.width,s.width=jp):(s.width*=jp/s.height,s.height=jp))}function nme(s){return new Promise((t,r)=>{const n=new Image;n.onload=()=>{n.decode().then(()=>{requestAnimationFrame(()=>t(n))})},n.onerror=r,n.crossOrigin="anonymous",n.decoding="async",n.src=s})}async function M6s(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function I6s(s,t,r){const n="http://www.w3.org/2000/svg",a=document.createElementNS(n,"svg"),i=document.createElementNS(n,"foreignObject");return a.setAttribute("width",`${t}`),a.setAttribute("height",`${r}`),a.setAttribute("viewBox",`0 0 ${t} ${r}`),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),M6s(a)}const rp=(s,t)=>{if(s instanceof t)return!0;const r=Object.getPrototypeOf(s);return r===null?!1:r.constructor.name===t.name||rp(r,t)};function L6s(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function P6s(s,t){return cxt(t).map(r=>{const n=s.getPropertyValue(r),a=s.getPropertyPriority(r);return`${r}: ${n}${a?" !important":""};`}).join(" ")}function D6s(s,t,r,n){const a=`.${s}:${t}`,i=r.cssText?L6s(r):P6s(r,n);return document.createTextNode(`${a}{${i}}`)}function dVe(s,t,r,n){const a=window.getComputedStyle(s,r),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=S6s();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(D6s(l,r,a,n)),t.appendChild(o)}function R6s(s,t,r){dVe(s,t,":before",r),dVe(s,t,":after",r)}const uVe="application/font-woff",hVe="image/jpeg",O6s={woff:uVe,woff2:uVe,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:hVe,jpeg:hVe,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function F6s(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function HEe(s){const t=F6s(s).toLowerCase();return O6s[t]||""}function B6s(s){return s.split(/,/)[1]}function Rke(s){return s.search(/^(data:)/)!==-1}function z6s(s,t){return`data:${t};base64,${s}`}async function uxt(s,t,r){const n=await fetch(s,t);if(n.status===404)throw new Error(`Resource "${n.url}" not found`);const a=await n.blob();return new Promise((i,l)=>{const o=new FileReader;o.onerror=l,o.onloadend=()=>{try{i(r({res:n,result:o.result}))}catch(c){l(c)}},o.readAsDataURL(a)})}const Abe={};function $6s(s,t,r){let n=s.replace(/\?.*/,"");return r&&(n=s),/ttf|otf|eot|woff2?/i.test(n)&&(n=n.replace(/.*\//,"")),t?`[${t}]${n}`:n}async function GEe(s,t,r){const n=$6s(s,t,r.includeQueryParams);if(Abe[n]!=null)return Abe[n];r.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await uxt(s,r.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),B6s(o)));a=z6s(i,t)}catch(i){a=r.imagePlaceholder||"";let l=`Failed to fetch resource: ${s}`;i&&(l=typeof i=="string"?i:i.message),l&&console.warn(l)}return Abe[n]=a,a}async function U6s(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):nme(t)}async function q6s(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 nme(o)}const r=s.poster,n=HEe(r),a=await GEe(r,n,t);return nme(a)}async function V6s(s,t){var r;try{if(!((r=s==null?void 0:s.contentDocument)===null||r===void 0)&&r.body)return await Gxe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function H6s(s,t){return rp(s,HTMLCanvasElement)?U6s(s):rp(s,HTMLVideoElement)?q6s(s,t):rp(s,HTMLIFrameElement)?V6s(s,t):s.cloneNode(hxt(s))}const G6s=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",hxt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function W6s(s,t,r){var n,a;if(hxt(t))return t;let i=[];return G6s(s)&&s.assignedNodes?i=_j(s.assignedNodes()):rp(s,HTMLIFrameElement)&&(!((n=s.contentDocument)===null||n===void 0)&&n.body)?i=_j(s.contentDocument.body.childNodes):i=_j(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||rp(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>Gxe(o,r)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function K6s(s,t,r){const n=t.style;if(!n)return;const a=window.getComputedStyle(s);a.cssText?(n.cssText=a.cssText,n.transformOrigin=a.transformOrigin):cxt(r).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`),rp(s,HTMLIFrameElement)&&i==="display"&&l==="inline"&&(l="block"),i==="d"&&t.getAttribute("d")&&(l=`path(${t.getAttribute("d")})`),n.setProperty(i,l,a.getPropertyPriority(i))})}function Y6s(s,t){rp(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),rp(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function Z6s(s,t){if(rp(s,HTMLSelectElement)){const r=t,n=Array.from(r.children).find(a=>s.value===a.getAttribute("value"));n&&n.setAttribute("selected","")}}function X6s(s,t,r){return rp(t,Element)&&(K6s(s,t,r),R6s(s,t,r),Y6s(s,t),Z6s(s,t)),t}async function Q6s(s,t){const r=s.querySelectorAll?s.querySelectorAll("use"):[];if(r.length===0)return s;const n={};for(let i=0;iH6s(n,t)).then(n=>W6s(s,n,t)).then(n=>X6s(s,n,t)).then(n=>Q6s(n,t))}const mxt=/url\((['"]?)([^'"]+?)\1\)/g,J6s=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,eDs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function tDs(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function sDs(s){const t=[];return s.replace(mxt,(r,n,a)=>(t.push(a),r)),t.filter(r=>!Rke(r))}async function rDs(s,t,r,n,a){try{const i=r?k6s(t,r):t,l=HEe(t);let o;return a||(o=await GEe(i,l,n)),s.replace(tDs(t),`$1${o}$3`)}catch{}return s}function nDs(s,{preferredFontFormat:t}){return t?s.replace(eDs,r=>{for(;;){const[n,,a]=J6s.exec(r)||[];if(!a)return"";if(a===t)return`src: ${n};`}}):s}function fxt(s){return s.search(mxt)!==-1}async function pxt(s,t,r){if(!fxt(s))return s;const n=nDs(s,r);return sDs(n).reduce((i,l)=>i.then(o=>rDs(o,l,t,r)),Promise.resolve(n))}async function uE(s,t,r){var n;const a=(n=t.style)===null||n===void 0?void 0:n.getPropertyValue(s);if(a){const i=await pxt(a,null,r);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function aDs(s,t){await uE("background",s,t)||await uE("background-image",s,t),await uE("mask",s,t)||await uE("-webkit-mask",s,t)||await uE("mask-image",s,t)||await uE("-webkit-mask-image",s,t)}async function iDs(s,t){const r=rp(s,HTMLImageElement);if(!(r&&!Rke(s.src))&&!(rp(s,SVGImageElement)&&!Rke(s.href.baseVal)))return;const n=r?s.src:s.href.baseVal,a=await GEe(n,HEe(n),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"),r?(s.srcset="",s.src=a):s.href.baseVal=a})}async function oDs(s,t){const n=_j(s.childNodes).map(a=>xxt(a,t));await Promise.all(n).then(()=>s)}async function xxt(s,t){rp(s,Element)&&(await aDs(s,t),await iDs(s,t),await oDs(s,t))}function lDs(s,t){const{style:r}=s;t.backgroundColor&&(r.backgroundColor=t.backgroundColor),t.width&&(r.width=`${t.width}px`),t.height&&(r.height=`${t.height}px`);const n=t.style;return n!=null&&Object.keys(n).forEach(a=>{r[a]=n[a]}),s}const mVe={};async function fVe(s){let t=mVe[s];if(t!=null)return t;const n=await(await fetch(s)).text();return t={url:s,cssText:n},mVe[s]=t,t}async function pVe(s,t){let r=s.cssText;const n=/url\(["']?([^"')]+)["']?\)/g,i=(r.match(/url\([^)]+\)/g)||[]).map(async l=>{let o=l.replace(n,"$1");return o.startsWith("https://")||(o=new URL(o,s.url).href),uxt(o,t.fetchRequestInit,({result:c})=>(r=r.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>r)}function xVe(s){if(s==null)return[];const t=[],r=/(\/\*[\s\S]*?\*\/)/gi;let n=s.replace(r,"");const a=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const c=a.exec(n);if(c===null)break;t.push(c[0])}n=n.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(n);if(c===null){if(c=o.exec(n),c===null)break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;t.push(c[0])}return t}async function cDs(s,t){const r=[],n=[];return s.forEach(a=>{if("cssRules"in a)try{_j(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=fVe(c).then(h=>pVe(h,t)).then(h=>xVe(h).forEach(m=>{try{a.insertRule(m,m.startsWith("@import")?o+=1:a.cssRules.length)}catch(x){console.error("Error inserting rule from remote css",{rule:m,error:x})}})).catch(h=>{console.error("Error loading remote css",h.toString())});n.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&n.push(fVe(a.href).then(o=>pVe(o,t)).then(o=>xVe(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(n).then(()=>(s.forEach(a=>{if("cssRules"in a)try{_j(a.cssRules||[]).forEach(i=>{r.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),r))}function dDs(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>fxt(t.style.getPropertyValue("src")))}async function uDs(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const r=_j(s.ownerDocument.styleSheets),n=await cDs(r,t);return dDs(n)}function gxt(s){return s.trim().replace(/["']/g,"")}function hDs(s){const t=new Set;function r(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(i=>{t.add(gxt(i))}),Array.from(n.children).forEach(i=>{i instanceof HTMLElement&&r(i)})}return r(s),t}async function mDs(s,t){const r=await uDs(s,t),n=hDs(s);return(await Promise.all(r.filter(i=>n.has(gxt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return pxt(i.cssText,l,t)}))).join(` `)}async function fDs(s,t){const r=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await mDs(s,t);if(r){const n=document.createElement("style"),a=document.createTextNode(r);n.appendChild(a),s.firstChild?s.insertBefore(n,s.firstChild):s.appendChild(n)}}async function pDs(s,t={}){const{width:r,height:n}=dxt(s,t),a=await Gxe(s,t,!0);return await fDs(a,t),await xxt(a,t),lDs(a,t),await I6s(a,r,n)}async function xDs(s,t={}){const{width:r,height:n}=dxt(s,t),a=await pDs(s,t),i=await nme(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||E6s(),d=t.canvasWidth||r,h=t.canvasHeight||n;return l.width=d*c,l.height=h*c,t.skipAutoScale||A6s(l),l.style.width=`${d}`,l.style.height=`${h}`,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 gDs(s,t={}){return(await xDs(s,t)).toDataURL()}const NI=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Wxe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},Y$={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},yDs=({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})]})]}),yxt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=Wxe[t],h=[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:NI(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",NI(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:h})}),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(yDs,{branding:n,dim:l})]})]})]})});yxt.displayName="LuxuryDarkTemplate";const vDs=({branding:s,dim:t,accentColor:r})=>!(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 ${r}`,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})]})]}),vxt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var y;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(y=s.photos)==null?void 0:y[a],d=Wxe[t],h=r==="instagram-story",m=r==="facebook-post",x=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:m?"row":"column"},children:[e.jsxs("div",{style:{width:m?"55%":"100%",height:m?"100%":h?"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:x,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*(m?.055:.065),fontWeight:800,lineHeight:1.1,color:x,marginBottom:l.w*.012},children:NI(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:`${x}10`,border:`2px solid ${x}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:x,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(vDs,{branding:n,dim:l,accentColor:x})]})]})});vxt.displayName="ModernCleanTemplate";const bDs=({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})]})]}),bxt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var x;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(x=s.photos)==null?void 0:x[a],d=Wxe[t],h={"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)"},m=[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:h[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:NI(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:m}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background:h["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(bDs,{branding:n,dim:l})]})]})]})});bxt.displayName="BoldColorfulTemplate";const _Ds=({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})]})]}),_xt=wt.forwardRef(({listing:s,postType:t,format:r,branding:n,selectedPhotoIndex:a},i)=>{var m;const l=r==="instagram-story"?{w:1080,h:1920}:r==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=Wxe[t],h=r==="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:h?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:h?"100%":"42%",height:h?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:h?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*(h?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:NI(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",NI(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(_Ds,{branding:n,dim:l})]}),e.jsxs("div",{style:{width:h?"100%":"58%",height:h?"60%":"100%",position:"relative",overflow:"hidden",order:h?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"}})]})]})})});_xt.displayName="EditorialTemplate";const wDs=[{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:"📉"}],gVe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Jd,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Jd,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(yu,{className:"h-4 w-4"})}],jDs=[{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:"📰"}],yVe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),vVe={"luxury-dark":yxt,"modern-clean":vxt,"bold-colorful":bxt,editorial:_xt};function NDs(){const[s,t]=k.useState(""),[r,n]=k.useState("address"),[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(null),[h,m]=k.useState(0),[x,y]=k.useState("just-listed"),[v,w]=k.useState(["instagram-square"]),[b,N]=k.useState("luxury-dark"),[S,T]=k.useState(!1),[A,I]=k.useState(""),[D,R]=k.useState(""),[$,F]=k.useState(""),[z,Q]=k.useState(!1),[K,X]=k.useState(!1),[Z,re]=k.useState([]),[le,oe]=k.useState("search"),ne=k.useRef({});k.useEffect(()=>{(async()=>{const{data:{user:He}}=await V.auth.getUser();if(!He)return;const{data:Le}=await V.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",He.id).single();if(Le){I(Le.name||""),F(Le.avatar_url||"");const Ie=Le.brokerages;R((Ie==null?void 0:Ie.name)||"")}})()},[]);const ie=async()=>{var Ae;if(s.trim()){i(!0),o([]);try{const{data:He,error:Le}=await V.functions.invoke("repliers-mls-search",{body:{searchType:r,query:s.trim()}});if(Le)throw Le;if(He.error)throw new Error(He.error);o(He.listings||[]),((Ae=He.listings)==null?void 0:Ae.length)===0&&ue.info("No listings found. Try a different search.")}catch(He){ue.error(He.message||"Search failed")}finally{i(!1)}}},ye=Ae=>{var He;d(Ae),m(0),oe("customize"),Ae.soldDate||(He=Ae.status)!=null&&He.toLowerCase().includes("sold")?y("just-sold"):y("just-listed")},ce=Ae=>{w(He=>He.includes(Ae)?He.filter(Le=>Le!==Ae):[...He,Ae])},ve=k.useCallback(async()=>{if(!(!c||v.length===0)){Q(!0),re([]),oe("generate");try{await new Promise(He=>setTimeout(He,500));const Ae=[];for(const He of v){const Le=`${b}-${He}`,Ie=ne.current[Le];if(!Ie)continue;const Te=Y$[He],xe=await gDs(Ie,{width:Te.width,height:Te.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ae.push({format:He,imageUrl:xe})}re(Ae),ue.success(`Generated ${Ae.length} social post${Ae.length>1?"s":""}!`)}catch(Ae){ue.error(Ae.message||"Generation failed")}finally{Q(!1)}}},[c,v,b,h,S,A,D,$,x]),be=async()=>{if(!(!c||v.length===0)){Q(!0),re([]),oe("generate");try{const Ae={...c,photos:c.photos.length>0?[c.photos[h]]:[]},He=[];for(const Le of v){const{data:Ie,error:Te}=await V.functions.invoke("generate-listing-social-post",{body:{listing:Ae,postType:x,format:Le,branding:S?{enabled:!0,agentName:A,brokerage:D}:{enabled:!1}}});if(Te)throw Te;if(Ie.error)throw new Error(Ie.error);He.push({format:Le,imageUrl:Ie.imageUrl})}re(He),ue.success(`Generated ${He.length} AI post${He.length>1?"s":""}!`)}catch(Ae){ue.error(Ae.message||"AI generation failed")}finally{Q(!1)}}},Ue=()=>K?be():ve(),Be=(Ae,He)=>{var Ie;const Le=document.createElement("a");Le.href=Ae,Le.download=`${((Ie=c==null?void 0:c.address)==null?void 0:Ie.replace(/\s+/g,"-"))||"listing"}-${x}-${He}.png`,document.body.appendChild(Le),Le.click(),document.body.removeChild(Le)},De=c?{listing:c,postType:x,format:"instagram-square",branding:S?{enabled:!0,agentName:A,brokerage:D,agentPhotoUrl:$||void 0}:{enabled:!1},selectedPhotoIndex:h}:null;return e.jsx(ws,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(eh,{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:()=>oe("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${le==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(yn,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&oe("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${le==="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(jr,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(va,{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 ${le==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(ml,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),le==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(cnt,{})]}),e.jsx(Nr,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx(On,{value:r,onValueChange:Ae=>n(Ae),children:e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"address",children:[e.jsx(Ca,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Kt,{value:"mls",children:[e.jsx(wh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:s,onChange:Ae=>t(Ae.target.value),placeholder:r==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ae=>Ae.key==="Enter"&&ie()}),e.jsxs(G,{onClick:ie,disabled:a||!s.trim(),children:[a?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{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,He)=>{var Le;return e.jsx(ke,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ye(Ae),children:e.jsx(Pe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Le=Ae.photos)!=null&&Le[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(En,{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:yVe(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(M4,{className:"h-3 w-3"})," ",Ae.bedrooms]}),Ae.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Xf,{className:"h-3 w-3"})," ",Ae.bathrooms]}),Ae.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(SR,{className:"h-3 w-3"})," ",Ae.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Ae.mlsNumber}),e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Ae.status})]})]})]})})},Ae.mlsNumber||He)})})]})]}),le==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(ke,{className:"lg:col-span-1",children:[e.jsx(Mt,{className:"pb-3",children:e.jsx(Dt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Pe,{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[h],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(G,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Ae=>Math.max(0,Ae-1)),disabled:h===0,children:e.jsx($o,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h+1," of ",c.photos.length]}),e.jsx(G,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>m(Ae=>Math.min(c.photos.length-1,Ae+1)),disabled:h===c.photos.length-1,children:e.jsx(va,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:yVe(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(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{oe("search"),d(null)},children:[e.jsx(cv,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(ke,{className:"lg:col-span-2",children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Nr,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Pe,{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:K?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:K?"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(_r,{checked:K,onCheckedChange:X}),K&&e.jsx(Zx,{className:"h-4 w-4 text-purple-500"})]})]}),!K&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{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:jDs.map(Ae=>e.jsxs("button",{onClick:()=>N(Ae.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${b===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(he,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:wDs.map(Ae=>e.jsxs("button",{onClick:()=>y(Ae.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${x===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(he,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:gVe.map(Ae=>e.jsxs("button",{onClick:()=>ce(Ae.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${v.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(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Di,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(_r,{checked:S,onCheckedChange:T})]}),S&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[$&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:$,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(he,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(Ne,{value:A,onChange:Ae=>I(Ae.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(Ne,{value:D,onChange:Ae=>R(Ae.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!K&&De&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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*(Y$[v[0]||"instagram-square"].height/Y$[v[0]||"instagram-square"].width)},children:(()=>{const Ae=vVe[b],He=v[0]||"instagram-square";return e.jsx(Ae,{...De,format:He})})()})})]}),e.jsx(G,{onClick:Ue,disabled:v.length===0||z,size:"lg",className:"w-full gap-2",children:z?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-5 w-5 animate-spin"})," Generating ",v.length," post",v.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[K?e.jsx(Zx,{className:"h-5 w-5"}):e.jsx(jr,{className:"h-5 w-5"}),"Generate ",v.length," Social Post",v.length>1?"s":"",K&&e.jsx(Ge,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),le==="generate"&&e.jsxs("div",{className:"space-y-4",children:[z&&e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(es,{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:K?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),Z.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(G,{variant:"outline",size:"sm",onClick:()=>oe("customize"),children:[e.jsx(cv,{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:Z.map((Ae,He)=>{const Le=gVe.find(Ie=>Ie.value===Ae.format);return e.jsxs(ke,{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(Pe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Le==null?void 0:Le.icon,e.jsx("span",{className:"text-sm font-medium",children:Le==null?void 0:Le.label})]}),e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:Le==null?void 0:Le.dimensions})]}),e.jsxs(G,{size:"sm",className:"w-full gap-1.5",onClick:()=>Be(Ae.imageUrl,Ae.format),children:[e.jsx(Ya,{className:"h-3.5 w-3.5"})," Download"]})]})]},He)})})]})]}),le==="generate"&&!K&&c&&De&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:v.map(Ae=>{const He=vVe[b],Le=Y$[Ae];return e.jsx("div",{style:{width:Le.width,height:Le.height},children:e.jsx(He,{ref:Ie=>{ne.current[`${b}-${Ae}`]=Ie},...De,format:Ae})},`${b}-${Ae}`)})})]})})}function kDs(){return mt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await V.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function SDs(s){return mt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(r)throw r;return t!=null&&t.modules&&(t.modules.sort((n,a)=>n.sort_order-a.sort_order),t.modules.forEach(n=>{n.resources&&n.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function CDs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("lms_courses").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function wxt(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("lms_courses").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function TDs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("lms_courses").delete().eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function EDs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("lms_modules").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function ADs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("lms_modules").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function MDs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("lms_modules").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function IDs(){const s=Xt();return Ct({mutationFn:async t=>{const{data:r,error:n}=await V.from("lms_module_resources").insert(t).select().single();if(n)throw n;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function LDs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("lms_module_resources").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function PDs(){const s=Xt();return Ct({mutationFn:async({courseId:t,accessRules:r})=>{const{error:n}=await V.from("lms_course_access").delete().eq("course_id",t);if(n)throw n;if(r.length>0){const a=r.map(l=>({...l,course_id:t})),{error:i}=await V.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function DDs(){return mt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await V.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function RDs(s){return mt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(r)throw r;return t!=null&&t.modules&&(t.modules.sort((n,a)=>n.sort_order-a.sort_order),t.modules.forEach(n=>{n.resources&&n.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function jxt(s){return mt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("lms_progress").select("*").eq("course_id",s);if(r)throw r;return t},enabled:!!s})}function ODs(){const s=Xt();return Ct({mutationFn:async({courseId:t,moduleId:r,userId:n})=>{const{data:a,error:i}=await V.from("lms_progress").upsert({user_id:n,course_id:t,module_id:r,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 FDs(){const{user:s}=js(),t=br(),{data:r,isLoading:n}=kDs(),a=CDs(),i=wxt(),l=TDs(),[o,c]=k.useState(!1),[d,h]=k.useState(""),[m,x]=k.useState(""),[y,v]=k.useState(!0),w=async()=>{if(!(!d.trim()||!s))try{const S=await a.mutateAsync({title:d.trim(),description:m.trim()||void 0,is_sequential:y,created_by:s.id});ue.success("Course created"),c(!1),h(""),x(""),v(!0),t(`/admin/lms/${S.id}`)}catch{ue.error("Failed to create course")}},b=async S=>{try{await i.mutateAsync({id:S.id,is_published:!S.is_published}),ue.success(S.is_published?"Course unpublished":"Course published")}catch{ue.error("Failed to update course")}},N=async S=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(S),ue.success("Course deleted")}catch{ue.error("Failed to delete")}};return e.jsxs(ws,{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(Md,{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(G,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(G,{onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),n?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(S=>e.jsx(ke,{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"})]})},S))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(S=>{var D,R;const T=((R=(D=S.modules)==null?void 0:D[0])==null?void 0:R.count)??0,A=S.access||[],I=A.length===0?"No access set":A.some($=>$.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(ke,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${S.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(Dt,{className:"text-base truncate",children:S.title}),S.description&&e.jsx(Nr,{className:"mt-1 line-clamp-2",children:S.description})]}),e.jsx(Ge,{variant:S.is_published?"default":"secondary",className:"ml-2 shrink-0",children:S.is_published?"Published":"Draft"})]})}),e.jsxs(Pe,{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(bh,{className:"h-3.5 w-3.5"}),T," module",T!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[S.is_sequential?e.jsx(Cy,{className:"h-3.5 w-3.5"}):e.jsx(t3,{className:"h-3.5 w-3.5"}),S.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),I]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(G,{size:"sm",variant:"ghost",onClick:$=>{$.stopPropagation(),b(S)},children:[S.is_published?e.jsx(Xh,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"}),S.is_published?"Unpublish":"Publish"]}),e.jsx(G,{size:"sm",variant:"ghost",className:"text-destructive",onClick:$=>{$.stopPropagation(),N(S.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Ha,{className:"h-4 w-4 text-muted-foreground"})]})]})]},S.id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(bh,{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(G,{onClick:()=>c(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create New Course"}),e.jsx(Hr,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Course Title"}),e.jsx(Ne,{value:d,onChange:S=>h(S.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:m,onChange:S=>x(S.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(_r,{checked:y,onCheckedChange:v})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{onClick:w,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function BDs(){const{courseId:s}=Ki(),t=br(),{data:r,isLoading:n}=SDs(s),a=wxt(),i=EDs(),l=ADs(),o=MDs(),c=IDs(),d=LDs(),h=PDs(),{data:m}=mt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:Ke}=await V.from("brokerages").select("id, name").order("name");return Ke||[]}}),[x,y]=k.useState(null),[v,w]=k.useState(!1),[b,N]=k.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[S,T]=k.useState(null),[A,I]=k.useState({title:"",resource_type:"link",url:""}),[D,R]=k.useState(new Set),[$,F]=k.useState(null),[z,Q]=k.useState(0),[K,X]=k.useState(!1),Z=k.useRef(null),re=k.useRef(null),[le,oe]=k.useState(!1),[ne,ie]=k.useState(""),[ye,ce]=k.useState(""),[ve,be]=k.useState(""),[Ue,Be]=k.useState(!1);if(n)return e.jsx(ws,{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(!r)return e.jsx(ws,{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(G,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const De=r.modules||[],Ae=r.access||[],He=Ae.some(Ke=>Ke.access_type==="all"),Le=Ae.filter(Ke=>Ke.access_type==="brokerage").map(Ke=>Ke.brokerage_id),Ie=(m||[]).filter(Ke=>Ke.name.toLowerCase().includes(ne.toLowerCase())),Te=Ke=>{const Ze=new Set(D);Ze.has(Ke)?Ze.delete(Ke):Ze.add(Ke),R(Ze)},xe=async()=>{if(!$)return null;X(!0),Q(0);try{const{data:Ke,error:Ze}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:$.name}});if(Ze)throw new Error(Ze.message);const{videoId:lt,libraryId:xt}=Ke,{data:Xe,error:Je}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:lt,libraryId:xt}});if(Je)throw new Error(Je.message);const jt=new XMLHttpRequest;return await new Promise((ns,Ns)=>{jt.upload.onprogress=Ys=>{Ys.lengthComputable&&Q(Math.round(Ys.loaded/Ys.total*100))},jt.onload=()=>jt.status>=200&&jt.status<300?ns():Ns(new Error(`Upload failed: ${jt.status}`)),jt.onerror=()=>Ns(new Error("Upload failed")),jt.open("PUT",Xe.uploadUrl),jt.setRequestHeader("AccessKey",Xe.apiKey),jt.send($)}),`https://iframe.mediadelivery.net/embed/${xt}/${lt}`}catch(Ke){return console.error("Bunny upload error:",Ke),ue.error("Video upload failed"),null}finally{X(!1),Q(0)}},et=async()=>{if(b.title.trim())try{let Ke=b.video_url.trim()||void 0;if($){const Ze=await xe();if(!Ze)return;Ke=Ze}await i.mutateAsync({course_id:r.id,title:b.title.trim(),description:b.description.trim()||void 0,video_url:Ke,text_content:b.text_content.trim()||void 0,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):void 0,sort_order:De.length}),ue.success("Module added"),w(!1),N({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),F(null)}catch{ue.error("Failed to add module")}},fe=async()=>{if(x)try{let Ke=b.video_url.trim()||null;if($){const Ze=await xe();if(!Ze)return;Ke=Ze}await l.mutateAsync({id:x.id,title:b.title.trim(),description:b.description.trim()||null,video_url:Ke,text_content:b.text_content.trim()||null,duration_minutes:b.duration_minutes?parseInt(b.duration_minutes):null}),ue.success("Module updated"),y(null),F(null)}catch{ue.error("Failed to update")}},it=async Ke=>{if(confirm("Delete this module?"))try{await o.mutateAsync(Ke),ue.success("Module deleted")}catch{ue.error("Failed to delete")}},Oe=async Ke=>{if(A.title.trim())try{await c.mutateAsync({module_id:Ke,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),ue.success("Resource added"),T(null),I({title:"",resource_type:"link",url:""})}catch{ue.error("Failed to add resource")}},Ye=async()=>{try{await h.mutateAsync({courseId:r.id,accessRules:[{access_type:"all"}]}),ue.success("Access updated: All brokerages / all agents")}catch{ue.error("Failed to update access")}},We=async Ke=>{const Ze=Ae.filter(Je=>Je.access_type==="brokerage").map(Je=>Je.brokerage_id),lt=Ze.includes(Ke);let xt;lt?xt=Ze.filter(Je=>Je!==Ke):xt=[...Ze,Ke];const Xe=xt.map(Je=>({access_type:"brokerage",brokerage_id:Je}));try{await h.mutateAsync({courseId:r.id,accessRules:Xe}),ue.success(lt?"Brokerage removed":"Brokerage added")}catch{ue.error("Failed to update access")}},_e=async()=>{try{await h.mutateAsync({courseId:r.id,accessRules:[]}),ue.success("Access cleared")}catch{ue.error("Failed")}},Re=async(Ke,Ze)=>{const lt=Ze==="up"?Ke-1:Ke+1;if(!(lt<0||lt>=De.length))try{await Promise.all([l.mutateAsync({id:De[Ke].id,sort_order:lt}),l.mutateAsync({id:De[lt].id,sort_order:Ke})])}catch{ue.error("Failed to reorder")}},tt=async()=>{try{await a.mutateAsync({id:r.id,title:ye,description:ve||null}),ue.success("Course updated"),Be(!1)}catch{ue.error("Failed to update")}};return e.jsxs(ws,{title:r.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(G,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:r.title}),e.jsx(Ge,{variant:r.is_published?"default":"secondary",children:r.is_published?"Published":"Draft"})]}),r.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:r.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:[r.is_sequential?e.jsx(Cy,{className:"h-3.5 w-3.5"}):e.jsx(t3,{className:"h-3.5 w-3.5"}),r.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[De.length," module",De.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{ce(r.title),be(r.description||""),Be(!0)},children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(G,{variant:r.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:r.id,is_published:!r.is_published}).then(()=>ue.success(r.is_published?"Unpublished":"Published")),children:[r.is_published?e.jsx(Xh,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(bn,{className:"h-3.5 w-3.5 mr-1"}),r.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(On,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Rn,{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(ts,{value:"modules",className:"mt-6 space-y-4",children:[De.map((Ke,Ze)=>e.jsxs(ke,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Te(Ke.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:lt=>{lt.stopPropagation(),Re(Ze,"up")},disabled:Ze===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Jf,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:lt=>{lt.stopPropagation(),Re(Ze,"down")},disabled:Ze===De.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Wi,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Ge,{variant:"outline",className:"shrink-0 font-mono text-xs",children:Ze+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Ke.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[Ke.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Jr,{className:"h-3 w-3"})," Video"]}),Ke.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ln,{className:"h-3 w-3"})," Text"]}),Ke.duration_minutes&&e.jsxs("span",{children:[Ke.duration_minutes," min"]}),Ke.resources&&Ke.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(tl,{className:"h-3 w-3"})," ",Ke.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{size:"sm",variant:"ghost",onClick:lt=>{var xt;lt.stopPropagation(),y(Ke),N({title:Ke.title,description:Ke.description||"",video_url:Ke.video_url||"",text_content:Ke.text_content||"",duration_minutes:((xt=Ke.duration_minutes)==null?void 0:xt.toString())||""})},children:e.jsx(Ea,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"ghost",className:"text-destructive",onClick:lt=>{lt.stopPropagation(),it(Ke.id)},children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]}),D.has(Ke.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[Ke.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ke.description}),Ke.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:Ke.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:Ke.video_url})]}),Ke.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:Ke.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(G,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{T(Ke.id),I({title:"",resource_type:"link",url:""})},children:[e.jsx($s,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),Ke.resources&&Ke.resources.length>0?e.jsx("div",{className:"space-y-1",children:Ke.resources.map(lt=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:lt.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:lt.title}),lt.url&&e.jsx("a",{href:lt.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(G,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(lt.id),children:e.jsx(vr,{className:"h-3 w-3"})})]},lt.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},Ke.id)),e.jsxs(G,{variant:"outline",className:"w-full border-dashed",onClick:()=>{w(!0),N({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(ts,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Pe,{className:"space-y-5",children:[e.jsxs("div",{className:It("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",He?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Ye,children:[e.jsx("div",{className:It("h-10 w-10 rounded-full flex items-center justify-center shrink-0",He?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(fc,{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(_r,{checked:He,onCheckedChange:Ye})]}),!He&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Le.length===0?"No brokerages selected — agents won't see this course":`${Le.length} brokerage${Le.length!==1?"s":""} selected`})]}),Le.length>0&&e.jsx(G,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:_e,children:"Clear all"})]}),e.jsx(Ne,{placeholder:"Search brokerages...",value:ne,onChange:Ke=>ie(Ke.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Ie.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Ie.map(Ke=>{const Ze=Le.includes(Ke.id);return e.jsxs("div",{className:It("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",Ze?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>We(Ke.id),children:[e.jsx("div",{className:It("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",Ze?"bg-primary border-primary":"border-muted-foreground/30"),children:Ze&&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(Sa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:Ke.name}),Ze&&e.jsx(Ge,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},Ke.id)})})]})]})]})}),e.jsxs(ts,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Pe,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[r.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:r.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:r.id,thumbnail_url:null}).then(()=>ue.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(vr,{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(rv,{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:re,type:"file",accept:"image/*",className:"hidden",onChange:async Ke=>{var lt;const Ze=(lt=Ke.target.files)==null?void 0:lt[0];if(!(!Ze||!r)){oe(!0);try{const xt=Ze.name.split(".").pop(),Xe=`${r.id}/thumbnail.${xt}`,{error:Je}=await V.storage.from("lms-thumbnails").upload(Xe,Ze,{upsert:!0});if(Je)throw Je;const{data:jt}=V.storage.from("lms-thumbnails").getPublicUrl(Xe),ns=`${jt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:r.id,thumbnail_url:ns}),ue.success("Thumbnail uploaded")}catch{ue.error("Failed to upload thumbnail")}finally{oe(!1),re.current&&(re.current.value="")}}}}),e.jsxs(G,{variant:"outline",size:"sm",disabled:le,onClick:()=>{var Ke;return(Ke=re.current)==null?void 0:Ke.click()},children:[le?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-2"}),le?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Course Settings"})}),e.jsxs(Pe,{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(_r,{checked:r.is_sequential,onCheckedChange:Ke=>a.mutateAsync({id:r.id,is_sequential:Ke}).then(()=>ue.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(_r,{checked:r.is_published,onCheckedChange:Ke=>a.mutateAsync({id:r.id,is_published:Ke}).then(()=>ue.success("Updated"))})]})]})]})]})]})]}),e.jsx(fs,{open:v||!!x,onOpenChange:Ke=>{Ke||(w(!1),y(null))},children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:x?"Edit Module":"Add Module"}),e.jsx(Hr,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(Ne,{value:b.title,onChange:Ke=>N(Ze=>({...Ze,title:Ke.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:b.description,onChange:Ke=>N(Ze=>({...Ze,description:Ke.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:It("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",$?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var Ke;return(Ke=Z.current)==null?void 0:Ke.click()},children:[e.jsx("input",{ref:Z,type:"file",accept:"video/*",className:"hidden",onChange:Ke=>{var lt;const Ze=(lt=Ke.target.files)==null?void 0:lt[0];Ze&&(F(Ze),N(xt=>({...xt,video_url:""})))}}),$?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(Jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:$.name}),e.jsx(G,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:Ke=>{Ke.stopPropagation(),F(null)},children:e.jsx(vr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(da,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),K&&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(es,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",z,"%"]})]}),e.jsx(ei,{value:z,className:"h-1.5"})]}),!$&&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(Ne,{value:b.video_url,onChange:Ke=>N(Ze=>({...Ze,video_url:Ke.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Text Content"}),e.jsx(or,{value:b.text_content,onChange:Ke=>N(Ze=>({...Ze,text_content:Ke.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Duration (minutes)"}),e.jsx(Ne,{type:"number",value:b.duration_minutes,onChange:Ke=>N(Ze=>({...Ze,duration_minutes:Ke.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>{w(!1),y(null),F(null)},children:"Cancel"}),e.jsxs(G,{onClick:x?fe:et,disabled:!b.title.trim()||K,children:[K?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Bl,{className:"h-4 w-4 mr-2"}),K?"Uploading...":x?"Save Changes":"Add Module"]})]})]})}),e.jsx(fs,{open:!!S,onOpenChange:Ke=>{Ke||T(null)},children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Add Resource"}),e.jsx(Hr,{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(he,{children:"Title"}),e.jsx(Ne,{value:A.title,onChange:Ke=>I(Ze=>({...Ze,title:Ke.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Type"}),e.jsxs(Is,{value:A.resource_type,onValueChange:Ke=>I(Ze=>({...Ze,resource_type:Ke})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"link",children:"Link"}),e.jsx(ct,{value:"pdf",children:"PDF"}),e.jsx(ct,{value:"template",children:"Template"}),e.jsx(ct,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"URL"}),e.jsx(Ne,{value:A.url,onChange:Ke=>I(Ze=>({...Ze,url:Ke.target.value})),placeholder:"https://..."})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>T(null),children:"Cancel"}),e.jsx(G,{onClick:()=>S&&Oe(S),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(fs,{open:Ue,onOpenChange:Be,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Edit Course"}),e.jsx(Hr,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Title"}),e.jsx(Ne,{value:ye,onChange:Ke=>ce(Ke.target.value)})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:ve,onChange:Ke=>be(Ke.target.value),rows:3})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>Be(!1),children:"Cancel"}),e.jsx(G,{onClick:tt,disabled:!ye.trim(),children:"Save"})]})]})})]})}function zDs(){return mt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await V.rpc("get_lms_stats");if(t)throw t;return s}})}function $Ds(){return mt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await V.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function UDs(s){return mt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.rpc("get_lms_agent_progress",{p_course_id:s});if(r)throw r;return t||[]},enabled:!!s})}function qDs(){const s=br(),{data:t,isLoading:r}=zDs(),{data:n,isLoading:a}=$Ds(),[i,l]=k.useState(null),{data:o,isLoading:c}=UDs(i),[d,h]=k.useState(""),m=n==null?void 0:n.find(v=>v.course_id===i),x=o==null?void 0:o.filter(v=>{var w,b;return!d||((w=v.agent_name)==null?void 0:w.toLowerCase().includes(d.toLowerCase()))||((b=v.email)==null?void 0:b.toLowerCase().includes(d.toLowerCase()))}),y=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:bh,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:In,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:pr,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:Gi,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:bo,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:ro,color:"text-rose-500"}];return e.jsx(ws,{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(G,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Md,{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:y.map(v=>e.jsx(ke,{className:It("transition-all",r&&"animate-pulse"),children:e.jsxs(Pe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(v.icon,{className:It("h-4 w-4",v.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:r?"—":v.value})]})},v.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(ro,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(v=>e.jsx(ke,{className:"animate-pulse",children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},v))}):n!=null&&n.length?e.jsx("div",{className:"space-y-2",children:n.map(v=>{const w=i===v.course_id;return e.jsx(ke,{className:It("cursor-pointer transition-all hover:shadow-md",w?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(w?null:v.course_id),children:e.jsxs(Pe,{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:v.course_title}),e.jsx(Ge,{variant:v.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:v.is_published?"Live":"Draft"})]})}),e.jsx(va,{className:It("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",w&&"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:v.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:v.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:v.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:[v.avg_completion_pct,"%"]})]}),e.jsx(ei,{value:v.avg_completion_pct,className:"h-2"})]})]})},v.course_id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Pe,{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(uv,{className:"h-5 w-5 text-primary"}),m?`Agent Progress — ${m.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{value:d,onChange:v=>h(v.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(v=>e.jsx(ke,{className:"animate-pulse",children:e.jsx(Pe,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},v))}):x!=null&&x.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:x.map((v,w)=>{const b=v.completion_pct>=100;return e.jsx(ke,{className:It("transition-all",b&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:It("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",w===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":w===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":w===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:w+1}),e.jsxs(Nn,{className:"h-9 w-9 shrink-0",children:[e.jsx(ya,{src:v.avatar_url||void 0}),e.jsx(kn,{className:"text-xs bg-primary/10 text-primary",children:(v.agent_name||v.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:v.agent_name||v.email}),b&&e.jsxs(Ge,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(In,{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:[v.modules_completed,"/",v.total_modules," modules"]}),v.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),_s(new Date(v.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:It("text-sm font-bold",b?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[v.completion_pct,"%"]}),e.jsx(ei,{value:v.completion_pct,className:"h-1.5 mt-1"})]})]})})},v.user_id)})}):e.jsx(ke,{className:"border-dashed",children:e.jsx(Pe,{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(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"py-16 text-center",children:[e.jsx(pr,{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 VDs(){const{user:s}=js(),t=br(),{data:r,isLoading:n}=DDs();return e.jsx(ws,{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(Md,{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"})]}),n?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(ke,{className:"animate-pulse",children:e.jsxs(Pe,{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))}):r!=null&&r.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:r.map(a=>e.jsx(HDs,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(bh,{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 HDs({course:s,userId:t,onClick:r}){var o;const n=((o=s.modules)==null?void 0:o.length)??0,{data:a}=jxt(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=n>0?Math.round(i/n*100):0;return e.jsxs(ke,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:r,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(Md,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Pe,{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(bh,{className:"h-3.5 w-3.5"}),n," module",n!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(Cy,{className:"h-3.5 w-3.5"}):e.jsx(t3,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),n>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 ",n," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(ei,{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(va,{className:"h-3.5 w-3.5"})]})})]})]})}function GDs(){const{courseId:s}=Ki(),t=br(),{user:r}=js(),{data:n,isLoading:a}=RDs(s),{data:i}=jxt(s),l=ODs(),[o,c]=k.useState(null),d=(n==null?void 0:n.modules)||[],h=new Set((i==null?void 0:i.filter(S=>S.completed).map(S=>S.module_id))||[]),m=h.size,x=d.length>0?Math.round(m/d.length*100):0;k.useEffect(()=>{if(d.length>0&&!o){const S=d.find(T=>!h.has(T.id));c((S==null?void 0:S.id)||d[0].id)}},[d,o,h]);const y=d.find(S=>S.id===o),v=d.findIndex(S=>S.id===o),w=(S,T)=>{if(!(n!=null&&n.is_sequential)||T===0)return!1;for(let A=0;A{if(!(!y||!r||!s))try{await l.mutateAsync({courseId:s,moduleId:y.id,userId:r.id}),ue.success("Module completed! 🎉"),v{const T=S.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(T)return`https://www.youtube.com/embed/${T[1]}`;const A=S.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const I=S.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return I?`https://iframe.mediadelivery.net/embed/${I[1]}/${I[2]}?responsive=true`:S};return a?e.jsx(ws,{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"})})}):n?e.jsx(ws,{title:n.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:n.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[m,"/",d.length," completed"]}),e.jsxs("span",{children:[x,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(ei,{value:x,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(ke,{className:"lg:sticky lg:top-4",children:e.jsxs(Pe,{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(Qa,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((S,T)=>{const A=w(S,T),I=h.has(S.id),D=S.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(S.id),className:It("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",D?"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(Hc,{className:"h-4 w-4 text-muted-foreground"}):I?e.jsx(In,{className:"h-4 w-4 text-green-500"}):e.jsx(Ld,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:It("font-medium truncate",D&&"text-primary"),children:[T+1,". ",S.title]}),S.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(fn,{className:"h-3 w-3"})," ",S.duration_minutes," min"]})]})]},S.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:y?e.jsxs(e.Fragment,{children:[y.video_url&&e.jsx(ke,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:N(y.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(ke,{children:e.jsxs(Pe,{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:y.title}),y.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:y.description})]}),h.has(y.id)?e.jsxs(Ge,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(In,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(G,{size:"sm",onClick:b,disabled:l.isPending,children:[e.jsx(In,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),y.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:y.text_content}),y.resources&&y.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:y.resources.map(S=>e.jsxs("a",{href:S.url||S.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:[S.resource_type==="pdf"?e.jsx(ln,{className:"h-4 w-4 text-red-500 shrink-0"}):S.resource_type==="template"?e.jsx(Md,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(tl,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:S.title}),e.jsx(Qr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},S.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(G,{variant:"outline",size:"sm",disabled:v===0,onClick:()=>v>0&&c(d[v-1].id),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),vc(d[v+1].id),children:["Next ",e.jsx(va,{className:"h-3.5 w-3.5 ml-1"})]}):x===100&&e.jsx(Ge,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(ke,{children:e.jsx(Pe,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(ws,{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(G,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function WDs({headline:s,subtext:t,primaryColor:r,accentColor:n,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, ${n} 0%, ${r} 50%, ${n}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(Sr.img,{src:i,alt:l,className:"h-14 md:h-20 w-auto mx-auto mb-10 drop-shadow-2xl",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.8,delay:.2}}),e.jsx(Sr.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.3},children:e.jsx("span",{className:"inline-block text-white/70 text-sm md:text-base font-medium tracking-[0.2em] uppercase mb-6",children:"Your Next Chapter Starts Here"})}),e.jsx(Sr.h1,{className:"text-4xl md:text-6xl lg:text-7xl font-bold text-white mb-8 leading-[1.1] tracking-tight",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.9,delay:.5},children:s}),e.jsx(Sr.p,{className:"text-lg md:text-xl text-white/80 mb-12 max-w-2xl mx-auto leading-relaxed font-light",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.7},children:t}),e.jsxs(Sr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:n},children:["Get In Touch",e.jsx(Ha,{className:"h-5 w-5 transition-transform group-hover:translate-x-1"})]}),e.jsx("a",{href:"#benefits",className:"inline-flex items-center gap-2 px-8 py-4 rounded-full text-base font-medium text-white/90 border border-white/30 backdrop-blur-sm transition-all duration-300 hover:bg-white/10 hover:border-white/50",children:"Learn More"})]})]}),e.jsx(Sr.div,{className:"absolute bottom-8 left-1/2 -translate-x-1/2 z-10",animate:{y:[0,8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:e.jsx("div",{className:"w-6 h-10 border-2 border-white/40 rounded-full flex justify-center pt-2",children:e.jsx("div",{className:"w-1.5 h-3 bg-white/60 rounded-full"})})})]})}function ux({children:s,className:t="",delay:r=0,direction:n="up"}){const a=k.useRef(null),i=IFt(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:n==="up"?40:0,x:n==="left"?-40:n==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Sr.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:r,ease:[.25,.46,.45,.94]},className:t,children:s})}function KDs({benefits:s,accentColor:t,primaryColor:r}){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(ux,{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:r},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:r}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8",children:s.map((n,a)=>e.jsx(ux,{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, ${r}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:`${r}12`},children:n.icon}),e.jsx("h3",{className:"text-xl font-bold mb-3 tracking-tight",style:{color:t},children:n.title}),e.jsx("p",{className:"text-gray-500 leading-relaxed text-[15px]",children:n.description})]})]})},a))})]})})}function YDs({images:s,primaryColor:t,accentColor:r}){const[n,a]=k.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(ux,{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(pr,{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:r},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(ux,{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))})]})}),n!==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(vr,{className:"h-8 w-8"})}),e.jsx("img",{src:s[n],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function ZDs({testimonials:s,primaryColor:t,accentColor:r}){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(ux,{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:r},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((n,a)=>{var i;return e.jsx(ux,{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(X4,{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:['"',n.quote,'"']}),e.jsxs("div",{className:"flex items-center gap-4",children:[n.photo_url?e.jsx("img",{src:n.photo_url,alt:n.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}, ${r})`},children:((i=n.name)==null?void 0:i[0])||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-base",style:{color:r},children:n.name}),n.role&&e.jsx("p",{className:"text-sm text-gray-500",children:n.role})]})]})]})},a)})})]})})}function XDs({form:s,setForm:t,onSubmit:r,isPending:n,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(ux,{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(ux,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),r()},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(he,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(Ne,{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(he,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(or,{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(G,{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:n,children:n?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(Ha,{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(Wu,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function QDs({form:s,setForm:t,onSubmit:r,isPending:n,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=k.useState(1),[d,h]=k.useState(""),m=3,x=!!s.first_name&&!!s.email,y=v=>{h(v),t(w=>({...w,why_interested:v})),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(ux,{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(Hc,{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(ux,{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(v=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:v<=o?a:"#e5e7eb"}},v)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",m]})]}),e.jsxs(z4e,{mode:"wait",children:[o===1&&e.jsxs(Sr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(v=>e.jsxs("button",{type:"button",onClick:()=>y(v.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:v.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:v.label}),e.jsx(Ha,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},v.val))]},"step1"),o===2&&e.jsxs(Sr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"How can we reach you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"We'll text first, on your schedule."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(Ne,{required:!0,value:s.first_name,onChange:v=>t(w=>({...w,first_name:v.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(Ne,{value:s.last_name,onChange:v=>t(w=>({...w,last_name:v.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(Ne,{type:"email",required:!0,value:s.email,onChange:v=>t(w=>({...w,email:v.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(Ne,{value:s.phone,onChange:v=>t(w=>({...w,phone:v.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(G,{type:"button",disabled:!x,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(Ha,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Sr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"A few quick details (optional)"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"Helps us prepare a more personalized comp comparison."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(Ne,{value:s.current_brokerage,onChange:v=>t(w=>({...w,current_brokerage:v.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(he,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(Ne,{type:"number",min:"0",value:s.experience_years,onChange:v=>t(w=>({...w,experience_years:v.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(Ne,{value:s.annual_production,onChange:v=>t(w=>({...w,annual_production:v.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(or,{value:s.why_interested,onChange:v=>t(w=>({...w,why_interested:v.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(G,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(G,{type:"button",onClick:r,disabled:n,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:n?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(Kn,{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(Wu,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(xi,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Cn,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function JDs({config:s,primaryColor:t,accentColor:r,brokerageId:n,brokerageName:a}){const{toast:i}=Ma(),[l,o]=k.useState("250000"),[c,d]=k.useState("12"),[h,m]=k.useState("70"),[x,y]=k.useState("150"),[v,w]=k.useState(""),[b,N]=k.useState(!1),[S,T]=k.useState(!1),A=s.commission_split_pct??80,I=s.cap_amount??16e3,D=s.post_cap_split_pct??100,R=s.monthly_fee??99,$=s.transaction_fee??0,F=k.useMemo(()=>{const K=parseFloat(l)||0,X=Math.max(0,parseInt(c,10)||0),Z=parseFloat(h)||0,re=parseFloat(x)||0,le=K*(Z/100)-re*12-$*X,oe=1-A/100,ne=oe>0?I/oe:K,ie=Math.min(K,ne),ye=Math.max(0,K-ne),ce=ie*oe+ye*(1-D/100),ve=K-ce-R*12-$*X,be=ve-le;return{currentNet:le,newNet:ve,diff:be}},[l,c,h,x,A,I,D,R,$]),z=K=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(K),Q=async K=>{if(K.preventDefault(),!!v){T(!0);try{const{error:X}=await V.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:v,source:"calculator"});if(X)throw X;const{error:Z}=await V.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:n,brokerage_name:a,email:v,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(h)||0,current_monthly_fee:parseFloat(x)||0},plan:{commission_split_pct:A,cap_amount:I,post_cap_split_pct:D,monthly_fee:R,transaction_fee:$},result:F,primary_color:t,accent_color:r}});Z&&console.error("Breakdown email failed:",Z),N(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(X){i({title:"Error",description:X.message,variant:"destructive"})}finally{T(!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(ux,{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:r},children:[e.jsx(Hc,{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:r},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(ux,{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(dA,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:r},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(he,{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(Ne,{type:"number",value:l,onChange:K=>o(K.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(Ne,{type:"number",min:"0",value:c,onChange:K=>d(K.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(Ne,{type:"number",value:h,onChange:K=>m(K.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(he,{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(Ne,{type:"number",value:x,onChange:K=>y(K.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, ${r}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(bo,{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(Sr.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children: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&&!b&&e.jsxs("form",{onSubmit:Q,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(Ne,{type:"email",required:!0,value:v,onChange:K=>w(K.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(G,{type:"submit",disabled:S,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),b&&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(Kn,{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 eRs({config:s,primaryColor:t,accentColor:r,brokerageId:n}){const{toast:a}=Ma(),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,h]=k.useState(!1),[m,x]=k.useState(!1),y=async v=>{v.preventDefault(),x(!0);try{const{error:w}=await V.from("recruit_lead_magnet_downloads").insert({brokerage_id:n,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(w)throw w;h(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(w){a({title:"Error",description:w.message,variant:"destructive"})}finally{x(!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(ux,{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, ${r}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}, ${r})`},children:e.jsx(O4,{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:r},children:[e.jsx(Hc,{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:r},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(Kn,{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:y,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(Ne,{value:o,onChange:v=>c(v.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(Ne,{type:"email",required:!0,value:i,onChange:v=>l(v.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(G,{type:"submit",disabled:m,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${r})`},children:[e.jsx(O4,{className:"h-4 w-4 mr-2"}),m?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function tRs(){const{slug:s}=Ki(),{toast:t}=Ma(),[r,n]=k.useState(!1),[a,i]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});k.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(X=>document.querySelectorAll(X).forEach(Z=>Z.style.display="none"))};F();const z=[setTimeout(F,500),setTimeout(F,1500),setTimeout(F,3e3)],Q=new MutationObserver(F);return Q.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),z.forEach(clearTimeout),Q.disconnect()}},[]);const{data:l,isLoading:o,error:c}=mt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:F,error:z}=await V.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(z)throw z;return F},enabled:!!s}),{data:d}=mt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:F,error:z}=await V.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)}),h=Ct({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 V.from("recruit_interest_submissions").insert(F);if(z)throw z;V.functions.invoke("recruit-lead-notify",{body:{lead:F,brokerage_id:l.id}}).catch(Q=>console.error("Lead notification error:",Q))},onSuccess:()=>n(!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(Sa,{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 m=d,x=(m==null?void 0:m.primary_color)||"#406E71",y=(m==null?void 0:m.accent_color)||"#2a4c64",v=(m==null?void 0:m.benefits)||[],w=(m==null?void 0:m.testimonials)||[],b=(m==null?void 0:m.gallery_images)||[],N=(m==null?void 0:m.hero_headline)||`Join ${l.name}`,S=(m==null?void 0:m.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",T=(m==null?void 0:m.calculator_enabled)===!0,A=(m==null?void 0:m.calculator_config)||{},I=(m==null?void 0:m.lead_magnet_enabled)===!0,D=(m==null?void 0:m.lead_magnet_config)||{},R=(m==null?void 0:m.form_style)||"classic",$=(m==null?void 0:m.confidential_messaging)!==!1;return r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Sr.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${x}, ${y})`},children:e.jsx(Kn,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:y},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:y},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:x}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":x,"--recruit-accent":y},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:[(m==null?void 0:m.logo_url)&&e.jsx("img",{src:m.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:y},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, ${x}, ${y})`},children:["Apply Now ",e.jsx(Ha,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(WDs,{headline:N,subtext:S,primaryColor:x,accentColor:y,heroImageUrl:m==null?void 0:m.hero_image_url,logoUrl:m==null?void 0:m.logo_url,brokerageName:l.name}),e.jsx(KDs,{benefits:v,accentColor:y,primaryColor:x}),e.jsx(YDs,{images:b,primaryColor:x,accentColor:y}),e.jsx(ZDs,{testimonials:w,primaryColor:x,accentColor:y}),T&&e.jsx(JDs,{config:A,primaryColor:x,accentColor:y,brokerageId:l.id,brokerageName:l.name}),I&&e.jsx(eRs,{config:D,primaryColor:x,accentColor:y,brokerageId:l.id}),R==="multi_step"?e.jsx(QDs,{form:a,setForm:i,onSubmit:()=>h.mutate(),isPending:h.isPending,primaryColor:x,accentColor:y,showConfidentialBadges:$}):e.jsx(XDs,{form:a,setForm:i,onSubmit:()=>h.mutate(),isPending:h.isPending,primaryColor:x,accentColor:y}),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 sRs(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 rRs(){var x,y,v,w;const{shareToken:s}=Ki(),t=k.useRef(!1),{data:r,isLoading:n,error:a}=mt({queryKey:["public-recruit-video",s],queryFn:async()=>{var I;if(!s)throw new Error("No token");const{data:b,error:N}=await V.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(N)throw N;const{data:S}=await V.from("profiles").select("name, avatar_url, title").eq("id",(I=b.video)==null?void 0:I.owner_user_id).single(),{data:T}=await V.from("brokerages").select("name").eq("id",b.brokerage_id).single(),{data:A}=await V.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",b.brokerage_id).maybeSingle();return{rv:b,profile:S,brokerage:T,settings:A}},enabled:!!s});if(k.useEffect(()=>{var b;!((b=r==null?void 0:r.rv)!=null&&b.id)||t.current||(t.current=!0,V.rpc("log_recruit_video_view",{p_recruit_video_id:r.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(x=r==null?void 0:r.rv)==null?void 0:x.id]),n)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||!r)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}=r,d=(c==null?void 0:c.primary_color)||"#3b82f6",h=((y=i.prospect)==null?void 0:y.first_name)||"there",m=(v=i.video)!=null&&v.playback_url?sRs(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(nl,{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 ",h,", ",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})]}),m&&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:m,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:((w=l==null?void 0:l.name)==null?void 0:w.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]})]})]}),e.jsx("div",{className:"text-center",children:e.jsxs(G,{size:"lg",className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{V.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:[e.jsx(on,{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 nRs="relzejiswnotikjgvjhz",bVe=`https://${nRs}.supabase.co/functions/v1/recruit-unsubscribe`;function aRs(){const[s]=Ac(),t=s.get("token")||"",[r,n]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(""),[h,m]=k.useState({});k.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const y=()=>{['[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(N=>document.querySelectorAll(N).forEach(S=>S.style.display="none"))};y();const v=[setTimeout(y,500),setTimeout(y,1500),setTimeout(y,3e3)],w=new MutationObserver(y);return w.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),v.forEach(clearTimeout),w.disconnect()}},[]),k.useEffect(()=>{if(!t){m({error:"Missing unsubscribe token in link."}),n(!1);return}fetch(`${bVe}?token=${encodeURIComponent(t)}`).then(async y=>{const v=await y.json();if(!y.ok)throw new Error(v.error||"Lookup failed");m(v),v.already_unsubscribed&&o(!0)}).catch(y=>m({error:y.message||"Could not load status"})).finally(()=>n(!1))},[t]);const x=async()=>{i(!0);try{const y=await fetch(bVe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),v=await y.json();if(!y.ok)throw new Error(v.error||"Failed");o(!0)}catch(y){m({...h,error:y.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:r?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(es,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):h.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(Oi,{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:h.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(In,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",h.first_name?`, ${h.first_name}`:""]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You won't receive any more recruiting emails from ",h.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(Ey,{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(Ey,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",h.first_name?`, ${h.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",h.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),h.email&&e.jsx("p",{className:"text-xs text-slate-400",children:h.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(or,{id:"reason",value:c,onChange:y=>d(y.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(G,{onClick:x,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(es,{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."})]})})})}function iRs(){const s=br(),t=Xt(),{isAdmin:r}=js(),[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(null),{data:d,isLoading:h}=mt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:I},error:D}=await V.auth.getUser();if(D)throw D;if(!I)return[];const{data:R,error:$}=await V.from("social_accounts").select("*").eq("user_id",I.id).order("created_at",{ascending:!1});if($)throw $;return R}}),m=Ct({mutationFn:async I=>{const{data:{user:D},error:R}=await V.auth.getUser();if(R)throw R;if(!D)throw new Error("Not authenticated");const{error:$}=await V.from("social_accounts").delete().eq("id",I).eq("user_id",D.id);if($)throw $},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ue.success("Account disconnected successfully")},onError:()=>{ue.error("Failed to disconnect account")}}),x=async I=>{a(!0);try{const{data:D,error:R}=await V.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:I}});if(R)throw R;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Meta OAuth error:",D),ue.error("Failed to start connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:I,error:D}=await V.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(D)throw D;if(I!=null&&I.authUrl)window.location.href=I.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(I){console.error("LinkedIn OAuth error:",I),ue.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},v=async()=>{a(!0);try{const{data:I,error:D}=await V.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(D)throw D;if(I!=null&&I.authUrl)window.location.href=I.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(I){console.error("Google OAuth error:",I),ue.error("Failed to start Google connection. Please try again."),a(!1)}},w=(d==null?void 0:d.filter(I=>I.platform==="facebook"))||[],b=(d==null?void 0:d.filter(I=>I.platform==="instagram"))||[],N=(d==null?void 0:d.filter(I=>I.platform==="linkedin"))||[],S=(d==null?void 0:d.filter(I=>I.platform==="google_business"))||[],T=((d==null?void 0:d.length)||0)>0,A=async(I,D)=>{l(I),c(null);try{const{data:R,error:$}=await V.functions.invoke("meta-api-test",{body:{testType:"all",accountId:I}});if($)throw $;c(R.results||[]),ue.success(R.summary||"API tests completed")}catch(R){console.error("Meta API test error:",R),ue.error("Failed to run API tests")}finally{l(null)}};return e.jsx(ws,{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(Ge,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(jr,{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(G,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Social Swag"]}),T&&e.jsx(ke,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Pe,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(di,{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(ke,{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(yu,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Facebook"}),e.jsx(Nr,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Mi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length>0?e.jsx("div",{className:"space-y-3",children:w.map(I=>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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:I.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(yu,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:I.page_name||I.platform_username||"Facebook Page"}),e.jsx(Ge,{variant:I.is_active?"default":"secondary",className:"text-xs",children:I.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Facebook?"}),e.jsx(Bo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>m.mutate(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},I.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(G,{onClick:()=>x("facebook"),disabled:n,className:"w-full gap-2",variant:w.length>0?"outline":"default",children:[n?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4"}),w.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(ke,{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(Jd,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Instagram"}),e.jsx(Nr,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Mi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(I=>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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:I.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Jd,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",I.platform_username||"Instagram Account"]}),e.jsx(Ge,{variant:I.is_active?"default":"secondary",className:"text-xs",children:I.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Instagram?"}),e.jsx(Bo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>m.mutate(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},I.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(G,{onClick:()=>x("instagram"),disabled:n,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[n?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4"}),b.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(ke,{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(Jh,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"LinkedIn"}),e.jsx(Nr,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Mi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):N.length>0?e.jsx("div",{className:"space-y-3",children:N.map(I=>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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:I.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Jh,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:I.platform_username||"LinkedIn Account"}),e.jsx(Ge,{variant:I.is_active?"default":"secondary",className:"text-xs",children:I.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect LinkedIn?"}),e.jsx(Bo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>m.mutate(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},I.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(G,{onClick:y,disabled:n,className:"w-full gap-2",variant:N.length>0?"outline":"default",children:[n?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4"}),N.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(ke,{className:`relative overflow-hidden ${r?"":"opacity-75"}`,children:[!r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Ge,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),r&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Ge,{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(Ca,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Google Business"}),e.jsx(Nr,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Pe,{className:"space-y-4",children:[h?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Mi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length>0?e.jsx("div",{className:"space-y-3",children:S.map(I=>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(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:I.profile_picture_url||""}),e.jsx(kn,{children:e.jsx(Ca,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:I.page_name||I.platform_username||"Google Business"}),e.jsx(Ge,{variant:I.is_active?"default":"secondary",className:"text-xs",children:I.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ko,{children:[e.jsx(vm,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})}),e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Disconnect Google Business?"}),e.jsx(Bo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>m.mutate(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},I.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:r?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(G,{onClick:r?v:void 0,disabled:!r||n,className:"w-full gap-2",variant:S.length>0?"outline":"default",children:[n?e.jsx(Mi,{className:"h-4 w-4 animate-spin"}):e.jsx($s,{className:"h-4 w-4"}),S.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"})]})]})]}),r&&(w.length>0||b.length>0)&&e.jsxs(ke,{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(Xw,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Nr,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Pe,{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:[w.map(I=>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(yu,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:I.page_name||"Facebook Page"})]}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>A(I.id),disabled:i===I.id,children:i===I.id?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xw,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${I.id}`)),b.map(I=>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(Jd,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",I.platform_username||"Instagram"]})]}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>A(I.id),disabled:i===I.id,children:i===I.id?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xw,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${I.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((I,D)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[I.status==="success"?e.jsx(In,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):I.status==="pending"?e.jsx(es,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Sc,{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:I.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:I.details})]})]},D))})]}),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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-lg",children:"How it works"})}),e.jsx(Pe,{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 oRs(){const[s]=Ac(),t=br(),[r,n]=k.useState("loading"),[a,i]=k.useState("Processing your connection...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:x,error:y}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:h,callbackPath:"/social-connections/callback"}});if(y)throw y;if(x!=null&&x.success)n("success"),i(`Successfully connected ${((m=x.accounts)==null?void 0:m.length)||0} account(s)!`),ue.success("Social accounts connected successfully!");else throw new Error((x==null?void 0:x.error)||"Unknown error")}catch(x){console.error("OAuth callback error:",x),n("error"),i(x instanceof Error?x.message:"Failed to connect accounts"),ue.error("Failed to connect: "+(x instanceof Error?x.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[r==="loading"&&e.jsx(es,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(di,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Sc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/mission-control/integrations"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function lRs(){const[s]=Ac(),t=br(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your Google Business Profile...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),h=s.get("state");if(c){n("error"),i(d||"Authorization was denied"),ue.error("Connection failed: "+(d||c));return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:m,error:x}=await V.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:h}});if(x)throw x;if(m!=null&&m.success)n("success"),i(m.message||"Successfully connected Google Business Profile!"),ue.success("Google Business Profile connected!");else throw new Error((m==null?void 0:m.error)||"Unknown error")}catch(m){console.error("Google OAuth callback error:",m),n("error"),i(m instanceof Error?m.message:"Failed to connect Google Business Profile"),ue.error("Failed to connect: "+(m instanceof Error?m.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(ke,{className:"w-full max-w-md",children:[e.jsxs(Mt,{className:"text-center",children:[r==="loading"&&e.jsx(es,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),r==="success"&&e.jsx(di,{className:"h-12 w-12 mx-auto text-green-500"}),r==="error"&&e.jsx(Sc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Dt,{className:"mt-4",children:[r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:r!=="loading"&&e.jsx(G,{onClick:()=>t("/social-connections"),children:r==="success"?"View Connected Accounts":"Try Again"})})]})})}function cRs(){const[s]=Ac(),t=br(),[r,n]=k.useState("loading"),[a,i]=k.useState("Connecting your LinkedIn account...");return k.useEffect(()=>{(async()=>{var m;const o=s.get("code"),c=s.get("state"),d=s.get("error"),h=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,h),n("error"),i(h||"Failed to connect LinkedIn account"),ue.error(h||"Failed to connect LinkedIn");return}if(!o){n("error"),i("No authorization code received"),ue.error("No authorization code received");return}try{const{data:x,error:y}=await V.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(y)throw y;if(x!=null&&x.success)n("success"),i(`Successfully connected ${((m=x.accounts)==null?void 0:m.length)||1} LinkedIn account`),ue.success("LinkedIn connected successfully!");else throw new Error((x==null?void 0:x.error)||"Failed to connect LinkedIn account")}catch(x){console.error("LinkedIn callback error:",x),n("error"),i(x instanceof Error?x.message:"Failed to connect LinkedIn account"),ue.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(ke,{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:[r==="loading"&&e.jsx(es,{className:"h-8 w-8 animate-spin text-blue-600"}),r==="success"&&e.jsx(di,{className:"h-8 w-8 text-green-600"}),r==="error"&&e.jsx(Sc,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Dt,{className:"flex items-center justify-center gap-2",children:[e.jsx(Jh,{className:"h-5 w-5 text-blue-600"}),r==="loading"&&"Connecting...",r==="success"&&"Connected!",r==="error"&&"Connection Failed"]}),e.jsx(Nr,{children:a})]}),e.jsx(Pe,{className:"flex justify-center",children:e.jsx(G,{onClick:()=>t("/mission-control/integrations"),disabled:r==="loading",children:r==="success"?"View Integrations":"Back to Integrations"})})]})})}function dRs(){const s=br(),[t,r]=k.useState(null),{data:n,isLoading:a}=Opt(t||void 0,!0),{data:i,isLoading:l}=UEe(!0),{cartItems:o}=Bfe(),c=o.reduce((h,m)=>h+m.quantity,0),d=h=>{s(`/marketplace/${h.id}`)};return a||l?e.jsx(ws,{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(h=>e.jsx(Fs,{className:"h-10 w-24 flex-shrink-0"},h))}),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(h=>e.jsx(Fs,{className:"h-72 w-full"},h))})]})}):e.jsx(ws,{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(G,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(Hf,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Ge,{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(G,{variant:t===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),i.map(h=>e.jsx(G,{variant:t===h.id?"default":"outline",size:"sm",onClick:()=>r(h.id),children:h.name},h.id))]}),n&&n.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(h=>{var m;return e.jsxs(ke,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(h),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[h.images&&h.images.length>0?e.jsx("img",{src:((m=h.images.find(x=>x.is_primary))==null?void 0:m.image_url)||h.images[0].image_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Il,{className:"h-12 w-12 text-muted-foreground"})}),h.category&&e.jsx(Ge,{className:"absolute top-2 left-2",variant:"secondary",children:h.category.name})]}),e.jsxs(Pe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:h.name}),h.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:h.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(h.base_price).toFixed(2)]}),h.variants&&h.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.variants.length," options"]})]})]})]},h.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Il,{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 Nxt=k.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Nxt.displayName="Breadcrumb";const kxt=k.forwardRef(({className:s,...t},r)=>e.jsx("ol",{ref:r,className:It("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));kxt.displayName="BreadcrumbList";const Tce=k.forwardRef(({className:s,...t},r)=>e.jsx("li",{ref:r,className:It("inline-flex items-center gap-1.5",s),...t}));Tce.displayName="BreadcrumbItem";const Oke=k.forwardRef(({asChild:s,className:t,...r},n)=>{const a=s?sCe:"a";return e.jsx(a,{ref:n,className:It("transition-colors hover:text-foreground",t),...r})});Oke.displayName="BreadcrumbLink";const Sxt=k.forwardRef(({className:s,...t},r)=>e.jsx("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:It("font-normal text-foreground",s),...t}));Sxt.displayName="BreadcrumbPage";const Fke=({children:s,className:t,...r})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:It("[&>svg]:size-3.5",t),...r,children:s??e.jsx(va,{})});Fke.displayName="BreadcrumbSeparator";function uRs(){var X,Z;const{productId:s}=Ki(),t=br(),{data:r,isLoading:n}=oPs(s||""),{addToCart:a,cartItems:i}=Bfe(),[l,o]=k.useState(null),[c,d]=k.useState(1),[h,m]=k.useState(0),[x,y]=k.useState(null),[v,w]=k.useState(!1),[b,N]=k.useState(!1),S=(X=r==null?void 0:r.variants)==null?void 0:X.find(re=>re.id===l),T=((Z=r==null?void 0:r.variants)==null?void 0:Z.filter(re=>re.is_active))||[],A=Number((r==null?void 0:r.base_price)||0),I=S?Number(S.price_adjustment):0,D=A+I,R=Number((r==null?void 0:r.shipping_fee)||0),$=i.reduce((re,le)=>re+le.quantity,0),F=async re=>{if(!re.target.files||re.target.files.length===0)return;w(!0);const le=re.target.files[0],oe=le.name.split(".").pop(),ne=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${oe}`;try{const{error:ie}=await V.storage.from("marketplace").upload(ne,le);if(ie)throw ie;const{data:{publicUrl:ye}}=V.storage.from("marketplace").getPublicUrl(ne);y(ye),ue.success("Artwork uploaded successfully")}catch(ie){ue.error("Failed to upload artwork: "+ie.message)}finally{w(!1)}},z=()=>{if(r){if(T.length>0&&!l){ue.error("Please select an option");return}a(r,S||void 0,c,x||void 0),N(!0),ue.success("Added to cart!"),setTimeout(()=>N(!1),2e3)}},Q=()=>{r!=null&&r.images&&m(re=>(re+1)%r.images.length)},K=()=>{r!=null&&r.images&&m(re=>(re-1+r.images.length)%r.images.length)};return n?e.jsx(ws,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(Fs,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fs,{className:"h-8 w-3/4"}),e.jsx(Fs,{className:"h-6 w-1/4"}),e.jsx(Fs,{className:"h-24 w-full"}),e.jsx(Fs,{className:"h-12 w-full"})]})]})}):r?e.jsxs(ws,{title:r.name,children:[e.jsx(Nxt,{className:"mb-6",children:e.jsxs(kxt,{children:[e.jsx(Tce,{children:e.jsx(Oke,{asChild:!0,children:e.jsx(Yn,{to:"/marketplace",children:"Marketplace"})})}),r.category&&e.jsxs(e.Fragment,{children:[e.jsx(Fke,{}),e.jsx(Tce,{children:e.jsx(Oke,{asChild:!0,children:e.jsx(Yn,{to:`/marketplace?category=${r.category.id}`,children:r.category.name})})})]}),e.jsx(Fke,{}),e.jsx(Tce,{children:e.jsx(Sxt,{children:r.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:r.images&&r.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:r.images[h].image_url,alt:r.name,className:"max-w-full max-h-full object-contain"}),r.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(G,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:K,children:e.jsx($o,{className:"h-6 w-6"})}),e.jsx(G,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:Q,children:e.jsx(va,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Il,{className:"h-24 w-24 text-muted-foreground"})})}),r.images&&r.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:r.images.map((re,le)=>e.jsx("button",{onClick:()=>m(le),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${le===h?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:re.image_url,alt:"",className:"w-full h-full object-cover"})},re.id))}),r.video&&e.jsx(ke,{children:e.jsxs(Pe,{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:r.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[r.category&&e.jsx(Ge,{variant:"secondary",className:"mb-2",children:r.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:r.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",D.toFixed(2)]}),R>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",R.toFixed(2)," shipping"]})]})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})}),T.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(re=>e.jsxs(G,{variant:l===re.id?"default":"outline",onClick:()=>o(re.id),children:[re.name,Number(re.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(re.price_adjustment)>0?"+":"","$",Number(re.price_adjustment).toFixed(2),")"]})]},re.id))})]}),r.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Upload Your Artwork (Optional)"}),x?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:x,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(G,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>y(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:v}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(da,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:v?"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(he,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(G,{variant:"outline",size:"icon",onClick:()=>d(re=>Math.max(1,re-1)),children:"-"}),e.jsx(Ne,{type:"number",value:c,onChange:re=>d(Math.max(1,parseInt(re.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(G,{variant:"outline",size:"icon",onClick:()=>d(re=>re+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(G,{size:"lg",className:"flex-1",onClick:z,disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(Kn,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hf,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(G,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(Hf,{className:"h-5 w-5"}),$>0&&e.jsx(Ge,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:$})]})]}),r.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(ws,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Il,{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(G,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function hRs(){const s=br(),{cartItems:t,removeFromCart:r,updateQuantity:n,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=Bfe(),[d,h]=k.useState(!1),[m,x]=k.useState(""),y=async()=>{if(t.length===0){ue.error("Your cart is empty");return}h(!0);try{const{data:v,error:w}=await V.functions.invoke("marketplace-checkout",{body:{items:t.map(b=>{var N;return{product_id:b.product.id,variant_id:((N=b.variant)==null?void 0:N.id)||null,quantity:b.quantity,artwork_url:b.artworkUrl||null}}),notes:m.trim()||null}});if(w)throw w;if(v!=null&&v.url)c(),window.open(v.url,"_blank");else throw new Error("No checkout URL received")}catch(v){ue.error("Checkout failed: "+v.message)}finally{h(!1)}};return t.length===0?e.jsx(ws,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(dv,{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(G,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(ws,{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(v=>{var w,b;return e.jsx(ke,{children:e.jsx(Pe,{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:v.product.images&&v.product.images.length>0?e.jsx("img",{src:((w=v.product.images.find(N=>N.is_primary))==null?void 0:w.image_url)||v.product.images[0].image_url,alt:v.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(dv,{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:v.product.name}),v.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:v.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(v).toFixed(2),Number(v.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(v.product.shipping_fee).toFixed(2)," shipping"]})]}),v.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(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var N;return r(v.product.id,(N=v.variant)==null?void 0:N.id)},children:e.jsx(yr,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var N;return n(v.product.id,(N=v.variant)==null?void 0:N.id,v.quantity-1)},disabled:v.quantity<=1,children:e.jsx(av,{className:"h-3 w-3"})}),e.jsx(Ne,{type:"number",value:v.quantity,onChange:N=>{var S;return n(v.product.id,(S=v.variant)==null?void 0:S.id,parseInt(N.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(G,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var N;return n(v.product.id,(N=v.variant)==null?void 0:N.id,v.quantity+1)},children:e.jsx($s,{className:"h-3 w-3"})})]})]})]})})},`${v.product.id}-${((b=v.variant)==null?void 0:b.id)||"base"}`)}),e.jsx(G,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(ke,{className:"sticky top-4",children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Order Summary"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((v,w)=>v+w.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(fo,{}),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(fo,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(or,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:m,onChange:v=>x(v.target.value),rows:3,className:"resize-none"})]}),e.jsx(G,{className:"w-full",size:"lg",onClick:y,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Ha,{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 mRs(){const s=br(),{data:t,isLoading:r}=yPs();return r?e.jsx(ws,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(n=>e.jsx(Fs,{className:"h-32 w-full"},n))})}):!t||t.length===0?e.jsx(ws,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Il,{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(G,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(ws,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(n=>{var a,i,l;return e.jsx(ke,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${n.id}`),children:e.jsxs(Pe,{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:n.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:_s(new Date(n.created_at),"MMM d, yyyy")})]}),e.jsx(Ge,{className:$Ee[n.status],children:ZA[n.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=n.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)),n.items&&n.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:["+",n.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=n.items)==null?void 0:i.length)===1?n.items[0].product_name:`${(l=n.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(n.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n.tracking_url&&e.jsxs(G,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(n.tracking_url,"_blank")},children:[e.jsx(Qr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(va,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},n.id)})})})}const _Ve=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function fRs({currentStatus:s,statusHistory:t}){const r=_Ve.indexOf(s);return e.jsx("div",{className:"space-y-3",children:_Ve.map((n,a)=>{const i=t==null?void 0:t.find(d=>d.status===n),l=ar;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(In,{className:"h-4 w-4"}):o?e.jsx(fn,{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:ZA[n]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_s(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},n)})})}function pRs(){var N;const{orderId:s}=Ki(),t=br(),{data:r,isLoading:n,refetch:a}=vPs(s||""),i=wPs(),l=jPs(),[o,c]=k.useState(!1),[d,h]=k.useState(null),[m,x]=k.useState(""),[y,v]=k.useState(null),w=async S=>{v(S);try{await i.mutateAsync({orderId:s,itemId:S}),ue.success("Proof approved!"),a()}catch{ue.error("Failed to approve proof")}finally{v(null)}},b=async()=>{if(d){v(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:m}),ue.success("Revision requested"),c(!1),x(""),h(null),a()}catch{ue.error("Failed to request revision")}finally{v(null)}}};return n?e.jsx(ws,{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(Fs,{className:"h-64 w-full"}),e.jsx(Fs,{className:"h-48 w-full"})]}),e.jsx(Fs,{className:"h-96 w-full"})]})}):r?e.jsxs(ws,{title:`Order ${r.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(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Dt,{children:"Order Status"}),e.jsx(Ge,{className:$Ee[r.status],children:ZA[r.status]})]}),e.jsx(Pe,{children:e.jsx(fRs,{currentStatus:r.status,statusHistory:r.status_history})})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Items"})}),e.jsx(Pe,{className:"space-y-4",children:(N=r.items)==null?void 0:N.map(S=>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:S.product_name}),S.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:S.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",S.quantity," × $",Number(S.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(S.unit_price)*S.quantity).toFixed(2)]})]}),S.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:S.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(hb,{className:"h-4 w-4"}),"View Artwork",e.jsx(Qr,{className:"h-3 w-3"})]})]}),S.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:S.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(hb,{className:"h-4 w-4"}),"View Proof",e.jsx(Qr,{className:"h-3 w-3"})]}),S.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(G,{size:"sm",onClick:()=>w(S.id),disabled:y===S.id,children:[y===S.id?e.jsx(es,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(jh,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{h(S.id),c(!0)},disabled:y===S.id,children:[e.jsx(VR,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),S.proof_status==="approved"&&e.jsxs(Ge,{className:"bg-green-100 text-green-800",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),S.proof_status==="rejected"&&S.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Ge,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.proof_notes})]})]})]},S.id))})]}),r.shipping_name&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(GR,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Pe,{children:[e.jsx("p",{className:"font-medium",children:r.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[r.shipping_address,e.jsx("br",{}),r.shipping_city,", ",r.shipping_state," ",r.shipping_zip]}),r.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:r.tracking_number}),r.tracking_url&&e.jsxs(G,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(r.tracking_url,"_blank"),children:["Track Package",e.jsx(Qr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(ke,{className:"sticky top-4",children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Order Summary"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",_s(new Date(r.created_at),"MMMM d, yyyy")]}),e.jsx(fo,{}),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(r.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(r.shipping_total).toFixed(2)]})]})]}),e.jsx(fo,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(r.total).toFixed(2)]})]}),r.notes&&e.jsxs(e.Fragment,{children:[e.jsx(fo,{}),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:r.notes})]})]})]})]})})]}),e.jsx(fs,{open:o,onOpenChange:c,children:e.jsxs(ms,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Request Changes"}),e.jsx(Hr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(or,{placeholder:"Describe the changes needed...",value:m,onChange:S=>x(S.target.value),rows:4}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(G,{onClick:b,disabled:!m.trim()||y!==null,children:[y?e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(ws,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Il,{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(G,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function xRs(){const s=br(),[t]=Ac();return t.get("session_id"),k.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(ws,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(ke,{children:e.jsxs(Pe,{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(In,{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(Il,{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(G,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(Ha,{className:"h-4 w-4 ml-2"})]}),e.jsx(G,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function gRs(){const{user:s}=js(),[t,r]=k.useState("store"),[n,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,h]=k.useState(5),[m,x]=k.useState(""),[y,v]=k.useState(!1),[w,b]=k.useState(!1),[N,S]=k.useState(""),[T,A]=k.useState(null),[I,D]=k.useState(!1),{hasSubmittedReview:R,submitReview:$,markPostedToGoogle:F}=jrt(),{data:z}=Bpt(),{data:Q,isLoading:K}=Fpt(),{data:X,isLoading:Z}=APs(n),{data:re,isLoading:le}=MPs(s==null?void 0:s.id),{data:oe=0}=LPs(s==null?void 0:s.id),ne=PPs(),ie=new Set((re==null?void 0:re.map(De=>De.item_id))||[]),ye=async()=>{if(i)try{const De=await ne.mutateAsync(i.id);i.item_type==="reelflow_credits"?ue.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ue.success(`Successfully purchased "${i.name}"!`),l(null)}catch(De){ue.error(De.message||"Failed to purchase item")}},ce=async()=>{if(!m.trim()){ue.error("Please write a review");return}v(!0);const De=await $(d,m);v(!1),De.success?(ue.success("Thank you for your review! You earned 25 points!"),S(m),b(!0),x(""),h(5)):ue.error(De.error||"Failed to submit review")},ve=()=>{navigator.clipboard.writeText(N),ue.success("Review copied to clipboard!")},be=()=>{F(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},Ue=()=>{b(!1),c(!1),S("")};return K||Z||le?e.jsx(ws,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fs,{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(De=>e.jsx(Fs,{className:"h-64"},De))})]})}):e.jsxs(ws,{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(ke,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Pe,{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(Xn,{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:oe.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(Gi,{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(mc,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(Gp,{open:I,onOpenChange:D,children:e.jsxs(ke,{className:"border-primary/20",children:[e.jsx(Wp,{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(Gi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Dt,{className:"text-base",children:"How to Earn Points"}),e.jsx(Nr,{children:"See all the ways you can earn spendable points"})]})]}),I?e.jsx(Jf,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Wi,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(Kp,{children:e.jsx(Pe,{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(De=>De.is_active).map(De=>{const Ae=He=>{switch(He){case"event_attendance":return e.jsx(on,{className:"h-5 w-5"});case"leave_review":return e.jsx(Xn,{className:"h-5 w-5"});case"add_listing":return e.jsx(En,{className:"h-5 w-5"});case"first_contact":return e.jsx(pr,{className:"h-5 w-5"});case"first_video":return e.jsx(Jr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(xi,{className:"h-5 w-5"});default:return e.jsx(ii,{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(De.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:De.action_name}),De.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:De.description})]}),e.jsxs(Ge,{variant:"secondary",className:"font-bold shrink-0",children:["+",De.points]})]},De.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(mc,{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(Ge,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!R&&e.jsx(ke,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Pe,{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(xi,{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(G,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Xn,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(On,{value:t,onValueChange:r,children:[e.jsxs(Rn,{children:[e.jsxs(Kt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(dv,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Kt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Il,{className:"h-4 w-4"}),"My Rewards",re&&re.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1",children:re.length})]})]}),e.jsxs(ts,{value:"store",className:"mt-6",children:[Q&&Q.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(G,{variant:n===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),Q.map(De=>e.jsxs(G,{variant:n===De.id?"default":"outline",size:"sm",onClick:()=>a(De.id),children:[De.icon&&`${De.icon} `,De.name]},De.id))]}),!X||X.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ii,{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:X.map(De=>{const Ae=De.item_type==="reelflow_credits",He=!Ae&&ie.has(De.id),Le=!Ae&&De.max_quantity!==null&&De.current_quantity===0,Ie=oe>=De.points_cost;return e.jsxs(ke,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${He?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(De),children:[De.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:De.preview_image_url,alt:De.name,className:"w-full h-full object-cover"}),He&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(In,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Le&&!He&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Ge,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(ii,{className:"h-12 w-12 text-muted-foreground/50"}),He&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ge,{className:"bg-green-500 text-white",children:[e.jsx(In,{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(Dt,{className:"text-lg",children:De.name}),e.jsxs(Ge,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),De.points_cost]})]}),De.category&&e.jsxs(Ge,{variant:"outline",className:"w-fit",children:[De.category.icon&&`${De.category.icon} `,De.category.name]})]}),e.jsxs(Pe,{children:[e.jsx(Nr,{className:"mb-4 line-clamp-2",children:De.description||"No description available"}),De.max_quantity!==null&&!He&&!Ae&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[De.current_quantity," of ",De.max_quantity," remaining"]}),Ae&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",De.max_quantity," ReelFlow credits per purchase"]}),He?e.jsx(G,{className:"w-full",onClick:Te=>{Te.stopPropagation(),De.file_url&&Ebe(De.file_url,De.name)},disabled:!De.file_url,children:De.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(G,{className:"w-full",onClick:Te=>{Te.stopPropagation(),l(De)},disabled:Le||!Ie,children:Le?"Sold Out":Ie?e.jsxs(e.Fragment,{children:[e.jsx(dv,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${De.points_cost-oe} more pts`})]})]},De.id)})})]}),e.jsx(ts,{value:"my-rewards",className:"mt-6",children:!re||re.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Il,{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:re.map(De=>{var Ae,He,Le,Ie,Te,xe,et;return e.jsxs(ke,{className:"overflow-hidden",children:[(Ae=De.item)!=null&&Ae.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:De.item.preview_image_url,alt:((He=De.item)==null?void 0:He.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(ii,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Mt,{className:"pb-2",children:[e.jsx(Dt,{className:"text-lg",children:((Le=De.item)==null?void 0:Le.name)||"Unknown Item"}),e.jsxs(Nr,{className:"text-xs",children:["Purchased for ",De.points_spent," points • ",new Date(De.purchased_at).toLocaleDateString()]})]}),e.jsx(Pe,{children:((Ie=De.item)==null?void 0:Ie.item_type)==="reelflow_credits"?e.jsxs(G,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(In,{className:"h-4 w-4 mr-2 text-green-500"}),(Te=De.item)==null?void 0:Te.max_quantity," Credits Applied"]}):e.jsx(G,{className:"w-full",onClick:()=>{var fe,it;(fe=De.item)!=null&&fe.file_url&&Ebe(De.item.file_url,(it=De.item)==null?void 0:it.name)},disabled:!((xe=De.item)!=null&&xe.file_url),children:((et=De.item)==null?void 0:et.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},De.id)})})})]})]}),e.jsx(Ko,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Confirm Purchase"}),e.jsxs(Bo,{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:[oe," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[oe-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:ye,disabled:ne.isPending,children:ne.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(fs,{open:o,onOpenChange:De=>{!De&&w?Ue():c(De)},children:e.jsx(ms,{children:w?e.jsxs(e.Fragment,{children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(In,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Hr,{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:['"',N,'"']})]}),e.jsxs(G,{variant:"outline",className:"w-full",onClick:ve,children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(an,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(G,{variant:"outline",onClick:Ue,children:"Maybe Later"}),e.jsxs(G,{onClick:be,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Leave a Review"}),e.jsx(Hr,{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(De=>e.jsx("button",{type:"button",onClick:()=>h(De),className:"focus:outline-none",children:e.jsx(Xn,{className:`h-8 w-8 transition-colors ${d>=De?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},De))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(or,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:m,onChange:De=>x(De.target.value),rows:4})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(G,{onClick:ce,disabled:y,className:"bg-yellow-600 hover:bg-yellow-700",children:y?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(fs,{open:!!T,onOpenChange:()=>A(null),children:e.jsxs(ms,{className:"max-w-lg",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[T==null?void 0:T.name,e.jsxs(Ge,{variant:"secondary",className:"font-bold",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),T==null?void 0:T.points_cost]})]}),(T==null?void 0:T.category)&&e.jsxs(Ge,{variant:"outline",className:"w-fit",children:[T.category.icon&&`${T.category.icon} `,T.category.name]})]}),(T==null?void 0:T.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:T.preview_image_url,alt:T.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(T==null?void 0:T.description)||"No description available"}),(T==null?void 0:T.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",T==null?void 0:T.max_quantity," ReelFlow credits per purchase"]}),(T==null?void 0:T.item_type)!=="reelflow_credits"&&(T==null?void 0:T.max_quantity)!==null&&!ie.has((T==null?void 0:T.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[T==null?void 0:T.current_quantity," of ",T==null?void 0:T.max_quantity," remaining"]})]}),e.jsx(an,{children:T&&T.item_type!=="reelflow_credits"&&ie.has(T.id)?e.jsx(G,{className:"w-full",onClick:()=>{T.file_url&&Ebe(T.file_url,T.name)},disabled:!T.file_url,children:T.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Access"]})}):T&&e.jsx(G,{className:"w-full",onClick:()=>{A(null),l(T)},disabled:T.item_type!=="reelflow_credits"&&T.max_quantity!==null&&T.current_quantity===0||oe{s&&le()},[s==null?void 0:s.id]);const le=async()=>{if(!s)return;o(!0),N(!1),w(!0);const{data:Te}=await V.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Te==null||Te.forEach(it=>{it.action_key==="referral_signup"&&m(it.points),it.action_key==="referral_paid"&&y(it.points)});const{data:xe}=await V.from("profiles").select("name").eq("id",s.id).maybeSingle();xe!=null&&xe.name&&T(xe.name);let{data:et}=await V.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!et){const{data:it}=await V.rpc("generate_agent_referral_code",{_user_id:s.id}),Oe=it||`agent${s.id.slice(0,6)}`,{data:Ye,error:We}=await V.from("agent_referral_codes").insert({user_id:s.id,code:Oe}).select("code").maybeSingle();!We&&Ye&&(et=Ye)}i((et==null?void 0:et.code)??null);const{data:fe}=await V.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(fe&&fe.length>0){const it=fe.map(We=>We.referred_user_id),{data:Oe}=await V.from("profiles").select("id, name, email").in("id",it),Ye=new Map((Oe==null?void 0:Oe.map(We=>[We.id,We]))??[]);d(fe.map(We=>({...We,referred_profile:Ye.get(We.referred_user_id)??null})))}else d([]);o(!1)},oe=k.useMemo(()=>a?`${yRs}/trial?ref=${a}`:"",[a]),ne=c.length,ie=c.filter(Te=>Te.status==="qualified").length,ye=c.filter(Te=>Te.signup_points_awarded).length*h+c.filter(Te=>Te.paid_points_awarded).length*x,ce=async()=>{oe&&(await navigator.clipboard.writeText(oe),ue.success("Referral link copied!"))},ve=()=>{const Te=encodeURIComponent("Join me on LevelUp"),xe=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: ${oe} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Te}&body=${xe}`},be=()=>{const Te=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${oe}`);window.location.href=`sms:?&body=${Te}`},Ue=async()=>{if(navigator.share&&oe)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:oe})}catch{}else ce()},Be=Te=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Te.trim()),De=Te=>{const xe=(Te??D).trim().replace(/,$/,"");if(!xe)return;const et=xe.split(/[\s,;]+/).filter(Boolean),fe=[...$];let it=0;for(const Oe of et){if(!Be(Oe)){ue.error(`Invalid email: ${Oe}`);continue}fe.includes(Oe)||(fe.push(Oe),it++)}F(fe),it>0&&R("")},Ae=Te=>F($.filter(xe=>xe!==Te)),He=()=>{X(`${S?S.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),Q("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."),I(!0)},Le=Te=>{const xe=Te.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),et=S||"A fellow agent",fe="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",it=oe;return`
LevelUp
You're Invited

${et} thinks you'd love LevelUp 🎉

${xe}

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 ${et} via LevelUp · relevelup.com

`.trim()},Ie=async()=>{if($.length===0&&(D.trim()&&De(),$.length===0)){ue.error("Add at least one recipient");return}if(!K.trim()){ue.error("Subject is required");return}re(!0);const Te=Le(z);let xe=0,et=0;for(const fe of $)try{const{data:it,error:Oe}=await V.functions.invoke("gmail-send",{body:{to:fe,subject:K,body:Te,source:"referral_invite"}});if(Oe||it!=null&&it.error)throw new Error((Oe==null?void 0:Oe.message)||(it==null?void 0:it.error));xe++}catch(it){console.error("Gmail send failed for",fe,it),et++}re(!1),xe>0?(ue.success(`Invite sent to ${xe} ${xe===1?"person":"people"}`+(et>0?` (${et} failed)`:"")),F([]),R(""),I(!1)):ue.error("Failed to send invites")};return!b&&!v?e.jsx(ws,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(nl,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(ke,{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(Hc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Dt,{children:"Refer & Earn is for active members"}),e.jsx(Nr,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Pe,{className:"flex justify-center",children:e.jsx(G,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(ws,{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(nl,{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(ii,{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:[h," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[x," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(pr,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ne}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(In,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ie}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(ke,{children:e.jsxs(Pe,{className:"p-4 flex items-center gap-3",children:[e.jsx(Gi,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ye.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Nr,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(Ne,{readOnly:!0,value:l?"Loading…":oe,className:"font-mono text-sm",onFocus:Te=>Te.currentTarget.select()}),e.jsxs(G,{onClick:ce,disabled:!oe,children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[r&&e.jsxs(G,{size:"sm",onClick:He,disabled:!oe,className:"bg-primary hover:bg-primary/90",children:[e.jsx(en,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:ve,disabled:!oe,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:be,disabled:!oe,children:[e.jsx(xi,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:Ue,disabled:!oe,children:[e.jsx(Ec,{className:"h-4 w-4 mr-2"})," More…"]})]}),!r&&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(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Your Referrals"}),e.jsx(Nr,{children:"Track who joined and when they upgrade."})]}),e.jsx(Pe,{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(pr,{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(Te=>{var fe,it;const xe=((fe=Te.referred_profile)==null?void 0:fe.name)||((it=Te.referred_profile)==null?void 0:it.email)||"New agent",et=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Te.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:xe}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",et]})]}),Te.status==="qualified"?e.jsxs(Ge,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(In,{className:"h-3 w-3 mr-1"})," Paid · +",h+x," pts"]}):e.jsxs(Ge,{variant:"secondary",children:[e.jsx(fn,{className:"h-3 w-3 mr-1"})," Signed up · +",h," pts"]})]},Te.id)})})})]}),e.jsx(ke,{className:"bg-muted/30",children:e.jsxs(Pe,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(jr,{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:[h," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[x," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(fo,{className:"opacity-0"})]}),e.jsx(fs,{open:A,onOpenChange:I,children:e.jsxs(ms,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Hr,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:n}),". 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(he,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[$.map(Te=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pr-1",children:[Te,e.jsx("button",{type:"button",onClick:()=>Ae(Te),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Te}`,children:e.jsx(vr,{className:"h-3 w-3"})})]},Te)),e.jsx("input",{type:"email",value:D,onChange:Te=>R(Te.target.value),onKeyDown:Te=>{Te.key==="Enter"||Te.key===","||Te.key===" "?(Te.preventDefault(),De()):Te.key==="Backspace"&&!D&&$.length>0&&F($.slice(0,-1))},onBlur:()=>D.trim()&&De(),onPaste:Te=>{const xe=Te.clipboardData.getData("text");/[\s,;]/.test(xe)&&(Te.preventDefault(),De(xe))},placeholder:$.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(he,{htmlFor:"email-subject",children:"Subject"}),e.jsx(Ne,{id:"email-subject",value:K,onChange:Te=>X(Te.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(or,{id:"personal-note",value:z,onChange:Te=>Q(Te.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(he,{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: ",n]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",K||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Le(z),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>I(!1),disabled:Z,children:"Cancel"}),e.jsxs(G,{onClick:Ie,disabled:Z,children:[e.jsx(en,{className:"h-4 w-4 mr-2"}),Z?"Sending…":`Send${$.length>0?` to ${$.length}`:""}`]})]})]})})]})}const Cxt=()=>{const{user:s}=js(),t=Xt(),r=mt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:h}=await V.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(h)throw h;return d||[]},enabled:!!s}),n=mt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:h}=await V.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(h)throw h;return d||[]},enabled:!!s}),a=Ct({mutationFn:async d=>{const{data:h,error:m}=await V.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=Ct({mutationFn:async({id:d,...h})=>{const{data:m,error:x}=await V.from("smart_presentations").update(h).eq("id",d).select().single();if(x)throw x;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=Ct({mutationFn:async d=>{const{data:h,error:m}=await V.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ue.success("Presentation published!")}}),o=Ct({mutationFn:async d=>{const{error:h}=await V.from("smart_presentations").update({status:"archived"}).eq("id",d);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ue.success("Presentation archived")}}),c=Ct({mutationFn:async d=>{const{error:h}=await V.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(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ue.success("Saved as template!")}});return{presentations:r.data||[],templates:n.data||[],isLoading:r.isLoading,templatesLoading:n.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},bRs=()=>{const s=br(),{presentations:t,isLoading:r,archivePresentation:n,saveAsTemplate:a}=Cxt(),i=o=>o.status==="draft"?e.jsx(Ge,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Ge,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Ge,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ue.success("Link copied!")};return e.jsx(ws,{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(G,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Create Presentation"]})]}),r?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(Fs,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(ke,{children:e.jsxs(Pe,{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(Ty,{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(G,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(ke,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Pe,{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(ln,{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 ",_s(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(bn,{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(G,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(G,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Yx,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Pa,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(Qr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(Pa,{onClick:()=>a.mutate(o),children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Pa,{onClick:()=>n.mutate(o.id),className:"text-destructive",children:[e.jsx(Kw,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},wVe={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."}]},_Rs=[{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 wRs(s){const t=wVe[s];if(t)return t;const r=s.toLowerCase();for(const[n,a]of Object.entries(wVe))if(r.includes(n.toLowerCase())||n.toLowerCase().includes(r))return a;return _Rs}function jRs({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=k.useState(!1),[i,l]=k.useState("script"),[o,c]=k.useState(0),[d,h]=k.useState(0),{canRecord:m}=Dht(),x=Yb(),[y,v]=k.useState(""),[w,b]=k.useState(!1),[N,S]=k.useState(!0),[T,A]=k.useState(!1),[I,D]=k.useState(null),R=wRs(s),$=()=>{l("script"),c(0),h(0),v(""),b(!1),S(!0),A(!1),D(null)},F=Z=>{!Z&&(i==="uploading"||i==="processing")||(a(Z),Z||$())},z=Z=>{D(Z),v(R[Z].text),b(!1)},Q=()=>{l("record"),S(y.trim().length>0)},K=()=>{v(""),S(!1),l("record")},X=k.useCallback(async(Z,re)=>{l("uploading");try{const le=s||"Presentation Video",{videoId:oe,uploadUrl:ne,libraryId:ie}=await h5(le),{apiKey:ye}=await m5(oe),ce=new XMLHttpRequest;ce.upload.onprogress=De=>{De.lengthComputable&&c(De.loaded/De.total*100)},await new Promise((De,Ae)=>{ce.onload=()=>ce.status>=200&&ce.status<300?De():Ae(new Error("Upload failed")),ce.onerror=()=>Ae(new Error("Upload failed")),ce.open("PUT",ne),ce.setRequestHeader("AccessKey",ye),ce.send(Z)}),l("processing");let ve=0;const be=Date.now(),Ue=9e4;let Be=null;for(;ve<4;){if(await new Promise(Ae=>setTimeout(Ae,3e3)),Date.now()-be>Ue){const Ae=Z.size/1048576,He=`https://iframe.mediadelivery.net/embed/${ie}/${oe}?responsive=true`;await x.mutateAsync({bunny_video_id:oe,playback_url:He,file_size_mb:Ae,title:le,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(He),ue.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const De=await Ev(oe);if(ve=De.status,h(De.encodeProgress||0),ve===4)Be={playbackUrl:De.directPlayUrl,thumbnailUrl:De.thumbnailUrl,previewUrl:De.previewUrl||null,duration:De.length||re,fileSizeMb:(De.storageSize||Z.size)/(1024*1024)};else if(ve===5||ve===6)throw new Error("Video processing failed")}if(!Be)throw new Error("No video data");await x.mutateAsync({bunny_video_id:oe,contact_id:t||void 0,playback_url:Be.playbackUrl,thumbnail_url:Be.thumbnailUrl,preview_url:Be.previewUrl,duration_seconds:Be.duration,file_size_mb:Be.fileSizeMb,title:le,status:"ready",touch_type:"presentation"}),r(Be.playbackUrl),ue.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(le){console.error("Recording upload error:",le),ue.error("Failed to process video. Please try again."),l("record")}},[s,t,r,x]);return e.jsxs(fs,{open:n,onOpenChange:F,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(ms,{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(ys,{children:e.jsxs(gs,{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:R.map((Z,re)=>e.jsxs("button",{onClick:()=>z(re),className:It("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",I===re?"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(ln,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:Z.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:Z.text})]},re))})]}),y&&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"}),!w&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>b(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Ea,{className:"h-3 w-3"}),"Edit"]})]}),w?e.jsx(or,{value:y,onChange:Z=>v(Z.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:y})]}),!y&&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(or,{value:y,onChange:Z=>{v(Z.target.value),D(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(G,{variant:"ghost",size:"sm",onClick:K,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(G,{onClick:Q,disabled:!1,children:y.trim()?"Continue with Script":"Continue Without Script"})]})]}),!m&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(id,{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."}),y.trim()&&e.jsxs(G,{variant:"ghost",size:"sm",onClick:()=>S(!N),className:"h-7 text-xs gap-1",children:[N?e.jsx(Xh,{className:"h-3 w-3"}):e.jsx(bn,{className:"h-3 w-3"}),N?"Hide Script":"Show Script"]})]}),e.jsx(IL,{maxDurationSeconds:600,onRecordingComplete:X,onRecordingStateChange:A,onError:Z=>ue.error(Z),teleprompterContent:y.trim()?e.jsx(DEe,{text:y,isVisible:N,onToggleVisibility:()=>S(!N),isRecording:T,startCountdown:!1}):void 0}),e.jsx(G,{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(es,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ei,{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(es,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ei,{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(di,{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 NRs({sectionTitle:s,contactId:t,onVideoReady:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState("idle"),[d,h]=k.useState(0),m=k.useRef(null),x=Yb(),{data:y}=bxe(),v=(y==null?void 0:y.total_storage_mb)||0,b=((y==null?void 0:y.max_storage_mb)||1024)-v,N=()=>{l(null),c("idle"),h(0)},S=R=>{!R&&o!=="idle"&&o!=="done"||(a(R),R||N())},T=R=>{var z;const $=(z=R.target.files)==null?void 0:z[0];if(!$)return;if(!$.type.startsWith("video/")){ue.error("Please select a video file");return}const F=$.size/(1024*1024);if(F>500){ue.error("Video file must be less than 500MB");return}if(F>b){ue.error(`Not enough storage. You have ${b.toFixed(1)} MB remaining.`);return}l($)},A=k.useCallback(async()=>{if(i){c("creating"),h(0);try{const R=s||i.name,{data:$,error:F}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:R,isAgentVideo:!0}});if(F)throw new Error(F.message);const{videoId:z,libraryId:Q}=$;c("uploading");const{data:K,error:X}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:z,isAgentVideo:!0}});if(X)throw new Error(X.message);await new Promise((le,oe)=>{const ne=new XMLHttpRequest;ne.upload.addEventListener("progress",ie=>{ie.lengthComputable&&h(Math.round(ie.loaded/ie.total*100))}),ne.addEventListener("load",()=>ne.status>=200&&ne.status<300?le():oe(new Error(`Upload failed (${ne.status})`))),ne.addEventListener("error",()=>oe(new Error("Upload failed"))),ne.open("PUT",K.uploadUrl),ne.setRequestHeader("AccessKey",K.apiKey),ne.send(i)}),c("processing");const Z=i.size/(1024*1024),re=`https://iframe.mediadelivery.net/embed/${Q}/${z}`;await x.mutateAsync({bunny_video_id:z,playback_url:re,file_size_mb:Z,title:R,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),r(re),c("done"),ue.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(R){console.error("Upload error:",R),ue.error(R instanceof Error?R.message:"Failed to upload video"),c("idle")}}},[i,s,t,r,x]),I=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},D=o!=="idle"&&o!=="done";return e.jsxs(fs,{open:n,onOpenChange:S,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsx(ys,{children:e.jsxs(gs,{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(Jr,{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"]})]}),!D&&e.jsx(G,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(vr,{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 R;return(R=m.current)==null?void 0:R.click()},children:[e.jsx(da,{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:m,type:"file",accept:"video/*",className:"hidden",onChange:T,disabled:D}),D&&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(es,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:I()})]}),e.jsx(ei,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>S(!1),disabled:D,children:"Cancel"}),e.jsx(G,{onClick:A,disabled:!i||D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const jVe=[{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"}],NVe=()=>{const s=br(),{id:t}=Ki(),{user:r}=js(),{templates:n,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Cxt(),{isGmailConnected:c,gmailEmail:d}=Eh(),[h,m]=k.useState(!1),[x,y]=k.useState("client"),[v,w]=k.useState(!1),[b,N]=k.useState(""),[S,T]=k.useState([]),[A,I]=k.useState(!1),[D,R]=k.useState(null),[$,F]=k.useState(!1),[z,Q]=k.useState(""),[K,X]=k.useState(""),[Z,re]=k.useState(""),[le,oe]=k.useState("buyer"),[ne,ie]=k.useState(""),[ye,ce]=k.useState(null),[ve,be]=k.useState(""),[Ue,Be]=k.useState([]),[De,Ae]=k.useState("schedule_call"),[He,Le]=k.useState("Schedule a Call"),[Ie,Te]=k.useState(""),[xe,et]=k.useState(""),[fe,it]=k.useState(null),[Oe,Ye]=k.useState(t||null),[We,_e]=k.useState(null),[Re,tt]=k.useState(!1),Ke=async(yt,is)=>{if(!r)return;const Bs=5*1024*1024;if(yt.size>Bs){ue.error("Image must be under 5MB");return}if(!yt.type.startsWith("image/")){ue.error("Please upload an image file");return}it(is);try{const ps=yt.name.split(".").pop()||"jpg",lr=`${r.id}/${Date.now()}.${ps}`,{error:kr}=await V.storage.from("listing-photos").upload(lr,yt);if(kr)throw kr;const{data:{publicUrl:Lr}}=V.storage.from("listing-photos").getPublicUrl(lr);jt(is,{image_url:Lr}),ue.success("Image uploaded")}catch{ue.error("Failed to upload image")}finally{it(null)}};k.useEffect(()=>{t&&Ze(t)},[t]);const Ze=async yt=>{const{data:is,error:Bs}=await V.from("smart_presentations").select("*").eq("id",yt).single();if(Bs||!is)return;const ps=is;if(w(!0),be(ps.title),Q(ps.client_name||""),ie(ps.property_address||""),Be(ps.sections||[]),Ae(ps.cta_type||"schedule_call"),Le(ps.cta_label||"Schedule a Call"),Te(ps.cta_url||""),et(ps.heading||""),_e(ps.share_token),tt(ps.status==="published"),Ye(ps.id),y("builder"),ps.contact_id){const{data:lr}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",ps.contact_id).maybeSingle();lr&&(R(lr),X(lr.email||""),re(lr.phone||""))}};k.useEffect(()=>{if(!r||b.length<1){T([]);return}const yt=setTimeout(async()=>{I(!0);const{data:is}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",r.id).or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%`).limit(10);T(is||[]),I(!1)},300);return()=>clearTimeout(yt)},[b,r]);const lt=yt=>{R(yt),Q(`${yt.first_name} ${yt.last_name||""}`.trim()),X(yt.email||""),re(yt.phone||""),F(!1)},xt=async()=>{if(!z.trim()){ue.error("Client name is required");return}const yt=z.trim().split(" "),is=yt[0],Bs=yt.slice(1).join(" ")||null,{data:ps,error:lr}=await V.from("innercircle_contacts").insert({owner_user_id:r.id,first_name:is,last_name:Bs,email:K||null,phone:Z||null,lead_source:"Smart Presentation"}).select().single();if(lr){ue.error("Failed to create client");return}R(ps),ue.success("Client created & saved to Agent OS"),y("template")},Xe=yt=>{ce(yt);const is=(yt.sections||[]).map(Bs=>({...Bs,is_visible:!0,video_url:"",text:""}));if(Be(is),be(yt.name+(z?` for ${z}`:"")),yt.cta_config){const Bs=yt.cta_config;Ae(Bs.type||"schedule_call"),Le(Bs.label||"Schedule a Call")}y("builder")},Je=()=>{Be([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),be(z?`Presentation for ${z}`:"New Presentation"),y("builder")},jt=(yt,is)=>{Be(Bs=>Bs.map((ps,lr)=>lr===yt?{...ps,...is}:ps))},ns=yt=>{jt(yt,{is_visible:!Ue[yt].is_visible})},Ns=()=>{Be(yt=>[...yt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},Ys=yt=>{Be(is=>is.filter((Bs,ps)=>ps!==yt))},rs=async()=>{if(!ve.trim()){ue.error("Title is required");return}try{if(Oe){const yt=await l.mutateAsync({id:Oe,title:ve,sections:Ue,client_name:z,property_address:ne||null,cta_type:De,cta_label:He,cta_url:Ie||null,heading:xe||null});ue.success("Saved")}else{const yt=await i.mutateAsync({title:ve,contact_id:(D==null?void 0:D.id)||void 0,client_name:z,property_address:ne||void 0,template_id:(ye==null?void 0:ye.id)||void 0,sections:Ue,cta_type:De,cta_label:He,cta_url:Ie||void 0,heading:xe||void 0});Ye(yt.id),_e(yt.share_token),ue.success("Presentation created!")}}catch(yt){console.error("Failed to save presentation:",yt);const is=(yt==null?void 0:yt.message)||(yt==null?void 0:yt.toString())||"Unknown error";ue.error(`Failed to save: ${is}`)}},bt=async()=>{try{await rs();const yt=Oe;if(yt){const is=await o.mutateAsync(yt);_e(is.share_token),tt(!0),y("share")}}catch(yt){console.error("Failed to publish presentation:",yt),ue.error(`Failed to publish: ${(yt==null?void 0:yt.message)||"Unknown error"}`)}},cs=We?`https://presentations.relevelup.com/${We}`:"";return e.jsx(ws,{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(G,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:v?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x==="client"&&"Who is this presentation for?",x==="template"&&"Choose a starting template",x==="builder"&&"Customize your presentation",x==="share"&&"Share with your client"]})]})]}),!v&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((yt,is)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:It("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",x===yt?"bg-primary text-primary-foreground":is<["client","template","builder","share"].indexOf(x)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:is<["client","template","builder","share"].indexOf(x)?e.jsx(Kn,{className:"h-4 w-4"}):is+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:yt}),is<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},yt))}),x==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{R(null),Q(""),X(""),re(""),F(!1),y("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(en,{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(Ha,{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(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Pe,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search by name or email...",value:b,onChange:yt=>N(yt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(Fs,{className:"h-12 w-full"}),S.map(yt=>e.jsxs("button",{onClick:()=>lt(yt),className:It("w-full text-left p-3 rounded-lg border transition-colors",(D==null?void 0:D.id)===yt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[yt.first_name," ",yt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:yt.email||yt.phone||"No contact info"})]},yt.id)),!b&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),b&&S.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),D&&e.jsxs(G,{onClick:()=>y("template"),className:"w-full gap-2",children:["Continue with ",D.first_name,e.jsx(Ha,{className:"h-4 w-4"})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Pe,{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(he,{className:"text-xs",children:"Name *"}),e.jsx(Ne,{value:z,onChange:yt=>{Q(yt.target.value),F(!0),R(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Email"}),e.jsx(Ne,{value:K,onChange:yt=>X(yt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Phone"}),e.jsx(Ne,{value:Z,onChange:yt=>re(yt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Client Type"}),e.jsxs(Is,{value:le,onValueChange:oe,children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"buyer",children:"Buyer"}),e.jsx(ct,{value:"seller",children:"Seller"}),e.jsx(ct,{value:"recruit",children:"Recruit"}),e.jsx(ct,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Property Address"}),e.jsx(Ne,{value:ne,onChange:yt=>ie(yt.target.value),placeholder:"Optional"})]})]}),$&&z&&e.jsxs(G,{onClick:xt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Ha,{className:"h-4 w-4"})]})]})]})]})]}),x==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(On,{defaultValue:"system",children:[e.jsxs(Rn,{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(ts,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(yt=>e.jsx(Fs,{className:"h-32"},yt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(yt=>!yt.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!"}):n.filter(yt=>!yt.is_system).map(yt=>e.jsx(kVe,{template:yt,onSelect:Xe},yt.id))})}),e.jsx(ts,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:n.filter(yt=>yt.is_system).map(yt=>e.jsx(kVe,{template:yt,onSelect:Xe},yt.id))})}),e.jsx(ts,{value:"blank",className:"mt-4",children:e.jsx(ke,{children:e.jsxs(Pe,{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(G,{onClick:Je,children:"Start from Scratch"})]})})})]}),e.jsxs(G,{variant:"outline",onClick:()=>y("client"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]})]}),x==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{children:e.jsxs(Pe,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Presentation Title"}),e.jsx(Ne,{value:ve,onChange:yt=>be(yt.target.value)})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Page Heading"}),e.jsx(Ne,{value:xe,onChange:yt=>et(yt.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(he,{children:"Client Name"}),e.jsx(Ne,{value:z,onChange:yt=>Q(yt.target.value)})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Property Address"}),e.jsx(Ne,{value:ne,onChange:yt=>ie(yt.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(G,{variant:"outline",size:"sm",onClick:Ns,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:Ue.map((yt,is)=>e.jsx(ke,{className:It(!yt.is_visible&&"opacity-50"),children:e.jsx(Pe,{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(vu,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:yt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ne,{value:yt.title,onChange:Bs=>jt(is,{title:Bs.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(G,{variant:"ghost",size:"icon",onClick:()=>ns(is),children:yt.is_visible?e.jsx(bn,{className:"h-4 w-4"}):e.jsx(Xh,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"icon",onClick:()=>Ys(is),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]}),e.jsx(Ne,{value:yt.description||"",onChange:Bs=>jt(is,{description:Bs.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(he,{className:"text-xs",children:"Video URL"}),e.jsx(Ne,{value:yt.video_url||"",onChange:Bs=>jt(is,{video_url:Bs.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(jRs,{sectionTitle:yt.title,contactId:D==null?void 0:D.id,onVideoReady:Bs=>jt(is,{video_url:Bs})}),e.jsx(NRs,{sectionTitle:yt.title,contactId:D==null?void 0:D.id,onVideoReady:Bs=>jt(is,{video_url:Bs})}),e.jsx(yL,{userId:r==null?void 0:r.id,onSelect:Bs=>jt(is,{video_url:Bs})})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),yt.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:yt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>jt(is,{image_url:""}),children:e.jsx(vr,{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:[fe===is?e.jsx(es,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(rv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:fe===is?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:fe===is,onChange:Bs=>{var lr;const ps=(lr=Bs.target.files)==null?void 0:lr[0];ps&&Ke(ps,is),Bs.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Text (optional)"}),e.jsx(Uy,{content:yt.text||"",onChange:Bs=>jt(is,{text:Bs}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},is))})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Call to Action"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"CTA Type"}),e.jsxs(Is,{value:De,onValueChange:yt=>{Ae(yt);const is=jVe.find(Bs=>Bs.value===yt);is&&Le(is.label)},children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:jVe.map(yt=>e.jsx(ct,{value:yt.value,children:yt.label},yt.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Button Label"}),e.jsx(Ne,{value:He,onChange:yt=>Le(yt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(he,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(Ne,{value:Ie,onChange:yt=>Te(yt.target.value),placeholder:"https://calendly.com/..."}),!Ie&&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:[!v&&e.jsxs(G,{variant:"outline",onClick:()=>y("template"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(G,{variant:"outline",onClick:rs,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(G,{onClick:bt,disabled:o.isPending,className:"gap-2",children:[e.jsx(en,{className:"h-4 w-4"}),Re?"Update & Reshare":"Publish & Share"]})]})]})]}),x==="share"&&We&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(ke,{children:e.jsxs(Pe,{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(Kn,{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(Ne,{value:cs,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(G,{onClick:()=>{navigator.clipboard.writeText(cs),ue.success("Link copied!")},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(G,{variant:"outline",className:"gap-2",onClick:()=>{const yt=`Hi ${z||""}! I put together something for you — check it out: ${cs}`;navigator.clipboard.writeText(yt),ue.success("Message copied!")},children:[e.jsx(xi,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(G,{variant:"outline",className:"gap-2",onClick:()=>{c?m(!0):window.open(`mailto:${K||""}?subject=${encodeURIComponent(ve)}&body=${encodeURIComponent(`Hi ${(D==null?void 0:D.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${cs} Looking forward to connecting!`)}`)},children:[e.jsx(Vs,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx($v,{open:h,onOpenChange:m,contact:D?{id:D.id,first_name:D.first_name,last_name:D.last_name,email:K||D.email||""}:K?{id:"",first_name:(z==null?void 0:z.split(" ")[0])||"",last_name:(z==null?void 0:z.split(" ").slice(1).join(" "))||"",email:K}:void 0,defaultSubject:ve,defaultBody:`Hi ${(D==null?void 0:D.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${cs} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(G,{variant:"outline",onClick:()=>y("builder"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(G,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},kVe=({template:s,onSelect:t})=>e.jsx(ke,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Pe,{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(Ge,{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(G,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),kRs=()=>{var w;const{shareToken:s}=Ki(),[t,r]=k.useState(null),[n,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),k.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:b,error:N}=await V.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(N||!b){c(!0),a(!1);return}const{data:S}=await V.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",b.owner_user_id).single();let T;if(S!=null&&S.brokerage_id){const{data:I}=await V.from("brokerages").select("name").eq("id",S.brokerage_id).single();T=(I==null?void 0:I.name)||void 0}let A=null;if(b.contact_id){const{data:I}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",b.contact_id).single();A=I}r({...b,owner_name:S==null?void 0:S.name,owner_email:S==null?void 0:S.email,owner_phone:S==null?void 0:S.phone,owner_avatar:S==null?void 0:S.avatar_url,owner_title:(S==null?void 0:S.title)||void 0,brokerage_name:T,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 V.rpc("log_presentation_view",{p_presentation_id:b.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},h=async()=>{if(t){try{await V.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(n)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(Fs,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Fs,{className:"h-64 w-full"}),e.jsx(Fs,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(b=>b.is_visible!==!1),x=m[i],y=b=>{const N=b.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(N)return`https://www.youtube.com/embed/${N[1]}?rel=0`;if(b.includes("iframe.mediadelivery.net/play/")){const A=b.replace("/play/","/embed/"),I=A.includes("?")?"&":"?";return`${A}${I}responsive=true`}if(b.includes("iframe.mediadelivery.net")){if(b.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const I=b.includes("?")?"&":"?";return`${b}${I}responsive=true`}return""}const S=b.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(S)return`https://www.loom.com/embed/${S[1]}`;const T=b.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return T?`https://iframe.mediadelivery.net/embed/${T[1]}/${T[2]}?responsive=true`:b},v=!!((w=t.cta_url)!=null&&w.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:[x!=null&&x.video_url&&y(x.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:y(x.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"})}):x!=null&&x.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:x.image_url,alt:x.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:x==null?void 0:x.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:x==null?void 0:x.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:x==null?void 0:x.description})]}),(x==null?void 0:x.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:x.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((b,N)=>e.jsx("button",{onClick:()=>l(N),className:It("w-full text-left p-4 rounded-xl border transition-all",i===N?"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(N+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:b.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:b.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:b.description})]})]})},N))})]}),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?"}),v?e.jsxs(G,{size:"lg",onClick:h,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(Qr,{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(DJe,{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 SRs({openHouseId:s,enableSurvey:t,onToggleSurvey:r}){const{data:n,isLoading:a}=LMt(s),i=OMt(),l=FMt(),o=BMt(),c=zMt(),[d,h]=k.useState(""),[m,x]=k.useState("rating"),y=async N=>{r(N),N&&(!n||n.length===0)&&await c.mutateAsync(s)},v=async()=>{if(!d.trim())return;const N=(n==null?void 0:n.reduce((S,T)=>Math.max(S,T.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:m,question_text:d.trim(),sort_order:N+1}),h("")},w=async N=>{await l.mutateAsync({id:N.id,open_house_id:s,is_active:!N.is_active})},b=async N=>{await o.mutateAsync({id:N.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(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Zw,{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(_r,{checked:t,onCheckedChange:y})]}),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(es,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:n==null?void 0:n.map(N=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(vu,{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:N.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:N.question_type.replace("_"," ")})]}),e.jsx(_r,{checked:N.is_active,onCheckedChange:()=>w(N),className:"scale-75"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>b(N),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]},N.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(Ne,{value:d,onChange:N=>h(N.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:N=>N.key==="Enter"&&v()})]}),e.jsxs(Is,{value:m,onValueChange:x,children:[e.jsx(As,{className:"w-28 h-9 text-xs",children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"rating",children:"Rating"}),e.jsx(ct,{value:"open_text",children:"Text"})]})]}),e.jsx(G,{size:"sm",variant:"outline",onClick:v,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx($s,{className:"h-3.5 w-3.5"})})]})]})})]})}function CRs({openHouseId:s}){const{user:t}=js(),{data:r=[],isLoading:n}=VMt(s),a=GMt(),[i,l]=k.useState(""),[o,c]=k.useState(!1),d=async()=>{const h=i.trim();if(h){c(!0);try{await a.mutateAsync({open_house_id:s,name:h,sort_order:r.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{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."})]}),n?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(es,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):r.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:r.map((h,m)=>e.jsx(TRs,{room:h,index:m,total:r.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},h.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(Ne,{value:i,onChange:h=>l(h.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d())}}),e.jsx(G,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function TRs({room:s,index:t,total:r,userId:n,openHouseId:a}){const i=WMt(),l=KMt(),o=YMt(),c=ZMt(),d=k.useRef(null),[h,m]=k.useState(!0),[x,y]=k.useState(s.name),[v,w]=k.useState(s.description||""),[b,N]=k.useState(!1),S=k.useMemo(()=>s.media.filter(F=>F.kind==="video"&&F.agent_video_id).map(F=>F.agent_video_id),[s.media]),{data:T={}}=mt({queryKey:["room-video-statuses",s.id,S.join(",")],enabled:S.length>0,queryFn:async()=>{const{data:F,error:z}=await V.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",S);if(z)throw z;const Q=F||[],K=Q.filter(Z=>Z.status==="processing"&&Z.bunny_video_id);await Promise.all(K.map(async Z=>{try{const{data:re}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:Z.bunny_video_id,isAgentVideo:!0}});re&&re.status===4&&(await V.from("agent_videos").update({status:"ready",playback_url:re.directPlayUrl,thumbnail_url:re.thumbnailUrl,preview_url:re.previewUrl,duration_seconds:re.length||void 0,updated_at:new Date().toISOString()}).eq("id",Z.id),Z.status="ready",Z.thumbnail_url=re.thumbnailUrl,Z.preview_url=re.previewUrl)}catch{}}));const X={};return Q.forEach(Z=>{X[Z.id]={status:Z.status,thumbnail_url:Z.thumbnail_url,preview_url:Z.preview_url}}),X},refetchInterval:F=>{const z=F.state.data;return z?Object.values(z).some(Q=>Q.status!=="ready"&&Q.status!=="failed")?5e3:!1:5e3}}),A=()=>{x.trim()&&x!==s.name&&i.mutate({id:s.id,open_house_id:a,name:x.trim()})},I=()=>{v!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:v.trim()||null})},D=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},R=F=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+F})},$=async F=>{const z=Array.from(F.target.files||[]);if(!(!z.length||!n)){N(!0);try{for(const Q of z){const K=Q.type.startsWith("video/"),X=K?500*1024*1024:15*1024*1024;if(Q.size>X){cn({title:`${Q.name} is too large`,description:K?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(K){try{const ne=`${s.name} – ${Q.name.replace(/\.[^/.]+$/,"")}`,{data:ie,error:ye}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:ne,isAgentVideo:!0}});if(ye||!ie)throw new Error((ye==null?void 0:ye.message)||"Could not start upload");const{videoId:ce,libraryId:ve}=ie,{data:be,error:Ue}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ce,isAgentVideo:!0}});if(Ue||!be)throw new Error((Ue==null?void 0:Ue.message)||"Could not get upload URL");await new Promise((Le,Ie)=>{const Te=new XMLHttpRequest;Te.addEventListener("load",()=>{Te.status>=200&&Te.status<300?Le():Ie(new Error(`Upload failed (${Te.status})`))}),Te.addEventListener("error",()=>Ie(new Error("Upload failed"))),Te.open("PUT",be.uploadUrl),Te.setRequestHeader("AccessKey",be.apiKey),Te.send(Q)});const Be=`https://iframe.mediadelivery.net/embed/${ve}/${ce}`,De=Q.size/(1024*1024),{data:Ae,error:He}=await V.from("agent_videos").insert({owner_user_id:n,bunny_video_id:ce,playback_url:Be,file_size_mb:De,title:ne,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(He)throw He;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Be,sort_order:s.media.length,agent_video_id:Ae.id}),cn({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(ne){cn({title:"Video upload failed",description:(ne==null?void 0:ne.message)||"Try again",variant:"destructive"})}continue}const Z=Q.name.split(".").pop()||"jpg",re=`${n}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${Z}`,{error:le}=await V.storage.from("open-house-tour-media").upload(re,Q,{upsert:!1,contentType:Q.type});if(le){cn({title:"Upload failed",description:le.message,variant:"destructive"});continue}const{data:oe}=V.storage.from("open-house-tour-media").getPublicUrl(re);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:oe.publicUrl,sort_order:s.media.length})}}finally{N(!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(vu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>m(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(G,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(-1),disabled:t===0,children:e.jsx(Jf,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(1),disabled:t===r-1,children:e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx(G,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:D,children:e.jsx(yr,{className:"h-4 w-4"})})]}),h&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(Ne,{value:x,onChange:F=>y(F.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(or,{value:v,onChange:F=>w(F.target.value),onBlur:I,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?T[F.agent_video_id]:void 0,Q=z==null?void 0:z.status,K=F.kind==="video"&&Q&&Q!=="ready"&&Q!=="failed",X=F.kind==="video"&&Q==="failed",Z=(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:[Z?e.jsx("img",{src:Z,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"}),!K&&!X&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(Jr,{className:"h-6 w-6 text-white"})}),K&&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(es,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),X&&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(vr,{className:"h-3.5 w-3.5"})})]},F.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:$,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",onClick:()=>{var F;return(F=d.current)==null?void 0:F.click()},disabled:b,className:"flex-1",children:b?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(yL,{userId:n,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}),cn({title:"Video added to room"})}catch(z){cn({title:"Failed to add video",description:z==null?void 0:z.message,variant:"destructive"})}}})]})]})]})}function ERs({open:s,onOpenChange:t,openHouse:r}){const n=OJe(),{user:a}=js(),i=k.useRef(null),l=k.useRef(null),o=k.useRef(null),c=r.kind==="virtual",[d,h]=k.useState(r.auto_forward_to_card??!1),[m,x]=k.useState(r.disclosure_pdf_url??""),[y,v]=k.useState(r.enable_survey??!1),[w,b]=k.useState(r.ask_visitor_intent??!0),[N,S]=k.useState(r.photo_url??""),[T,A]=k.useState(!1),[I,D]=k.useState(!1),[R,$]=k.useState(!1),[F,z]=k.useState(r.hero_video_url??""),[Q,K]=k.useState(!1),[X,Z]=k.useState(r.price!=null?String(r.price):""),[re,le]=k.useState(r.beds!=null?String(r.beds):""),[oe,ne]=k.useState(r.baths!=null?String(r.baths):""),[ie,ye]=k.useState(r.sqft!=null?String(r.sqft):""),[ce,ve]=k.useState(r.enable_question??!0),[be,Ue]=k.useState(r.enable_showing??!0),[Be,De]=k.useState(r.enable_disclosures??!0),[Ae,He]=k.useState(r.enable_offer??!0),[Le,Ie]=k.useState(r.brand_color_override??""),[Te,xe]=k.useState(r.property_description??""),et=async _e=>{var xt;const Re=(xt=_e.target.files)==null?void 0:xt[0];if(!Re||!a)return;if(Re.size>200*1024*1024){cn({title:"Video must be under 200MB",variant:"destructive"});return}if(!Re.type.startsWith("video/")){cn({title:"Please upload a video file",variant:"destructive"});return}K(!0);const tt=Re.name.split(".").pop()||"mp4",Ke=`${a.id}/${r.id}/hero-${Date.now()}.${tt}`,{error:Ze}=await V.storage.from("open-house-tour-media").upload(Ke,Re,{upsert:!0,contentType:Re.type});if(Ze){cn({title:"Upload failed",description:Ze.message,variant:"destructive"}),K(!1);return}const{data:lt}=V.storage.from("open-house-tour-media").getPublicUrl(Ke);z(lt.publicUrl),K(!1),cn({title:"Video uploaded!"})},fe=async _e=>{var xt;const Re=(xt=_e.target.files)==null?void 0:xt[0];if(!Re||!a)return;if(Re.size>10*1024*1024){cn({title:"Image must be under 10MB",variant:"destructive"});return}if(!Re.type.startsWith("image/")){cn({title:"Please upload an image file",variant:"destructive"});return}D(!0);const tt=Re.name.split(".").pop()||"jpg",Ke=`${a.id}/${r.id}-${Date.now()}.${tt}`,{error:Ze}=await V.storage.from("open-house-photos").upload(Ke,Re,{upsert:!0});if(Ze){cn({title:"Upload failed",description:Ze.message,variant:"destructive"}),D(!1);return}const{data:lt}=V.storage.from("open-house-photos").getPublicUrl(Ke);S(lt.publicUrl),D(!1),cn({title:"Photo updated!"})},it=()=>{S(""),l.current&&(l.current.value="")},Oe=async _e=>{var lt;const Re=(lt=_e.target.files)==null?void 0:lt[0];if(!Re||!a)return;if(Re.size>20*1024*1024){cn({title:"File must be under 20MB",variant:"destructive"});return}if(Re.type!=="application/pdf"){cn({title:"Only PDF files are accepted",variant:"destructive"});return}A(!0);const tt=`${a.id}/disclosures/${r.id}-${Date.now()}.pdf`,{error:Ke}=await V.storage.from("open-house-photos").upload(tt,Re,{upsert:!0});if(Ke){cn({title:"Upload failed",description:Ke.message,variant:"destructive"}),A(!1);return}const{data:Ze}=V.storage.from("open-house-photos").getPublicUrl(tt);x(Ze.publicUrl),A(!1),cn({title:"PDF uploaded!"})},Ye=()=>{x(""),i.current&&(i.current.value="")},We=async()=>{$(!0);try{const _e={id:r.id,auto_forward_to_card:d,disclosure_pdf_url:m||null,enable_survey:y,ask_visitor_intent:w,photo_url:N||null};c&&(_e.hero_video_url=F||null,_e.price=X.trim()?Number(X):null,_e.beds=re.trim()?parseInt(re,10):null,_e.baths=oe.trim()?Number(oe):null,_e.sqft=ie.trim()?parseInt(ie,10):null,_e.enable_question=ce,_e.enable_showing=be,_e.enable_disclosures=Be,_e.enable_offer=Ae,_e.brand_color_override=Le.trim()||null,_e.property_description=Te.trim()||null),await n.mutateAsync(_e),cn({title:"Settings saved!"}),t(!1)}catch{cn({title:"Failed to save",variant:"destructive"})}finally{$(!1)}};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Hr,{className:"truncate",children:r.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[r.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Jr,{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:et,className:"hidden"}),F?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:F,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(G,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var _e;return(_e=o.current)==null?void 0:_e.click()},disabled:Q,children:Q?e.jsx(es,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(G,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>z(""),children:e.jsx(vr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var _e;return(_e=o.current)==null?void 0:_e.click()},disabled:Q,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:Q?e.jsx(es,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Jr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(CRs,{openHouseId:r.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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(he,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(Ne,{type:"number",value:X,onChange:_e=>Z(_e.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(Ne,{type:"number",value:ie,onChange:_e=>ye(_e.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(Ne,{type:"number",value:re,onChange:_e=>le(_e.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(Ne,{type:"number",step:"0.5",value:oe,onChange:_e=>ne(_e.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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(or,{value:Te,onChange:_e=>xe(_e.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(he,{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(_r,{checked:ce,onCheckedChange:ve})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(_r,{checked:be,onCheckedChange:Ue})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(_r,{checked:Be,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(_r,{checked:Ae,onCheckedChange:He})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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:Le||"#0f172a",onChange:_e=>Ie(_e.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(Ne,{value:Le,onChange:_e=>Ie(_e.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Le&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Ie(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(_e=>e.jsx("button",{type:"button",onClick:()=>Ie(_e),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:_e},"aria-label":_e},_e))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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:fe,className:"hidden"}),N?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:N,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(G,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var _e;return(_e=l.current)==null?void 0:_e.click()},disabled:I,children:[I?e.jsx(es,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),I?"":"Replace"]}),e.jsx(G,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:it,children:e.jsx(vr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var _e;return(_e=l.current)==null?void 0:_e.click()},disabled:I,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:I?e.jsx(es,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ml,{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(he,{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(_r,{checked:d,onCheckedChange:h})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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:Oe,className:"hidden"}),m?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(ln,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(G,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ye,children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var _e;return(_e=i.current)==null?void 0:_e.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(es,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(da,{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(he,{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(_r,{checked:w,onCheckedChange:b})]})}),e.jsx(SRs,{openHouseId:r.id,enableSurvey:y,onToggleSurvey:v}),e.jsx(G,{onClick:We,disabled:R,className:"w-full",children:R?"Saving...":"Save Settings"})]})]})})}const Txt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function ARs({question:s,responses:t}){const r=t.filter(l=>l.question_id===s.id&&l.rating_value!=null),n=r.length;if(n===0)return null;const a=r.reduce((l,o)=>l+(o.rating_value||0),0)/n,i=[5,4,3,2,1].map(l=>({val:l,count:r.filter(o=>o.rating_value===l).length,pct:Math.round(r.filter(o=>o.rating_value===l).length/n*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 (",n," 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:Txt[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 MRs({openHouseId:s}){const{data:t,isLoading:r}=RMt(s),{data:n}=RJe(s),a=k.useMemo(()=>{const m={};return n==null||n.forEach(x=>{m[x.id]=x}),m},[n]);if(r||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(m=>m.question_type==="rating"),c=i.filter(m=>m.question_type!=="rating"),d=[...new Set(l.map(m=>m.visitor_id))],h=d.length;return h===0?e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Zw,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Pe,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(ke,{children:[e.jsx(Mt,{className:"pb-3",children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Zw,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[h," respondent",h!==1?"s":""]})]})}),e.jsx(Pe,{children:e.jsxs(On,{defaultValue:"summary",children:[e.jsxs(Rn,{className:"mb-4",children:[e.jsxs(Kt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(ro,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Kt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Di,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(ts,{value:"summary",className:"space-y-6",children:[o.map(m=>e.jsx(ARs,{question:m,responses:l},m.id)),c.map(m=>{const x=l.filter(y=>y.question_id===m.id&&y.text_value);return x.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:m.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:x.map(y=>{const v=a[y.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:[v?`${v.first_name} ${v.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:y.text_value})]},y.id)})})]},m.id)})]}),e.jsx(ts,{value:"individual",className:"space-y-4",children:d.map(m=>{const x=a[m],y=l.filter(v=>v.visitor_id===m);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:[x?`${x.first_name} ${x.last_name||""}`.trim():"Unknown Visitor",(x==null?void 0:x.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:x.email})]}),e.jsx("div",{className:"space-y-1",children:y.map(v=>{const w=i.find(b=>b.id===v.question_id);return w?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:w.question_text}),e.jsx("span",{className:"font-medium",children:v.rating_value!=null?Txt[v.rating_value]||v.rating_value:v.text_value})]},v.id):null})})]},m)})})]})})]})}const IRs={question:{label:"Question",icon:xi,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:on,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:ln,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:wl,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},SVe={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 LRs({openHouseId:s}){const{data:t=[],isLoading:r}=XMt(s),n=QMt(),[a,i]=k.useState(null),[l,o]=k.useState("all"),c=t.filter(m=>l==="all"?!0:l==="new"?m.status==="new":m.action_type===l),d={all:t.length,new:t.filter(m=>m.status==="new").length,question:t.filter(m=>m.action_type==="question").length,showing:t.filter(m=>m.action_type==="showing").length,disclosure:t.filter(m=>m.action_type==="disclosure").length,offer:t.filter(m=>m.action_type==="offer").length},h=(m,x)=>{n.mutate({id:m,status:x,open_house_id:s})};return r?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(ej,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Ge,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Ge,{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(([m,x,y])=>e.jsxs("button",{onClick:()=>o(m),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===m?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[x," ",e.jsx("span",{className:"opacity-60",children:y})]},m))})]}),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(m=>{const x=IRs[m.action_type],y=x.icon,v=m.payload||{},w=a===m.id,b=m.status==="contacted",N=m.status==="archived";return e.jsxs("li",{className:`transition-colors ${N?"opacity-60":""} ${m.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(w?null:m.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 ${x.bg}`,children:e.jsx(y,{className:`h-4 w-4 ${x.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:v.visitor_name||"Visitor"}),e.jsx(Ge,{variant:"outline",className:`text-[10px] ${x.color}`,children:x.label}),m.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),b&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(In,{className:"h-3 w-3"}),"Contacted"]})]}),v.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',v.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(fn,{className:"h-3 w-3"}),_s(new Date(m.created_at),"MMM d, h:mm a")]}),v.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Vs,{className:"h-3 w-3"}),v.email]}),v.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cn,{className:"h-3 w-3"}),v.phone]})]})]}),w?e.jsx(Wi,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(va,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),w&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[v.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',v.message,'"']}),Object.keys(SVe).some(S=>v[S]!=null&&v[S]!==""&&!(Array.isArray(v[S])&&v[S].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(SVe).map(([S,T])=>{const A=v[S];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:T}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},S)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[v.email&&e.jsx("a",{href:`mailto:${v.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(G,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Reply"]})}),v.phone&&e.jsx("a",{href:`tel:${String(v.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"Call"]})}),!b&&e.jsxs(G,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>h(m.id,"contacted"),children:[e.jsx(In,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),N?e.jsx(G,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>h(m.id,"new"),children:"Restore"}):e.jsxs(G,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>h(m.id,"archived"),children:[e.jsx(Kw,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},m.id)})})]})}function PRs({open:s,onOpenChange:t,openHouse:r}){const{isGmailConnected:n,gmailEmail:a}=Eh(),i=sa(),[l,o]=k.useState([]),[c,d]=k.useState([]),[h,m]=k.useState(!1),[x,y]=k.useState(!1),[v,w]=k.useState(""),[b,N]=k.useState(""),[S,T]=k.useState(""),[A,I]=k.useState(!1),[D,R]=k.useState(!1),[$,F]=k.useState(!1),z=`https://guestbook.relevelup.com/${r.slug}`;k.useEffect(()=>{s&&(N(`Take a virtual tour of ${r.property_address}`),T(`I wanted to share an immersive virtual tour of ${r.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),w(""),I(n),l.length===0&&Q())},[s,r.id,n]);const Q=async()=>{if(i){y(!0);try{const{data:ie,error:ye}=await V.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(ye)throw ye;o(ie||[])}catch{ue.error("Failed to load contacts")}finally{y(!1)}}},K=ie=>`${ie.first_name} ${ie.last_name||""}`.trim(),X=ie=>{d(ye=>ye.find(ce=>ce.id===ie.id)?ye.filter(ce=>ce.id!==ie.id):[...ye,ie])},Z=()=>{const ie=v.trim();if(!ie)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ie)){ue.error("Invalid email");return}d(ce=>[...ce,{id:`manual-${ie}`,first_name:ie.split("@")[0],last_name:null,email:ie}]),w("")},re=k.useMemo(()=>c.filter(ie=>!!ie.email).map(ie=>({email:ie.email,name:K(ie)})),[c]),le=ie=>{const ye=ie?`Hi ${ie},`:"Hi there,",ce=S.split(/\n\n+/).map(ve=>`

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

`).join("");return`

${ye}

${ce}

▶ Start Virtual Tour

Or copy this link: ${z}

`},oe=async()=>{var ie;if(re.length===0){ue.error("Add at least one recipient");return}R(!0);try{if(A&&n){let ye=0;for(const ce of re){const{data:ve,error:be}=await V.functions.invoke("gmail-send",{body:{to:ce.email,subject:b,body:le((ie=ce.name)==null?void 0:ie.split(" ")[0])}});!be&&(ve!=null&&ve.success)?ye+=1:console.warn("gmail-send error",be,ve)}if(ye===0)throw new Error("Gmail send failed");ue.success(`Sent to ${ye} of ${re.length} via Gmail`)}else{const{data:ye,error:ce}=await V.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:r.id,recipients:re,subject:b,personalMessage:S}});if(ce)throw ce;if(!(ye!=null&&ye.success))throw new Error((ye==null?void 0:ye.error)||"Send failed");ue.success(`Sent to ${ye.sent} of ${ye.total} recipient${ye.total===1?"":"s"}`)}t(!1)}catch(ye){ue.error((ye==null?void 0:ye.message)||"Failed to send")}finally{R(!1)}},ne=async()=>{await navigator.clipboard.writeText(z),F(!0),setTimeout(()=>F(!1),1500)};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(ys,{className:"min-w-0",children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Vs,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Hr,{className:"truncate",children:r.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(po,{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(G,{variant:"ghost",size:"sm",onClick:ne,className:"shrink-0 h-7 gap-1",children:[$?e.jsx(Kn,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ra,{className:"h-3.5 w-3.5"}),$?"Copied":"Copy"]})]}),n&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(G,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>I(!0),className:"gap-1.5",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(G,{type:"button",variant:A?"outline":"default",size:"sm",onClick:()=>I(!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(he,{className:"flex items-center gap-1.5",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(To,{open:h,onOpenChange:m,modal:!0,children:[e.jsx(Eo,{asChild:!0,children:e.jsxs(G,{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(qp,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(_o,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(rx,{children:[e.jsx(nx,{placeholder:"Search contacts..."}),e.jsxs(ax,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(ix,{children:x?"Loading...":"No contacts found."}),e.jsx(ox,{children:l.map(ie=>{const ye=!!c.find(be=>be.id===ie.id),ce=K(ie).slice(0,80),ve=(ie.email||"").slice(0,80);return e.jsxs(cf,{value:`${ce} ${ve}`,onSelect:()=>X(ie),className:"py-2",children:[e.jsx(Kn,{className:It("mr-2 h-4 w-4 shrink-0",ye?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:ce||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ve})]})]},ie.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ie=>e.jsxs(Ge,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:K(ie)}),e.jsx("button",{onClick:()=>X(ie),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(vr,{className:"h-3 w-3"})})]},ie.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(Ne,{value:v,onChange:ie=>w(ie.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:ie=>{ie.key==="Enter"&&(ie.preventDefault(),Z())}}),e.jsx(G,{type:"button",variant:"outline",size:"sm",onClick:Z,children:"Add"})]})]}),e.jsx(fo,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(Ne,{id:"vt-subject",value:b,onChange:ie=>N(ie.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(or,{id:"vt-message",value:S,onChange:ie=>T(ie.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>t(!1),disabled:D,children:"Cancel"}),e.jsxs(G,{onClick:oe,disabled:D||re.length===0||!b.trim(),className:"gap-2",children:[D?e.jsx(es,{className:"h-4 w-4 animate-spin"}):e.jsx(en,{className:"h-4 w-4"}),D?"Sending...":`Send${re.length?` to ${re.length}`:""}`]})]})]})]})})}const Bke="guestbook.relevelup.com";function DRs(){const{data:s,isLoading:t}=EMt(),r=AMt(),n=OJe(),a=MMt(),[i,l]=k.useState(!1),[o,c]=k.useState(null),{user:d}=js(),h=sa(),[m,x]=k.useState(null),[y,v]=k.useState(null),[w,b]=k.useState(!1),N=k.useRef(null),[S,T]=k.useState({property_address:"",city:"",state:"",zip:"",event_date:_s(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=$=>{var z;const F=(z=$.target.files)==null?void 0:z[0];if(F){if(F.size>5*1024*1024){cn({title:"Photo must be under 5MB",variant:"destructive"});return}x(F),v(URL.createObjectURL(F))}},I=()=>{x(null),v(null),N.current&&(N.current.value="")},D=async()=>{if(!S.property_address){cn({title:S.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let $;if(m&&d){b(!0);const z=m.name.split(".").pop(),Q=`${h}/${Date.now()}.${z}`,{error:K}=await V.storage.from("open-house-photos").upload(Q,m,{upsert:!0});if(K){cn({title:"Photo upload failed",description:K.message,variant:"destructive"}),b(!1);return}const{data:X}=V.storage.from("open-house-photos").getPublicUrl(Q);$=X.publicUrl,b(!1)}const F=S.kind==="virtual"?{...S,start_time:void 0,end_time:void 0,photo_url:$}:{...S,photo_url:$};await r.mutateAsync(F),l(!1),T({property_address:"",city:"",state:"",zip:"",event_date:_s(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"}),I()},R=$=>{navigator.clipboard.writeText(`https://${Bke}/${$}`),cn({title:"Link copied!"})};return e.jsxs(ws,{title:"Guest Book",children:[e.jsx(nl,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold font-serif text-foreground",children:"Guest Book"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"The modern open house sign-in experience"})]}),e.jsxs(fs,{open:i,onOpenChange:l,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"Create Open House"}),e.jsx(Hr,{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(he,{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:()=>T($=>({...$,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${S.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:()=>T($=>({...$,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${S.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"})]})]})]}),S.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:()=>T($=>({...$,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${S.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:()=>T($=>({...$,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${S.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),S.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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:()=>T($=>({...$,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${S.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:()=>T($=>({...$,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${S.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(he,{children:S.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(Ne,{value:S.property_address,onChange:$=>T(F=>({...F,property_address:$.target.value})),placeholder:S.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(he,{children:"City"}),e.jsx(Ne,{value:S.city,onChange:$=>T(F=>({...F,city:$.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"State"}),e.jsx(Ne,{value:S.state,onChange:$=>T(F=>({...F,state:$.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"ZIP"}),e.jsx(Ne,{value:S.zip,onChange:$=>T(F=>({...F,zip:$.target.value})),placeholder:"78701"})]})]}),S.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(he,{children:"Date"}),e.jsx(Ne,{type:"date",value:S.event_date,onChange:$=>T(F=>({...F,event_date:$.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Start Time"}),e.jsx(Ne,{type:"time",value:S.start_time,onChange:$=>T(F=>({...F,start_time:$.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"End Time"}),e.jsx(Ne,{type:"time",value:S.end_time,onChange:$=>T(F=>({...F,end_time:$.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Welcome Message"}),e.jsx(or,{value:S.agent_greeting,onChange:$=>T(F=>({...F,agent_greeting:$.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(he,{children:S.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:N,type:"file",accept:"image/*",onChange:A,className:"hidden"}),y?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:y,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:I,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var $;return($=N.current)==null?void 0:$.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(rv,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",S.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(G,{onClick:D,disabled:r.isPending||w,className:"w-full",children:w?"Uploading photo...":r.isPending?"Creating...":S.kind==="virtual"?"Create Virtual Open House":S.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map($=>e.jsx(ke,{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"})]})},$))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map($=>e.jsx(RRs,{openHouse:$,isExpanded:o===$.id,onToggle:()=>c(o===$.id?null:$.id),onCopyLink:()=>R($.slug||""),onToggleActive:()=>n.mutate({id:$.id,is_active:!$.is_active}),onDelete:()=>a.mutate($.id)},$.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{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(ov,{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(G,{onClick:()=>l(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function RRs({openHouse:s,isExpanded:t,onToggle:r,onCopyLink:n,onToggleActive:a,onDelete:i}){const{data:l}=RJe(t?s.id:void 0),{data:o}=mt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:R,error:$}=await V.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if($)throw $;const F=R.brokerages;return{...R,brokerage_name:(F==null?void 0:F.name)||null}},enabled:!!s.agent_id}),[c,d]=k.useState(!1),[h,m]=k.useState(!1),[x,y]=k.useState(!1),[v,w]=k.useState(!1),b=k.useRef(null),N=`https://${Bke}/${s.slug}`,S=R=>{if(!R)return"";const[$,F]=R.split(":"),z=parseInt($),Q=z>=12?"PM":"AM";return`${z>12?z-12:z||12}:${F} ${Q}`},T=()=>{if(!(l!=null&&l.length))return;const R=["First Name","Last Name","Email","Phone","Intent","Wants Market Updates","Message","Signed In"],$=l.map(X=>[X.first_name,X.last_name||"",X.email||"",X.phone||"",X.visitor_intent||"",X.wants_market_updates?"Yes":"No",(X.message||"").replace(/"/g,'""'),_s(new Date(X.created_at),"MM/dd/yyyy h:mm a")]),F=[R,...$].map(X=>X.map(Z=>`"${Z}"`).join(",")).join(` `),z=new Blob([F],{type:"text/csv"}),Q=URL.createObjectURL(z),K=document.createElement("a");K.href=Q,K.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,K.click(),URL.revokeObjectURL(Q)},A=k.useCallback(()=>{if(!b.current)return;const R=b.current.querySelector("svg");if(!R)return;const $=new XMLSerializer().serializeToString(R),F=document.createElement("canvas");F.width=1024,F.height=1024;const z=F.getContext("2d"),Q=new Image;Q.onload=()=>{z==null||z.drawImage(Q,0,0,1024,1024);const K=document.createElement("a");K.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,K.href=F.toDataURL("image/png"),K.click()},Q.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent($)))},[s.property_address]),I=k.useCallback(()=>{var fe;if(!b.current)return;const R=b.current.querySelector("svg");if(!R)return;const $=new XMLSerializer().serializeToString(R),F="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent($))),z=_s(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),Q=s.start_time?`${S(s.start_time)}${s.end_time?" – "+S(s.end_time):""}`:"",K=[s.city,s.state].filter(Boolean).join(", "),X=s.agent_greeting||"Welcome! Please sign in below.",Z=!!s.photo_url,re=!!o,le=Z||re,oe=Z&&re,ne=oe?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ie=oe?"28px":"34px",ye=oe?"0.2in 0.75in":le?"0.3in 0.75in":"0.4in 0.75in",ce=le?"0.15in":"0.3in",ve=le?"0.15in":"0.3in",be=oe?"14px 36px":"22px 44px",Ue=oe?"20px":"24px",Be=le?"0.2in":"0.35in",De=oe?"1.8in":"2.4in",Ae=le?"0.15in":"0.3in",He=oe?"140px":le?"160px":"200px",Le=oe?"16px":"24px",Ie=oe?"10px 20px":"16px 28px",Te=oe?"44px":"56px",xe="0.15in",et=window.open("","_blank");et&&(et.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${K?`
${K}${s.zip?" "+s.zip:""}
`:""}
Date
${z}
${Q?`
Time
${Q}
`:""}
${X}
${o?`
${o.avatar_url?`${o.name}`:`
${((fe=o.name)==null?void 0:fe.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
`),et.document.close(),setTimeout(()=>{et.focus(),et.print()},500))},[s,N,o]),D=async()=>{w(!0);try{const{error:R}=await V.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(R)throw R;cn({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(R){cn({title:"Failed to send",description:R.message,variant:"destructive"})}finally{w(!1)}};return e.jsxs(ke,{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(Dt,{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(Ge,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Ge,{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(bn,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Ge,{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(Ca,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Ge,{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(Di,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Ge,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(G,{variant:"ghost",size:"icon",onClick:r,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(Jf,{className:"h-4 w-4"}):e.jsx(Wi,{className:"h-4 w-4"})})]}),e.jsxs(Nr,{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(Ca,{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(fn,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),_s(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(fn,{className:"h-3 w-3"}),S(s.start_time),s.end_time?` – ${S(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(pr,{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(ov,{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(G,{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(gb,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(G,{variant:"outline",size:"sm",onClick:n,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(Ra,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>y(!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(Ec,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(G,{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(bn,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(G,{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(ov,{className:"h-3.5 w-3.5"}),"QR"]}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>m(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(oo,{className:"h-3.5 w-3.5"})}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>window.open(N,"_blank"),title:"Preview",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Qr,{className:"h-3.5 w-3.5"})}),e.jsx(G,{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(Xh,{className:"h-3.5 w-3.5"}):e.jsx(bn,{className:"h-3.5 w-3.5"})}),e.jsx(G,{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(yr,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Pe,{className:"pt-0",children:[e.jsx(fo,{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://",Bke,"/",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(G,{variant:"outline",size:"sm",onClick:T,className:"h-7 text-xs gap-1",children:[e.jsx(Ya,{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(R=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[R.first_name,R.last_name?` ${R.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[R.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:R.email}),R.phone&&e.jsx("div",{className:"text-xs",children:R.phone})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:R.visitor_intent?e.jsx(Ge,{variant:"outline",className:"text-xs capitalize",children:R.visitor_intent}):R.partial_signin?e.jsx(Ge,{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:_s(new Date(R.created_at),"h:mm a")})]},R.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(LRs,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(MRs,{openHouseId:s.id})})]}),e.jsx(fs,{open:c,onOpenChange:d,children:e.jsxs(ms,{className:"sm:max-w-sm",children:[e.jsxs(ys,{children:[e.jsx(gs,{children:"QR Code"}),e.jsx(Hr,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:b,className:"bg-white p-4 rounded-xl",children:e.jsx(GB,{value:N,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:N}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(G,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(G,{variant:"outline",className:"flex-1",onClick:I,children:[e.jsx(DR,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(G,{variant:"default",className:"w-full",onClick:D,disabled:v,children:[e.jsx(Vs,{className:"h-4 w-4 mr-2"}),v?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(ERs,{open:h,onOpenChange:m,openHouse:s}),s.kind==="virtual"&&e.jsx(PRs,{open:x,onOpenChange:y,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function ORs(){const{slug:s}=Ki();return s?e.jsx(Mst,{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 Ext({photoUrl:s,videoUrl:t,onPhotoChange:r,onVideoChange:n,contactId:a}){const{user:i}=js(),l=Yb(),o=k.useRef(null),c=k.useRef(null),[d,h]=k.useState(!1),[m,x]=k.useState(!1),[y,v]=k.useState(0),w=async N=>{if(i){h(!0);try{const S=N.name.split(".").pop()||"jpg",T=`${i.id}/card-${Date.now()}.${S}`,{error:A}=await V.storage.from("listing-photos").upload(T,N);if(A)throw A;const{data:{publicUrl:I}}=V.storage.from("listing-photos").getPublicUrl(T);r(I),ue.success("Photo uploaded")}catch(S){ue.error(S.message||"Failed to upload photo")}finally{h(!1)}}},b=async N=>{if(i){if(N.size>500*1024*1024){ue.error("Video must be under 500MB");return}x(!0),v(0);try{const{videoId:S,libraryId:T}=await h5(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:I}=await m5(S);await new Promise(($,F)=>{const z=new XMLHttpRequest;z.upload.addEventListener("progress",Q=>{Q.lengthComputable&&v(Math.round(Q.loaded/Q.total*100))}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?$():F(new Error("Upload failed"))}),z.addEventListener("error",()=>F(new Error("Upload failed"))),z.open("PUT",A),z.setRequestHeader("AccessKey",I),z.send(N)});const D=`https://iframe.mediadelivery.net/embed/${T}/${S}`;n(D);const R=parseFloat((N.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:S,playback_url:`https://iframe.mediadelivery.net/play/${T}/${S}`,file_size_mb:R,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ue.success("Video uploaded & added to your library")}catch(S){ue.error(S.message||"Failed to upload video")}finally{x(!1),v(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(he,{children:"Media (optional)"}),e.jsxs(On,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Rn,{className:"grid w-full grid-cols-2",children:[e.jsxs(Kt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(ml,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Kt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(ts,{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(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(vr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var N;return(N=o.current)==null?void 0:N.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(es,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Qf,{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:N=>{var T;const S=(T=N.target.files)==null?void 0:T[0];S&&w(S),N.target.value=""}})]}),e.jsxs(ts,{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(G,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(vr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var N;return(N=c.current)==null?void 0:N.click()},disabled:m,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:m?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(es,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",y,"%"]}),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:`${y}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a video (max 500MB)"})]})}),!t&&!m&&e.jsx("div",{className:"mt-2",children:e.jsx(REe,{contactId:a,onVideoReady:N=>n(N)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:N=>{var T;const S=(T=N.target.files)==null?void 0:T[0];S&&b(S),N.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 FRs=[{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:"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 BRs({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:FRs.map((t,r)=>e.jsxs(Sr.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:r*.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 LL={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."},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 CVe({initialOpen:s,initialCardType:t,initialContactId:r,initialRecipientName:n,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=js(),c=Xt(),[d,h]=k.useState(!1),[m,x]=k.useState("type"),[y,v]=k.useState(""),[w,b]=k.useState(null),[N,S]=k.useState(!1),[T,A]=k.useState("home_anniversary"),[I,D]=k.useState(""),[R,$]=k.useState(""),[F,z]=k.useState(""),[Q,K]=k.useState(""),[X,Z]=k.useState("elegant"),[re,le]=k.useState(null),[oe,ne]=k.useState(null),ie=k.useState(!1);!ie[0]&&s&&t&&(ie[1](!0),h(!0),A(t),r&&b(r),n&&D(n),a&&$(a),i&&z(i),x(n?"details":"contact"));const{data:ye}=mt({queryKey:["contacts-for-card",o==null?void 0:o.id,y],queryFn:async()=>{let Ie=V.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);y&&(Ie=Ie.or(`first_name.ilike.%${y}%,last_name.ilike.%${y}%`));const{data:Te,error:xe}=await Ie;if(xe)throw xe;return Te},enabled:!!(o!=null&&o.id)&&d}),{data:ce}=mt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Ie,error:Te}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(Te)throw Te;return Ie},enabled:!!(o!=null&&o.id)}),ve=Ie=>{b(Ie.id),D(`${Ie.first_name}${Ie.last_name?" "+Ie.last_name:""}`),$([Ie.address,Ie.city,Ie.state].filter(Boolean).join(", ")),z(Ie.home_anniversary||""),x("details")},be=Ie=>{A(Ie),x("contact")},Ue=async()=>{var Ie;if(!(!o||!ce)){S(!0);try{const Te={owner_user_id:o.id,contact_id:w,card_type:T,template:X,recipient_name:I,property_address:R||null,home_anniversary_date:F||null,custom_message:Q||null,property_photo_url:re||null,video_url:oe||null,agent_name:ce.name||"Agent",agent_photo_url:ce.avatar_url,agent_phone:ce.phone,agent_email:ce.email,agent_brokerage:((Ie=ce.brokerage)==null?void 0:Ie.name)||null},{error:xe}=await V.from("sendable_cards").insert(Te);if(xe)throw xe;ue.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Be()}catch(Te){ue.error(Te.message||"Failed to create card")}finally{S(!1)}}},Be=()=>{h(!1),x("type"),A("home_anniversary"),v(""),b(null),D(""),$(""),z(""),K(""),Z("elegant"),le(null),ne(null)},De={home_anniversary:"Home 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=LL[T],He=T==="home_anniversary",Le=["home_anniversary","just_listed","just_sold"].includes(T);return e.jsxs(fs,{open:d,onOpenChange:Ie=>{Ie?h(!0):(Be(),l==null||l(!1))},children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{className:"gap-2",children:[e.jsx($s,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:m==="type"?"What type of card?":m==="contact"?`${De[T]} — Choose a Contact`:`${De[T]} — Customize`})}),m==="type"&&e.jsx(BRs,{onSelect:be}),m==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>x("type"),children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search contacts...",value:y,onChange:Ie=>v(Ie.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[ye==null?void 0:ye.map(Ie=>e.jsxs("button",{onClick:()=>ve(Ie),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(Di,{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:[Ie.first_name," ",Ie.last_name]}),Ie.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(En,{className:"h-3 w-3"}),Ie.address]})]}),Ie.home_anniversary&&T==="home_anniversary"&&e.jsx("span",{className:"text-[10px] text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0",children:"Anniversary set"})]},Ie.id)),(ye==null?void 0:ye.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(G,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{x("details")},children:"Skip — enter details manually"})})]}),m==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>x("contact"),children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Recipient Name"}),e.jsx(Ne,{value:I,onChange:Ie=>D(Ie.target.value),placeholder:"John & Jane Smith"})]}),Le&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Address"}),e.jsx(Ne,{value:R,onChange:Ie=>$(Ie.target.value),placeholder:"123 Main St, Austin, TX"})]}),He&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Home Anniversary Date"}),e.jsx(Ne,{type:"date",value:F,onChange:Ie=>z(Ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Personal Message (optional)"}),e.jsx(or,{value:Q,onChange:Ie=>K(Ie.target.value),placeholder:Ae.defaultMessage,rows:3})]}),e.jsx(Ext,{photoUrl:re,videoUrl:oe,onPhotoChange:le,onVideoChange:ne,contactId:w}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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:Ie,label:Te,gradient:xe})=>e.jsxs("button",{onClick:()=>Z(Ie),className:`p-2 rounded-lg border-2 transition-all text-center ${X===Ie?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${xe}`}),e.jsx("span",{className:"text-[10px] font-medium",children:Te})]},Ie))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(G,{variant:"outline",onClick:()=>x("contact"),className:"flex-1",children:"Back"}),e.jsx(G,{onClick:Ue,disabled:!I||N,className:"flex-1 gap-2",children:N?"Creating...":"Create Card"})]})]})]})]})}const zRs={home_anniversary:"Home 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 $Rs({card:s}){js();const{isGmailConnected:t}=Eh(),r=Xt(),[n,a]=k.useState(!1),[i,l]=k.useState("");k.useEffect(()=>{n&&s.contact_id&&!i&&V.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:v})=>{v!=null&&v.email&&l(v.email)})},[n,s.contact_id]);const o={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[c,d]=k.useState(o[s.card_type]||`A Special Card for ${s.recipient_name}!`),[h,m]=k.useState(""),x=`https://cardstudio.relevelup.com/c/${s.share_token}`,y=Ct({mutationFn:async()=>{var S;if(!i)throw new Error("Recipient email is required");const v=`
${h?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:w}=await V.auth.getSession(),b=(S=w==null?void 0:w.session)==null?void 0:S.access_token,N=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`},body:JSON.stringify({to:i,subject:c,body:v,contactId:s.contact_id||void 0})});if(!N.ok){const T=await N.json();throw new Error(T.error||"Failed to send")}return N.json()},onSuccess:async()=>{await V.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),r.invalidateQueries({queryKey:["sendable-cards"]}),ue.success(`Card sent to ${i}!`),a(!1)},onError:v=>{ue.error(v.message||"Failed to send email")}});return t?e.jsxs(fs,{open:n,onOpenChange:a,children:[e.jsx(vi,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(en,{className:"h-3 w-3"})})}),e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Send Card via Gmail"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"To"}),e.jsx(Ne,{type:"email",value:i,onChange:v=>l(v.target.value),placeholder:"recipient@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Subject"}),e.jsx(Ne,{value:c,onChange:v=>d(v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Personal Note (optional)"}),e.jsx(or,{value:h,onChange:v=>m(v.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:["The email will include a beautiful button linking to your card at:",e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:x})]}),e.jsx(G,{onClick:()=>y.mutate(),disabled:!i||y.isPending,className:"w-full gap-2",children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs opacity-50 cursor-not-allowed",title:"Connect Gmail in Settings to send cards via email",disabled:!0,children:e.jsx(en,{className:"h-3 w-3"})})}function URs({card:s}){const t=Xt(),[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(s.recipient_name),[c,d]=k.useState(s.property_address||""),[h,m]=k.useState(s.home_anniversary_date||""),[x,y]=k.useState(s.custom_message||""),[v,w]=k.useState(s.template),[b,N]=k.useState(s.property_photo_url),[S,T]=k.useState(s.video_url||null),A=D=>{D&&(o(s.recipient_name),d(s.property_address||""),m(s.home_anniversary_date||""),y(s.custom_message||""),w(s.template),N(s.property_photo_url),T(s.video_url||null)),n(D)},I=async()=>{if(!l.trim()){ue.error("Recipient name is required");return}i(!0);try{const{error:D}=await V.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:h||null,custom_message:x.trim()||null,template:v,property_photo_url:b||null,video_url:S||null}).eq("id",s.id);if(D)throw D;t.invalidateQueries({queryKey:["sendable-cards"]}),ue.success("Card updated"),n(!1)}catch(D){ue.error(D.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(fs,{open:r,onOpenChange:A,children:[e.jsx(vi,{asChild:!0,children:e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Ea,{className:"h-3 w-3"})})}),e.jsxs(ms,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Recipient Name"}),e.jsx(Ne,{value:l,onChange:D=>o(D.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Property Address"}),e.jsx(Ne,{value:c,onChange:D=>d(D.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Home Anniversary Date"}),e.jsx(Ne,{type:"date",value:h,onChange:D=>m(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Personal Message (optional)"}),e.jsx(or,{value:x,onChange:D=>y(D.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(Ext,{photoUrl:b,videoUrl:S,onPhotoChange:N,onVideoChange:T,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(D=>e.jsxs("button",{onClick:()=>w(D),className:`p-3 rounded-lg border-2 transition-all text-center ${v===D?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${D==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":D==="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:D})]},D))})]}),e.jsx(G,{onClick:I,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function qRs(){const{user:s}=js(),t=Xt(),[r,n]=k.useState(""),[a,i]=Ac(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),h=a.get("date"),m=!!l,{data:x,isLoading:y}=mt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:T,error:A}=await V.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return T},enabled:!!(s!=null&&s.id)}),v=Ct({mutationFn:async T=>{const{error:A}=await V.from("sendable_cards").delete().eq("id",T);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ue.success("Card deleted")}}),w=T=>{const A=`https://cardstudio.relevelup.com/c/${T}`;navigator.clipboard.writeText(A),ue.success("Share link copied!")},b=x==null?void 0:x.filter(T=>{var A;return!r||T.recipient_name.toLowerCase().includes(r.toLowerCase())||((A=T.property_address)==null?void 0:A.toLowerCase().includes(r.toLowerCase()))}),N={elegant:"Elegant",bold:"Bold",warm:"Warm"},S={home_anniversary:"Home 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(ws,{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(CVe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:h||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(yn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Ne,{placeholder:"Search cards...",value:r,onChange:T=>n(T.target.value),className:"pl-9"})]}),y?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(T=>e.jsx(ke,{className:"animate-pulse",children:e.jsxs(Pe,{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"})]})},T))}):b!=null&&b.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(T=>e.jsxs(ke,{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 ${T.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":T.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:[T.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"})]}),T.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%)]"})]}),T.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:T.card_type==="home_anniversary"?"🏡":T.card_type==="birthday"?"🎂":T.card_type==="just_sold"?"🎉":T.card_type==="just_listed"?"🏠":T.card_type==="thank_you"?"💐":T.card_type==="congratulations"?"🏆":T.card_type==="holiday"?"🎄":T.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${T.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:S[T.card_type]||T.card_type}),e.jsx("p",{className:`font-semibold text-base ${T.template==="bold"?"text-white":"text-foreground"}`,children:T.recipient_name}),T.property_address&&e.jsx("p",{className:`text-xs mt-1 ${T.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:T.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Ge,{variant:T.template==="bold"?"outline":"secondary",className:`text-[10px] ${T.template==="bold"?"border-white/30 text-white/80":""}`,children:N[T.template]||T.template})})]}),e.jsxs(Pe,{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(bn,{className:"h-3 w-3"}),T.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:rl(new Date(T.created_at),{addSuffix:!0})})]}),T.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",_s(new Date(T.sent_at),"MMM d, yyyy")," via ",T.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(G,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>w(T.share_token),children:[e.jsx(Ra,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(URs,{card:T}),e.jsx($Rs,{card:T}),e.jsx(G,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${T.share_token}`,"_blank"),children:e.jsx(Qr,{className:"h-3 w-3"})}),e.jsx(G,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>v.mutate(T.id),children:e.jsx(yr,{className:"h-3 w-3"})})]})]})]},T.id))}):e.jsx(ke,{className:"border-dashed",children:e.jsxs(Pe,{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(CVe,{initialOpen:m,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:h||void 0,onOpenChange:()=>i({})})]})})]})})}const Z$=[{id:"mls",label:"MLS Description",tag:"Standard",icon:En,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:Zh,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:Ku,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:sv,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:yR,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:bo,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:yu,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:Jd,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:Jh,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:bu,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:fn,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:hd,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:fR,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:eu,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:Jr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:gh,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:W4,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:Zh,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:LR,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:Ca,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:NR,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:pr,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:aR,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:Ca,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function VRs(){var fa,go,wo,co,ia,Ji,il,bi,eo,no,ba;const{user:s}=js(),[t,r]=k.useState(""),[n,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(""),[d,h]=k.useState([]),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState(""),[T,A]=k.useState(""),[I,D]=k.useState(""),[R,$]=k.useState(""),[F,z]=k.useState(null),[Q,K]=k.useState(""),[X,Z]=k.useState(""),[re,le]=k.useState(""),[oe,ne]=k.useState(""),[ie,ye]=k.useState(""),[ce,ve]=k.useState(""),[be,Ue]=k.useState(""),[Be,De]=k.useState(""),[Ae,He]=k.useState(""),[Le,Ie]=k.useState(""),[Te,xe]=k.useState(""),[et,fe]=k.useState(""),[it,Oe]=k.useState(""),[Ye,We]=k.useState(""),[_e,Re]=k.useState(""),[tt,Ke]=k.useState(""),[Ze,lt]=k.useState(""),[xt,Xe]=k.useState(""),[Je,jt]=k.useState(""),[ns,Ns]=k.useState(""),[Ys,rs]=k.useState(""),[bt,cs]=k.useState(""),[yt,is]=k.useState(""),[Bs,ps]=k.useState(""),[lr,kr]=k.useState(""),[Lr,qr]=k.useState("listing"),[Ur,Mr]=k.useState("mls"),[Cr,Xr]=k.useState({}),[Ln,Zs]=k.useState({}),[Yr,ss]=k.useState(!1),[ta,nn]=k.useState(!1),hr=ir=>{qr(ir);const ra=Z$.find(Ci=>Ci.category===ir);ra&&Mr(ra.id)},{data:Pr}=mt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Yr,queryFn:async()=>{const{data:ir,error:ra}=await V.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(ra)throw ra;return ir||[]}}),Qn=()=>{const ir=o.trim();ir&&(l(ra=>[...ra,ir]),c(""))},Gt=ir=>l(ra=>ra.filter((Ci,qo)=>qo!==ir)),gr=ir=>{var ra,Ci,qo,Xo;z(ir.id),r(ir.property_address||""),D(ir.city||""),$(ir.state||""),S(((ra=ir.price)==null?void 0:ra.toString())||""),x(((Ci=ir.bedrooms)==null?void 0:Ci.toString())||""),v(((qo=ir.bathrooms)==null?void 0:qo.toString())||""),b(((Xo=ir.square_footage)==null?void 0:Xo.toString())||""),A(ir.property_type||""),a(ir.description||""),ss(!1),ue.success("Listing imported")},zt=async ir=>{if(!(!ir.target.files||!(s!=null&&s.id))){nn(!0);try{const ra=[];for(const Ci of Array.from(ir.target.files).slice(0,10)){const qo=`${s.id}/${Date.now()}-${Ci.name.replace(/[^\w.-]/g,"_")}`,{error:Xo}=await V.storage.from("listing-photos").upload(qo,Ci,{upsert:!1});if(Xo){console.error(Xo);continue}const{data:ol}=V.storage.from("listing-photos").getPublicUrl(qo);ra.push(ol.publicUrl)}h(Ci=>[...Ci,...ra]),ra.length&&ue.success(`${ra.length} photo(s) uploaded`)}catch(ra){ue.error(ra.message||"Photo upload failed")}finally{nn(!1)}}},Se=Z$.find(ir=>ir.id===Ur),ze=async ir=>{var Ci,qo,Xo;const ra=Z$.find(ol=>ol.id===ir);if(!t.trim()&&!n.trim()&&i.length===0){ue.error("Add a property address, MLS remarks, or features first");return}if((Ci=ra.extras)!=null&&Ci.includes("openHouse")&&(!Q||!X||!re)){ue.error("Add the open house date, start and end time");return}if((qo=ra.extras)!=null&&qo.includes("priceImprovement")&&(!oe||!ie)){ue.error("Add previous and new price");return}if((Xo=ra.extras)!=null&&Xo.includes("sold")&&!ce){ue.error("Add the sold price");return}Mr(ir),Zs(ol=>({...ol,[ir]:!0}));try{const{data:ol,error:Kc}=await V.functions.invoke("listing-studio-generate",{body:{copyType:ir,propertyAddress:t,mlsRemarks:n,features:i,photoUrls:d,listingId:F,bedrooms:m?Number(m):null,bathrooms:y?Number(y):null,squareFootage:w?Number(w):null,price:N?Number(N):null,propertyType:T||null,city:I||null,state:R||null,openHouseDate:Q||null,openHouseStart:X||null,openHouseEnd:re||null,previousPrice:oe?Number(oe):null,newPrice:ie?Number(ie):null,soldPrice:ce?Number(ce):null,soldDate:be||null,comingSoonDate:Be||null,builderName:Ae||null,yearBuilt:Le?Number(Le):null,warrantyInfo:Te||null,monthlyRent:et?Number(et):null,capRate:it||null,occupancy:Ye||null,daysOnMarket:_e?Number(_e):null,offerCount:tt?Number(tt):null,originalListPrice:Ze?Number(Ze):null,soldDaysOnMarket:xt?Number(xt):null,commissionOffered:Je||null,refreshments:ns||null,vibe:Ys||null,neighborhoodHighlights:bt||null,agentName:yt||null,agentBrokerage:Bs||null,agentContact:lr||null}});if(Kc)throw Kc;if(ol!=null&&ol.error)throw new Error(ol.error);Xr(nu=>({...nu,[ir]:ol.content}))}catch(ol){ue.error(ol.message||"Generation failed")}finally{Zs(ol=>({...ol,[ir]:!1}))}},st=ir=>{navigator.clipboard.writeText(ir),ue.success("Copied to clipboard")},gt=Se.icon,At=Cr[Ur]?Cr[Ur].trim().split(/\s+/).length:0,Ft=ir=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Z$.filter(ra=>ra.category===ir).map(ra=>{const Ci=ra.icon,qo=Ur===ra.id,Xo=!!Cr[ra.id];return e.jsxs("button",{onClick:()=>Mr(ra.id),className:It("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",qo?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[qo&&e.jsx("div",{className:It("absolute inset-0 opacity-[0.07] bg-gradient-to-br",ra.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:It("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",ra.accent),children:e.jsx(Ci,{className:"h-4 w-4"})}),Xo&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(Kn,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:ra.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ra.desc})]})]})]},ra.id)})}),Wt=(fa=Se.extras)==null?void 0:fa.includes("openHouse"),Vt=(go=Se.extras)==null?void 0:go.includes("priceImprovement"),Jt=(wo=Se.extras)==null?void 0:wo.includes("sold"),qs=(co=Se.extras)==null?void 0:co.includes("comingSoon"),Cs=(ia=Se.extras)==null?void 0:ia.includes("newConstruction"),xr=(Ji=Se.extras)==null?void 0:Ji.includes("investment"),Wr=(il=Se.extras)==null?void 0:il.includes("underContract"),tn=(bi=Se.extras)==null?void 0:bi.includes("brokerOpen"),Rr=(eo=Se.extras)==null?void 0:eo.includes("vibe"),sn=(no=Se.extras)==null?void 0:no.includes("neighborhood"),rn=(ba=Se.extras)==null?void 0:ba.includes("signoff"),un=Wt||Vt||Jt||qs||Cs||xr||Wr||tn||Rr||sn||rn;return e.jsx(ws,{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(jr,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(fs,{open:Yr,onOpenChange:ss,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(ln,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(ms,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsx(gs,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Pr!=null&&Pr.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Pr==null?void 0:Pr.map(ir=>e.jsxs("button",{onClick:()=>gr(ir),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:ir.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[ir.city,ir.state].filter(Boolean).join(", "),ir.price?` · $${Number(ir.price).toLocaleString()}`:"",ir.bedrooms?` · ${ir.bedrooms}bd`:"",ir.bathrooms?` · ${ir.bathrooms}ba`:""]})]},ir.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(ke,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Pe,{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(En,{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(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(Ne,{value:t,onChange:ir=>r(ir.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(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(Ne,{value:I,onChange:ir=>D(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(Ne,{value:R,onChange:ir=>$(ir.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(Ne,{type:"number",value:N,onChange:ir=>S(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(Ne,{value:T,onChange:ir=>A(ir.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(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(Ne,{type:"number",value:m,onChange:ir=>x(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(Ne,{type:"number",step:"0.5",value:y,onChange:ir=>v(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(Ne,{type:"number",value:w,onChange:ir=>b(ir.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(or,{value:n,onChange:ir=>a(ir.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(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:o,onChange:ir=>c(ir.target.value),onKeyDown:ir=>ir.key==="Enter"&&(ir.preventDefault(),Qn()),placeholder:"e.g. Quartz countertops"}),e.jsx(G,{type:"button",size:"icon",variant:"secondary",onClick:Qn,children:e.jsx($s,{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((ir,ra)=>e.jsxs(Ge,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[ir,e.jsx("button",{onClick:()=>Gt(ra),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(vr,{className:"h-3 w-3"})})]},ra))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{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(rv,{className:"h-4 w-4"}),ta?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:zt,disabled:ta,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((ir,ra)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:ir,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>h(Ci=>Ci.filter((qo,Xo)=>Xo!==ra)),className:"absolute top-1 right-1 bg-background/90 backdrop-blur rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(vr,{className:"h-3 w-3"})})]},ra))})]}),un&&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(jr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Se.label]})]}),Wt&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(Ne,{type:"date",value:Q,onChange:ir=>K(ir.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(Ne,{type:"time",value:X,onChange:ir=>Z(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(Ne,{type:"time",value:re,onChange:ir=>le(ir.target.value)})]})]})]}),Vt&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(Ne,{type:"number",value:oe,onChange:ir=>ne(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(Ne,{type:"number",value:ie,onChange:ir=>ye(ir.target.value),placeholder:"$"})]})]}),Jt&&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(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(Ne,{type:"number",value:ce,onChange:ir=>ve(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(Ne,{type:"date",value:be,onChange:ir=>Ue(ir.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(Ne,{type:"number",value:Ze,onChange:ir=>lt(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(Ne,{type:"number",value:xt,onChange:ir=>Xe(ir.target.value)})]})]})]}),qs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(Ne,{type:"date",value:Be,onChange:ir=>De(ir.target.value)})]}),Cs&&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(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(Ne,{value:Ae,onChange:ir=>He(ir.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(Ne,{type:"number",value:Le,onChange:ir=>Ie(ir.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(Ne,{value:Te,onChange:ir=>xe(ir.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),xr&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(Ne,{type:"number",value:et,onChange:ir=>fe(ir.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(Ne,{value:it,onChange:ir=>Oe(ir.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Ye,onChange:ir=>We(ir.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"})]})]})]}),Wr&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(Ne,{type:"number",value:_e,onChange:ir=>Re(ir.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(Ne,{type:"number",value:tt,onChange:ir=>Ke(ir.target.value),placeholder:"e.g. 5"})]})]}),tn&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(Ne,{value:Je,onChange:ir=>jt(ir.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(Ne,{value:ns,onChange:ir=>Ns(ir.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Rr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:Ys,onChange:ir=>rs(ir.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"})]})]}),sn&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(or,{value:bt,onChange:ir=>cs(ir.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),rn&&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(he,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(Ne,{value:yt,onChange:ir=>is(ir.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(Ne,{value:Bs,onChange:ir=>ps(ir.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(Ne,{value:lr,onChange:ir=>kr(ir.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:ln},{key:"social",label:"Social Media",icon:Jd},{key:"video",label:"Video Scripts",icon:Jr},{key:"email",label:"Email Marketing",icon:Vs}].map(ir=>{const ra=ir.icon,Ci=Lr===ir.key;return e.jsxs("button",{onClick:()=>hr(ir.key),className:It("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",Ci?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(ra,{className:"h-4 w-4"}),ir.label]},ir.key)})}),Ft(Lr),e.jsxs(ke,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:It("h-1 bg-gradient-to-r",Se.accent)}),e.jsxs(Pe,{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:It("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Se.accent),children:e.jsx(gt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Se.label,e.jsx(Ge,{variant:"outline",className:"text-[10px] font-normal",children:Se.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Cr[Ur]?`${At} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[Cr[Ur]&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>st(Cr[Ur]),children:[e.jsx(Ra,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(G,{onClick:()=>ze(Ur),disabled:Ln[Ur],className:It("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Se.accent),size:"sm",children:Ln[Ur]?e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):Cr[Ur]?e.jsxs(e.Fragment,{children:[e.jsx(Mi,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zx,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),Cr[Ur]?e.jsx(or,{value:Cr[Ur],onChange:ir=>Xr(ra=>({...ra,[Ur]:ir.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:It("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Se.accent),children:e.jsx(Zx,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Se.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 vD({delay:s,x:t,y:r,size:n}){return e.jsx(Sr.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:r,width:n,height:n},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 HRs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,y=LL[t];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-white dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-4 overflow-hidden relative",children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx(Sr.div,{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-blue-100/40 to-slate-100/20 blur-3xl",animate:{scale:[1,1.1,1],rotate:[0,5,0]},transition:{duration:8,repeat:1/0,ease:"easeInOut"}}),e.jsx(Sr.div,{className:"absolute -bottom-20 -left-20 w-64 h-64 rounded-full bg-gradient-to-tr from-slate-200/30 to-blue-100/20 blur-3xl",animate:{scale:[1,1.15,1],rotate:[0,-5,0]},transition:{duration:10,repeat:1/0,ease:"easeInOut"}}),e.jsx(vD,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(vD,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(vD,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(vD,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(vD,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,ease:"easeOut"},children:[e.jsxs(Sr.div,{className:"bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] overflow-hidden border border-slate-200/60 dark:border-slate-700/50",initial:{scale:.95},animate:{scale:1},transition:{duration:.6,delay:.2},children:[e.jsx("div",{className:"relative h-2 bg-gradient-to-r from-slate-200 via-blue-300 to-slate-200 dark:from-slate-700 dark:via-blue-500 dark:to-slate-700 overflow-hidden",children:e.jsx(Sr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(Sr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-slate-100 to-blue-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center shadow-lg relative",initial:{scale:0,rotate:-10},animate:{scale:1,rotate:0},transition:{duration:.5,delay:.4,type:"spring",stiffness:200},children:[e.jsx(Sr.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:y.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Sr.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:e.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[a," ",a===1?"Year":"Years"]})}),e.jsx(Sr.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:y.title[0]}),y.title[1]&&e.jsx(Sr.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:y.title[1]}),e.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),e.jsx(Sr.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),m&&e.jsx(Sr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Sr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Sr.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||y.defaultMessage}),e.jsxs(Sr.div,{className:"border-t border-slate-100 dark:border-slate-800 pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),h&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.p,{className:"text-center text-[10px] text-slate-400 dark:text-slate-600 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function Mbe({delay:s,x:t,y:r,color:n,size:a}){return e.jsx(Sr.div,{className:`absolute rounded-full blur-2xl ${n}`,style:{left:t,top:r,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 bD({delay:s,x:t,y:r}){return e.jsx(Sr.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:r},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 TVe={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 GRs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,y=LL[t],v=TVe[t]||TVe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${v.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(Mbe,{delay:0,x:"10%",y:"10%",color:v.orbs[0],size:200}),e.jsx(Mbe,{delay:1,x:"70%",y:"60%",color:v.orbs[1],size:180}),e.jsx(Mbe,{delay:2,x:"50%",y:"20%",color:v.orbs[2],size:150}),e.jsx(bD,{delay:0,x:"20%",y:"25%"}),e.jsx(bD,{delay:.8,x:"75%",y:"15%"}),e.jsx(bD,{delay:1.6,x:"85%",y:"65%"}),e.jsx(bD,{delay:2.4,x:"10%",y:"75%"}),e.jsx(bD,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.7,ease:"easeOut"},children:[e.jsxs(Sr.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsx(Sr.div,{className:"absolute -inset-[1px] rounded-3xl bg-gradient-to-r from-violet-500 via-fuchsia-500 to-violet-500 opacity-50",animate:{backgroundPosition:["0% 50%","100% 50%","0% 50%"]},transition:{duration:4,repeat:1/0,ease:"linear"},style:{backgroundSize:"200% 200%"}}),e.jsxs("div",{className:"relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl px-8 py-10 text-center m-[1px]",children:[e.jsxs(Sr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-2xl shadow-violet-500/40 relative",initial:{scale:0,rotate:-20},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:200},children:[e.jsx(Sr.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:y.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Sr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/10 border border-white/15 backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(Sr.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:a===1?"Year":"Years"})]}),e.jsx(Sr.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:y.title[0]}),y.title[1]&&e.jsx(Sr.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:y.title[1]}),e.jsx(Sr.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:y.emojis.slice(0,3).join("")}),e.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(En,{className:"h-3.5 w-3.5"}),n]})]}),m&&e.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Sr.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||y.defaultMessage})}),e.jsxs(Sr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),h&&e.jsx("p",{className:"text-xs text-violet-300/60",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.p,{className:"text-center text-[10px] text-violet-400/40 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function WRs({emoji:s,delay:t,x:r,duration:n}){return e.jsx(Sr.div,{className:"absolute text-2xl pointer-events-none",style:{left:r,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:n,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const EVe={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 KRs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,y=LL[t],v=EVe[t]||EVe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${v.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[y.emojis.map((w,b)=>e.jsx(WRs,{emoji:w,delay:b*1.2,x:`${15+b*14}%`,duration:5+b%3},b)),e.jsx(Sr.div,{className:"absolute top-1/4 left-1/2 -translate-x-1/2 w-96 h-96 bg-gradient-to-r from-amber-200/30 to-rose-200/30 rounded-full blur-[100px]",animate:{scale:[1,1.2,1],opacity:[.3,.5,.3]},transition:{duration:6,repeat:1/0,ease:"easeInOut"}}),e.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[e.jsxs(Sr.div,{className:"bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(251,146,60,0.2)] overflow-hidden border border-amber-100",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[e.jsxs(Sr.div,{className:`h-28 bg-gradient-to-r ${v.header} relative overflow-hidden`,children:[e.jsx(Sr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}}),e.jsx(Sr.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:y.emojis[0]}),e.jsx(Sr.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:y.emojis[1]}),e.jsx(Sr.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:y.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Sr.div,{className:"mx-auto mb-4 h-20 w-20 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-white relative",initial:{scale:0},animate:{scale:1},transition:{delay:.4,type:"spring",stiffness:300},children:e.jsx(Sr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:y.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Sr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${v.accent}`,children:[e.jsx(Sr.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:a}),e.jsx("span",{className:"text-sm font-semibold",children:a===1?"year":"wonderful years"})]})}),e.jsxs(Sr.h1,{className:`text-3xl font-bold ${v.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[y.title.join(" ")," ",y.emojis[4]]}),e.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${v.text} mb-1`,children:r}),n&&e.jsxs("p",{className:`text-sm ${v.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(Ca,{className:"h-3 w-3"}),n]})]}),m&&e.jsx(Sr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Sr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Sr.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${v.text} leading-relaxed italic`,children:['"',i||y.defaultMessage,'"']})}),e.jsxs(Sr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[o?e.jsx(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${v.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 ${v.accent}`,children:l}),h&&e.jsx("p",{className:`text-xs ${v.text} opacity-60`,children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${v.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${v.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(Sr.p,{className:"text-center text-[10px] text-amber-400 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function X$({delay:s,x:t,y:r,size:n,color:a}){return e.jsx(Sr.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:r,width:n,height:n},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 Ibe({delay:s,x:t,y:r,size:n}){return e.jsx(Sr.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:r,width:n,height:n},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 AVe={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 YRs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,y=LL[t],v=AVe[t]||AVe.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(X$,{delay:0,x:"5%",y:"10%",size:300,color:v.mesh[0]}),e.jsx(X$,{delay:2,x:"60%",y:"50%",size:250,color:v.mesh[1]}),e.jsx(X$,{delay:4,x:"30%",y:"70%",size:200,color:v.mesh[2]}),e.jsx(X$,{delay:1,x:"80%",y:"15%",size:180,color:v.mesh[0]}),e.jsx(Ibe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(Ibe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(Ibe,{delay:6,x:"40%",y:"10%",size:80}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`}}),e.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.8,ease:[.16,1,.3,1]},children:[e.jsxs(Sr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${v.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(Sr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:4,repeat:1/0,repeatDelay:3,ease:"easeInOut"}})}),e.jsxs("div",{className:"px-8 py-10 text-center",children:[e.jsxs(Sr.div,{className:"mx-auto mb-6 h-24 w-24 rounded-3xl bg-white/[0.08] backdrop-blur-xl border border-white/[0.15] flex items-center justify-center relative",initial:{scale:0,rotate:-15},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:180},children:[e.jsx(Sr.div,{className:"absolute -inset-1 rounded-3xl border border-white/[0.08]",animate:{scale:[1,1.1,1],opacity:[.3,0,.3]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}),e.jsx(Sr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:y.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Sr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/[0.06] border border-white/[0.1] backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[e.jsx(Sr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${v.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Sr.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:y.title[0]}),y.title[1]&&e.jsx(Sr.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:y.title[1]}),e.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",n]})]}),e.jsx(Sr.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),m&&e.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:m,alt:"Property",className:"w-full h-48 object-cover"})}),x&&e.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Sr.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||y.defaultMessage,'"']})}),e.jsxs(Sr.div,{className:"border-t border-white/[0.06] pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[o?e.jsx(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),h&&e.jsx("p",{className:"text-xs text-white/30",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Sr.p,{className:"text-center text-[10px] text-white/20 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function Lbe({delay:s,x:t,angle:r,color:n}){return e.jsx(Sr.div,{className:`absolute h-[400px] w-[1px] ${n} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${r}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function Q$({delay:s,x:t}){return e.jsx(Sr.div,{className:"absolute w-1 h-1 rounded-full bg-amber-400/60",style:{left:t,bottom:"20%"},animate:{y:[0,-200,-400],x:[0,15,-10],opacity:[0,.8,0],scale:[0,1.5,0]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeOut"}})}const MVe={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 ZRs(s){const{cardType:t,recipientName:r,propertyAddress:n,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:h,propertyPhotoUrl:m,videoUrl:x}=s,y=LL[t],v=MVe[t]||MVe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${v.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(Lbe,{delay:0,x:"20%",angle:15,color:v.stripe}),e.jsx(Lbe,{delay:2,x:"75%",angle:-12,color:v.stripe}),e.jsx(Lbe,{delay:4,x:"50%",angle:5,color:v.stripe}),e.jsx(Q$,{delay:0,x:"30%"}),e.jsx(Q$,{delay:1.5,x:"60%"}),e.jsx(Q$,{delay:3,x:"45%"}),e.jsx(Q$,{delay:.7,x:"75%"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.015] mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.7' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`}}),e.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Sr.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:e.jsxs("div",{className:"px-8 py-12 text-center",children:[e.jsx(Sr.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:e.jsx(Sr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${v.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:y.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Sr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Sr.span,{className:`text-6xl font-black bg-gradient-to-r ${v.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(Sr.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:y.title[0]})}),y.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Sr.h2,{className:`text-5xl font-black bg-gradient-to-r ${v.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:y.title[1]})}),e.jsxs(Sr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",n]})]}),e.jsxs(Sr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Sr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-r from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"right"}}),e.jsx(Sr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Sr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),m&&e.jsxs(Sr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:m,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"})]}),x&&e.jsx(Sr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:e.jsx("iframe",{src:`${x}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Sr.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||y.defaultMessage}),e.jsxs(Sr.div,{className:"pt-6 border-t border-white/[0.04]",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:1.6,duration:.6},children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[o?e.jsx(Sr.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${v.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}),h&&e.jsx("p",{className:"text-[11px] text-white/25",children:h})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(Sr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${v.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(Cn,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Sr.a,{href:`mailto:${d}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Sr.p,{className:"text-center text-[10px] text-white/10 mt-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:2.2},children:"Powered by LevelUp"})]})]})}function Axt(){const{shareToken:s}=Ki(),{data:t,isLoading:r,error:n}=mt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await V.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(k.useEffect(()=>{s&&V.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),r)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(n||!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()-Fl(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(GRs,{...i});case"warm":return e.jsx(KRs,{...i});case"glass":return e.jsx(YRs,{...i});case"cinematic":return e.jsx(ZRs,{...i});case"elegant":default:return e.jsx(HRs,{...i})}}function XRs(){const s=sa();return mt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:r}=await V.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(r)throw r;return t},enabled:!!s})}function QRs(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n}=await V.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(n){const{data:a,error:i}=await V.from("drip_settings").update(r).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await V.from("drip_settings").insert({user_id:s,is_globally_enabled:r.is_globally_enabled??!1,append_signature:r.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function JRs(){const s=br(),{isGmailConnected:t,gmailEmail:r}=Eh(),{data:n,isLoading:a}=XRs(),i=QRs(),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[h,m]=k.useState(!1);k.useEffect(()=>{n&&(o(n.is_globally_enabled),d(n.append_signature))},[n]);const x=async v=>{if(v&&!t){ue.error("Connect your Gmail account first before enabling Smart Drips");return}o(v);try{await i.mutateAsync({is_globally_enabled:v}),ue.success(v?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!v),ue.error("Failed to update settings")}},y=async v=>{d(v);try{await i.mutateAsync({append_signature:v}),ue.success(v?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!v),ue.error("Failed to update settings")}};return e.jsxs(fs,{open:h,onOpenChange:m,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(oo,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(ms,{className:"sm:max-w-md",children:[e.jsxs(ys,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(oo,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Hr,{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"}),r&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r})]})]}),t?e.jsxs(Ge,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(In,{className:"h-3 w-3"}),"Active"]}):e.jsxs(G,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{m(!1),s("/mission-control/integrations")},children:[e.jsx(Qr,{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(fo,{}),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(PR,{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(_r,{checked:l,onCheckedChange:x,disabled:a||i.isPending})]}),e.jsx(fo,{}),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(R0,{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(_r,{checked:c,onCheckedChange:y,disabled:a||i.isPending})]}),c&&e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{m(!1),s("/profile")},children:[e.jsx(R0,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function eOs(){const s=sa();return mt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function tOs(){const s=sa();return mt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:r}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(r)throw r;return t},enabled:!!s})}function sOs(){const s=sa(),t=Xt();return Ct({mutationFn:async r=>{if(!s)throw new Error("Not authenticated");const{data:n,error:a}=await V.from("drip_templates").insert({owner_user_id:s,stage_id:r.stage_id,title:r.title||"",subject:r.subject||"",body:r.body||"",video_url:r.video_url||null,channel:r.channel||"email",delay_type:r.delay_type||"instant",delay_minutes:r.delay_minutes||0,is_enabled:!1,deal_type:r.deal_type||null,sort_order:r.sort_order||0}).select().single();if(a)throw a;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function rOs(){const s=Xt();return Ct({mutationFn:async({id:t,...r})=>{const{data:n,error:a}=await V.from("drip_templates").update(r).eq("id",t).select().single();if(a)throw a;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function nOs(){const s=Xt();return Ct({mutationFn:async t=>{const{error:r}=await V.from("drip_templates").delete().eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function aOs(){const s=sa(),t=Xt();return Ct({mutationFn:async({templateId:r,stageId:n})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("drip_templates").select("*").eq("id",r).single();if(i)throw i;const{data:l,error:o}=await V.from("drip_templates").insert({owner_user_id:s,stage_id:n,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 iOs=[{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 oOs({open:s,onOpenChange:t,campaignId:r,campaignName:n}){const{data:a,isLoading:i}=g5s(r||void 0),l=v5s(),o=Pht(),c=async(m,x)=>{try{await l.mutateAsync({id:m,status:x}),ue.success(`Enrollment ${x}`)}catch{ue.error("Failed to update")}},d=async m=>{if(r)try{const x=await o.mutateAsync({campaignId:r,contactIds:[m]});x.enrolled>0?ue.success("Contact re-enrolled — first email queued"):x.skipped>0?ue.message("Already active in this campaign"):ue.error("Could not re-enroll")}catch{ue.error("Failed to re-enroll")}},h=m=>{const x={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(Ge,{variant:"outline",className:`text-[10px] capitalize ${x[m]||""}`,children:m})};return e.jsx(fs,{open:s,onOpenChange:t,children:e.jsxs(ms,{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(gs,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-4 w-4 text-primary"}),"Enrollments — ",n||"Campaign"]}),e.jsx(Hr,{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(m=>e.jsx(Fs,{className:"h-14"},m))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(pr,{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(m=>{var x,y,v,w;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(x=m.contact)==null?void 0:x.first_name," ",(y=m.contact)==null?void 0:y.last_name]}),h(m.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((v=m.contact)==null?void 0:v.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vs,{className:"h-2.5 w-2.5"})," ",m.contact.email]}),e.jsxs("span",{children:["Step ",m.current_step]}),m.next_send_at&&m.status==="active"&&e.jsxs("span",{children:["Next: ",_s(new Date(m.next_send_at),"MMM d, h:mma")]}),m.exit_reason&&e.jsxs("span",{children:["Exit: ",m.exit_reason]})]})]}),m.status==="active"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"paused"),title:"Pause",children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),m.status==="paused"&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"active"),title:"Resume",children:e.jsx(Uo,{className:"h-3.5 w-3.5"})}),(m.status==="active"||m.status==="paused")&&e.jsx(G,{size:"sm",variant:"ghost",onClick:()=>c(m.id,"exited"),title:"Exit",children:e.jsx(vr,{className:"h-3.5 w-3.5 text-destructive"})}),(m.status==="exited"||m.status==="completed")&&((w=m.contact)==null?void 0:w.id)&&e.jsxs(G,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(m.contact.id),disabled:o.isPending,children:[e.jsx(cv,{className:"h-3 w-3"}),"Re-enroll"]})]},m.id)})})})})]})})}function lOs(){var T;const{data:s,isLoading:t}=DTe(),{hasLeadSite:r}=_g(),n=m5s(),a=h5s(),i=Iht(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[h,m]=k.useState(null),[x,y]=k.useState(null),v=(s||[]).filter(A=>!A.is_starter),w=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||r),b=async A=>{try{await n.mutateAsync(A),ue.success("Campaign added to your library — customize and activate it!"),o(null)}catch(I){ue.error(I.message||"Failed to copy campaign")}},N=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),ue.success(A.is_active?"Campaign paused":"Campaign activated")}catch{ue.error("Failed to update")}},S=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),ue.success("Campaign deleted")}catch{ue.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(Fs,{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(B4,{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(Pd,{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(en,{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(pr,{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(G,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),v.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(jr,{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(G,{size:"sm",onClick:()=>{m(null),d(!0)},children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(A=>e.jsx(cOs,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>N(A),onDelete:()=>S(A.id),onEdit:()=>{m(A.id),d(!0)},onViewEnrollments:()=>y(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(jr,{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(Ge,{variant:"outline",className:"text-[10px]",children:[w.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:w.map(A=>e.jsx(dOs,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx(uOs,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:b,isCloning:n.isPending,onEdit:A=>{o(null),m(A),d(!0)}}),e.jsx(Oht,{open:c,onOpenChange:d,campaignId:h}),e.jsx(oOs,{open:!!x,onOpenChange:A=>!A&&y(null),campaignId:x,campaignName:(T=v.find(A=>A.id===x))==null?void 0:T.name})]})}function cOs({campaign:s,onPreview:t,onToggleActive:r,onDelete:n,onEdit:a,onViewEnrollments:i}){const o=y5s(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(Ge,{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(Ge,{variant:"outline",className:"text-[9px] mt-2",children:vxe[s.category]}),c&&e.jsxs("button",{onClick:r,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(id,{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(G,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(Ea,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(G,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:r,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:n,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function dOs({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(Ge,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(jr,{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(Ge,{variant:"outline",className:"text-[9px] mt-2",children:vxe[s.category]})]})]})}function uOs({campaignId:s,open:t,onOpenChange:r,onClone:n,isCloning:a,onEdit:i}){const{data:l}=DTe(),{data:o}=Lht(s||void 0),[c,d]=k.useState(new Set),h=l==null?void 0:l.find(y=>y.id===s);if(!h)return null;const m=y=>{d(v=>{const w=new Set(v);return w.has(y)?w.delete(y):w.add(y),w})},x=(y,v)=>{if(y.delay_type==="calendar_anchor"){const b=y.anchor_field==="birthday"?"birthday":"home anniversary",N=y.anchor_offset_days||0;return N===0?`On their ${b}`:N<0?`${Math.abs(N)} days before ${b}`:`${N} days after ${b}`}if(v===0&&y.delay_days===0&&y.delay_hours===0)return"Sends immediately";const w=[];return y.delay_days&&w.push(`${y.delay_days}d`),y.delay_hours&&w.push(`${y.delay_hours}h`),v===0?`After ${w.join(" ")}`:`+${w.join(" ")}`};return e.jsx(fs,{open:t,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${h.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:h.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx(gs,{className:"text-xl font-bold text-white",children:h.name}),e.jsx(Hr,{className:"text-white/90 mt-1",children:h.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Ge,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:vxe[h.category]}),e.jsxs(Ge,{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"}),h.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((y,v)=>{const w=c.has(y.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:v+1}),vm(y.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:[y.delay_type==="calendar_anchor"?e.jsx(on,{className:"h-3 w-3"}):e.jsx(fn,{className:"h-3 w-3"}),e.jsx("span",{children:x(y,v)}),e.jsx("span",{children:"·"}),e.jsx(Vs,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:y.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:y.subject}),w?e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:y.body}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 whitespace-pre-line",children:y.body}),y.body&&y.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:w?"Show less":"Show full email"})]})})]},y.id)})]})}),e.jsxs(an,{className:"border-t p-4 shrink-0",children:[e.jsx(G,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!h.is_starter&&i&&e.jsxs(G,{variant:"secondary",onClick:()=>i(h.id),children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),h.is_starter&&e.jsxs(G,{onClick:()=>n(h.id),disabled:a,children:[a?e.jsx(es,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}function hOs(){const s=sa(),t=br(),{isGmailConnected:r,gmailEmail:n,isLoading:a}=Eh(),{data:i,isLoading:l}=eOs(),{data:o,isLoading:c}=tOs(),d=sOs(),h=rOs(),m=nOs(),x=aOs(),[y,v]=k.useState(null),[w,b]=k.useState(null),N=(i==null?void 0:i.filter(F=>!F.is_starter&&F.owner_user_id===s))||[],S=(i==null?void 0:i.filter(F=>F.is_starter))||[],T=F=>N.filter(z=>z.stage_id===F),A=async F=>{try{await h.mutateAsync({id:F.id,is_enabled:!F.is_enabled}),ue.success(F.is_enabled?"Drip disabled":"Drip enabled")}catch{ue.error("Failed to update")}},I=async F=>{try{const z=o==null?void 0:o.find(Q=>Q.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}),v(F),ue.success("Drip template created")}catch{ue.error("Failed to create template")}},D=async F=>{try{await m.mutateAsync(F),ue.success("Template deleted")}catch{ue.error("Failed to delete")}},R=async F=>{if(!o||o.length===0){ue.error("No pipeline stages found");return}const z=o[0].id;try{await x.mutateAsync({templateId:F,stageId:z}),ue.success("Template copied to your drips!")}catch{ue.error("Failed to copy template")}},$=l||c;return e.jsx(ws,{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(Ku,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Ge,{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(JRs,{})]}),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(B4,{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&&(r?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",n?` (${n})`:""]}),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(B4,{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(G,{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(On,{defaultValue:"my-drips",children:[e.jsxs(Rn,{className:"grid grid-cols-3 w-full max-w-lg mb-6",children:[e.jsx(Kt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Kt,{value:"campaigns",children:["Campaigns",e.jsx(Ge,{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:"starters",children:["Stage Starters",S.length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:S.length})]})]}),e.jsx(ts,{value:"campaigns",children:e.jsx(lOs,{})}),e.jsx(ts,{value:"my-drips",children:$?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(F=>e.jsx(Fs,{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(Ku,{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=T(F.id),Q=y===F.id,K=z.some(X=>X.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>v(Q?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(Ge,{variant:"outline",className:`text-[10px] ${K?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",K&&" · Active"]}),Q?e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(va,{className:"h-4 w-4 text-muted-foreground"})]}),Q&&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(G,{variant:"outline",size:"sm",onClick:()=>I(F.id),disabled:d.isPending,children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(X=>e.jsx(IVe,{template:X,isEditing:w===X.id,onToggleEdit:()=>b(w===X.id?null:X.id),onToggleEnabled:()=>A(X),onUpdate:Z=>h.mutateAsync({id:X.id,...Z}),onDelete:()=>D(X.id),userId:s||""},X.id)),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>I(F.id),children:[e.jsx($s,{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=T(F.id),Q=y===F.id,K=z.some(X=>X.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>v(Q?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(Ge,{variant:"outline",className:`text-[10px] ${K?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",K&&" · Active"]}),Q?e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(va,{className:"h-4 w-4 text-muted-foreground"})]}),Q&&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(G,{variant:"outline",size:"sm",onClick:()=>I(F.id),disabled:d.isPending,children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(X=>e.jsx(IVe,{template:X,isEditing:w===X.id,onToggleEdit:()=>b(w===X.id?null:X.id),onToggleEnabled:()=>A(X),onUpdate:Z=>h.mutateAsync({id:X.id,...Z}),onDelete:()=>D(X.id),userId:s||""},X.id)),e.jsxs(G,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>I(F.id),children:[e.jsx($s,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)})]})]})}),e.jsx(ts,{value:"starters",children:S.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(jr,{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:S.map(F=>e.jsx(mOs,{template:F,onCopy:()=>R(F.id),isCopying:x.isPending},F.id))})})]})]})})}function IVe({template:s,isEditing:t,onToggleEdit:r,onToggleEnabled:n,onUpdate:a,onDelete:i,userId:l}){const[o,c]=k.useState(s.title),[d,h]=k.useState(s.subject),[m,x]=k.useState(s.body),[y,v]=k.useState(s.video_url||""),[w,b]=k.useState(s.channel),[N,S]=k.useState(s.delay_type),[T,A]=k.useState(s.delay_minutes),[I,D]=k.useState(!1),R=async()=>{D(!0);try{await a({title:o,subject:d,body:m,video_url:y||null,channel:w,delay_type:N,delay_minutes:T}),ue.success("Drip saved"),r()}catch{ue.error("Failed to save")}finally{D(!1)}},$=F=>{x(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:r,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(xi,{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(Jr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(_r,{checked:s.is_enabled,onCheckedChange:n})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(Ne,{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(he,{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:()=>b(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 ${w===F?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[F==="sms"?e.jsx(xi,{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(he,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>S("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${N==="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:()=>S("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${N==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(fn,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),N==="scheduled"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ne,{type:"number",min:1,value:T>=60?Math.round(T/60):T,onChange:F=>{const z=parseInt(F.target.value)||0;A(T>=60?z*60:z)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:T<60?T:30},{label:"Hours",mins:T>=60?T:60},{label:"Days",mins:T>=1440?T:1440}].map(F=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${F.label==="Minutes"&&T<60||F.label==="Hours"&&T>=60&&T<1440||F.label==="Days"&&T>=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))})]})]}),w==="email"&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(Ne,{value:d,onChange:F=>h(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(he,{className:"text-xs font-medium",children:w==="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&&$(F.target.value),F.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),iOs.map(F=>e.jsx("option",{value:F.key,children:F.label},F.key))]})]})]}),e.jsx("textarea",{value:m,onChange:F=>x(F.target.value),placeholder:w==="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(he,{className:"text-xs font-medium",children:"Attached Video"}),y?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(Jr,{className:"h-3 w-3 inline mr-1 text-primary"}),y.length>50?y.slice(0,50)+"...":y]}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>v(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(REe,{onVideoReady:F=>v(F)}),e.jsx(yL,{userId:l,onSelect:F=>v(F),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(G,{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&&v(F)},children:[e.jsx(po,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(G,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(yr,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(G,{variant:"outline",size:"sm",className:"text-xs",onClick:r,children:"Cancel"}),e.jsx(G,{size:"sm",className:"text-xs",onClick:R,disabled:I,children:I?"Saving...":"Save Drip"})]})]})]})]})}function mOs({template:s,onCopy:t,isCopying:r}){const[n,a]=k.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(!n),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}),!n&&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(Ge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(xi,{className:"h-3 w-3"}):e.jsx(Vs,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Ge,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(fn,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),n?e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(va,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),n&&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(fn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(G,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:r,children:[e.jsx(Ra,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const Mxt=()=>{const s=ec();return k.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 fOs(){return k.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(xde,{children:[e.jsx(ds,{path:"/c/:shareToken",element:e.jsx(Axt,{})}),e.jsx(ds,{path:"*",element:e.jsx(Mxt,{})})]})}const Pbe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function Ixt({slugOverride:s}){const t=Ki(),r=s||t.slug,[n,a]=k.useState("types"),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,h]=k.useState(null),[m,x]=k.useState(new Date),[y,v]=k.useState({name:"",email:"",phone:"",message:""}),[w,b]=k.useState(!1),{data:N,isLoading:S}=mt({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:Z,error:re}=await V.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(re)throw re;return Z},enabled:!!r}),{data:T}=mt({queryKey:["public-booking-profile",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Z,error:re}=await V.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",N.user_id).single();if(re)throw re;return Z},enabled:!!(N!=null&&N.user_id)}),{data:A=[]}=mt({queryKey:["public-booking-types",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Z,error:re}=await V.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",N.user_id).eq("is_active",!0).order("sort_order");if(re)throw re;return Z},enabled:!!(N!=null&&N.user_id)}),{data:I=[]}=mt({queryKey:["public-availability",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Z,error:re}=await V.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",N.user_id).eq("is_active",!0);if(re)throw re;return Z},enabled:!!(N!=null&&N.user_id)}),{data:D=[]}=mt({queryKey:["public-blocked-dates",N==null?void 0:N.user_id],queryFn:async()=>{const{data:Z,error:re}=await V.from("agent_blocked_dates").select("blocked_date").eq("user_id",N.user_id);if(re)throw re;return Z.map(le=>le.blocked_date)},enabled:!!(N!=null&&N.user_id)}),{data:R=[]}=mt({queryKey:["public-existing-bookings",N==null?void 0:N.user_id,o],queryFn:async()=>{if(!o)return[];const Z=_s(o,"yyyy-MM-dd"),{data:re,error:le}=await V.from("bookings").select("start_time, end_time").eq("agent_user_id",N.user_id).eq("booking_date",Z).eq("status","confirmed");if(le)throw le;return re},enabled:!!(N!=null&&N.user_id)&&!!o}),$=k.useMemo(()=>[...new Set(I.map(Z=>Z.day_of_week))],[I]),F=Z=>{const re=yf(new Date),le=Vl(re,(N==null?void 0:N.max_advance_days)||30),oe=Vl(re,0);return I3(Z,oe)||M3(Z,le)||D.includes(_s(Z,"yyyy-MM-dd"))?!1:$.includes(Z.getDay())},z=k.useMemo(()=>{if(!o||!i||!N)return[];const Z=I.filter(ye=>ye.day_of_week===o.getDay()),re=i.duration_minutes,le=N.buffer_minutes||0,oe=[],ne=new Date,ie=(N.min_notice_hours||2)*60*60*1e3;for(const ye of Z){const[ce,ve]=ye.start_time.split(":").map(Number),[be,Ue]=ye.end_time.split(":").map(Number);let Be=nO(rO(o,ce),ve);const De=nO(rO(o,be),Ue);for(;$E(Be,re)<=De;){const Ae=_s(Be,"HH:mm"),He=_s($E(Be,re),"HH:mm");Be.getTime()-ne.getTime()>=ie&&(R.some(Ie=>{const Te=Ie.start_time.slice(0,5),xe=Ie.end_time.slice(0,5);return AeTe})||oe.push(Ae)),Be=$E(Be,re+le)}}return oe},[o,i,I,N,R]),Q=k.useMemo(()=>{const Z=m.getFullYear(),re=m.getMonth(),le=new Date(Z,re,1),oe=new Date(Z,re+1,0),ne=le.getDay(),ie=[];for(let ye=0;ye{if(!(!i||!o||!d||!y.name||!N)){b(!0);try{const Z=_s($E(nO(rO(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:re}=await V.from("bookings").insert({agent_user_id:N.user_id,booking_type_id:i.id,booking_date:_s(o,"yyyy-MM-dd"),start_time:d,end_time:Z,guest_name:y.name,guest_email:y.email||null,guest_phone:y.phone||null,guest_message:y.message||null});if(re)throw re;V.functions.invoke("booking-notify",{body:{agentUserId:N.user_id,guestName:y.name,guestEmail:y.email||null,guestPhone:y.phone||null,guestMessage:y.message||null,bookingTypeName:i.name,bookingDate:_s(o,"yyyy-MM-dd"),startTime:d,endTime:Z,durationMinutes:i.duration_minutes,meetingLink:N.meeting_link||null}}).catch(le=>console.error("Booking notify error:",le)),a("confirmed")}catch(Z){ue.error("Failed to book: "+Z.message)}finally{b(!1)}}},X=Z=>{const[re,le]=Z.split(":").map(Number),oe=re>=12?"PM":"AM";return`${re%12||12}:${le.toString().padStart(2,"0")} ${oe}`};return S?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..."})]})}):N?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:[T!=null&&T.avatar_url?e.jsx("img",{src:T.avatar_url,alt:(T==null?void 0:T.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(Di,{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:(T==null?void 0:T.name)||"Agent"}),(T==null?void 0:T.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:T.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(T==null?void 0:T.phone)&&e.jsxs("a",{href:`tel:${T.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(Cn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:T.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(T==null?void 0:T.email)&&e.jsxs("a",{href:`mailto:${T.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:T.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:[n==="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(Z=>e.jsx("button",{onClick:()=>{l(Z),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:Z.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:Pbe[Z.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:Z.name}),Z.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:Z.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(fn,{className:"h-3 w-3"}),Z.duration_minutes,"m"]})]})})},Z.id))})]}),n==="date"&&i&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>{a("types"),c(null),h(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:i.color+"40",backgroundColor:i.color+"08"},children:[e.jsx("span",{className:"text-xl",children:Pbe[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(fn,{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:_s(m,"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:()=>x(new Date(m.getFullYear(),m.getMonth()-1)),children:e.jsx($o,{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:()=>x(new Date(m.getFullYear(),m.getMonth()+1)),children:e.jsx(va,{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(Z=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:Z},Z)),Q.map((Z,re)=>{if(!Z)return e.jsx("div",{},`pad-${re}`);const le=F(Z),oe=o&&Ol(Z,o),ne=Ol(Z,new Date);return e.jsx("button",{disabled:!le,onClick:()=>{c(Z),h(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${oe?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":le?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${ne&&!oe?"ring-1 ring-[#406E71]/40":""}`,children:Z.getDate()},Z.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hd,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:_s(o,"EEEE, MMMM d")})]}),z.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(fn,{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(Z=>{const re=d===Z;return e.jsx("button",{onClick:()=>h(Z),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${re?"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:X(Z)},Z)})}),d&&e.jsx(G,{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"})]})]}),n==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-[#406E71]/5 to-[#2a4c64]/5 border border-[#406E71]/15 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:Pbe[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(hd,{className:"h-3.5 w-3.5 text-[#406E71]"}),_s(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{className:"h-3.5 w-3.5 text-[#406E71]"}),X(d)," · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(he,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(Ne,{value:y.name,onChange:Z=>v({...y,name:Z.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(he,{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(Ne,{type:"email",value:y.email,onChange:Z=>v({...y,email:Z.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(he,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(Cn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(Ne,{type:"tel",value:y.phone,onChange:Z=>v({...y,phone:Z.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(he,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(or,{value:y.message,onChange:Z=>v({...y,message:Z.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(G,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:K,disabled:!y.name||w,children:w?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"})]}),n==="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(In,{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 ",(T==null?void 0:T.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&&_s(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&X(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."}),((T==null?void 0:T.phone)||(T==null?void 0:T.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:[(T==null?void 0:T.phone)&&e.jsxs("a",{href:`tel:${T.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(Cn,{className:"h-3.5 w-3.5"})," Call"]}),(T==null?void 0:T.email)&&e.jsxs("a",{href:`mailto:${T.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(hd,{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 pOs(){const t=ec().pathname.slice(1).split("/")[0];return k.useEffect(()=>{document.body.classList.add("booking-page");const r=()=>{['[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"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("booking-page"),n.forEach(clearTimeout)}},[]),t?e.jsx(Ixt,{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 xOs(){const t=ec().pathname.slice(1);return k.useEffect(()=>{document.body.classList.add("connect-page");const r=()=>{['[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"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("connect-page"),n.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(Yrt,{slugOverride:t})}function gOs(s){try{const t=document.createElement("canvas"),r=t.width=Math.min(s.naturalWidth,64),n=t.height=Math.min(s.naturalHeight,64),a=t.getContext("2d");if(!a)return!0;a.drawImage(s,0,0,r,n);const i=a.getImageData(0,0,r,n).data,l=[[0,0],[r-1,0],[0,n-1],[r-1,n-1],[Math.floor(r/2),0],[Math.floor(r/2),n-1],[0,Math.floor(n/2)],[r-1,Math.floor(n/2)]];for(const[o,c]of l)if(i[(c*r+o)*4+3]<250)return!0;return!1}catch{return!0}}const yOs={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function vOs({page:s,fields:t,answers:r,setAnswers:n,onSubmit:a,isSubmitting:i,renderField:l}){const o=s.accent_color||"#E8B84A",c=s.primary_color||"#0F1B3D",d=yOs[s.heading_font||"playfair"],h=s.eyebrow||null,m=s.headline_accent||null,x=Array.isArray(s.trust_pills)?s.trust_pills:[],y=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(bOs,{src:s.logo_url}),h&&e.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:h}),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,m&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:m})]})]}),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(Cn,{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:[y.map(v=>e.jsxs("div",{children:[e.jsxs(he,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[v.label,v.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(v,r,n,c)})]},v.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"})]}),x.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:x.map((v,w)=>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}}),v]},w))})]})})]})})]})}function bOs({src:s}){const[t,r]=k.useState(null),n=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>r(gOs(a.currentTarget)),onError:()=>r(!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:n}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}function Lxt({slugOverride:s}){const{slug:t}=Ki(),r=s||t,[n,a]=k.useState(!1),[i,l]=k.useState({}),[o,c]=k.useState(0),[d,h]=k.useState(!1),{data:m,isLoading:x}=mt({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:R,error:$}=await V.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if($)throw $;return R},enabled:!!r}),{data:y=[]}=mt({queryKey:["public-landing-page-fields",m==null?void 0:m.id],queryFn:async()=>{const{data:R,error:$}=await V.from("landing_page_fields").select("*").eq("page_id",m.id).order("sort_order");if($)throw $;return R},enabled:!!(m!=null&&m.id)});k.useEffect(()=>{m!=null&&m.id&&V.from("landing_pages").update({view_count:(m.view_count||0)+1}).eq("id",m.id).then(()=>{})},[m==null?void 0:m.id]);const v=Ct({mutationFn:async()=>{const R=y.find(Z=>Z.field_type==="text"&&Z.label.toLowerCase().includes("name")),$=y.find(Z=>Z.field_type==="email"),F=y.find(Z=>Z.field_type==="phone"),z=R?String(i[R.label]||""):null,Q=$?String(i[$.label]||""):null,K=F?String(i[F.label]||""):null,{error:X}=await V.from("landing_page_submissions").insert([{page_id:m.id,answers:JSON.parse(JSON.stringify(i)),contact_name:z,contact_email:Q,contact_phone:K,referrer:document.referrer||null,user_agent:navigator.userAgent,utm_source:new URLSearchParams(window.location.search).get("utm_source"),utm_medium:new URLSearchParams(window.location.search).get("utm_medium"),utm_campaign:new URLSearchParams(window.location.search).get("utm_campaign")}]);if(X)throw X;V.functions.invoke("landing-page-lead-notify",{body:{page_id:m.id,contact_name:z,contact_email:Q,contact_phone:K,answers:i}}).catch(Z=>console.error("Landing page lead notification error:",Z))},onSuccess:()=>a(!0)}),w=R=>{R.preventDefault(),!(y.filter(F=>F.is_required&&!i[F.label]).length>0)&&v.mutate()};if(x)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!m)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 b=m.primary_color||"#406E71",N=m.accent_color||"#2a4c64",S=m,T=m.page_type==="lead_magnet",A=m.page_type==="just_listed"||m.page_type==="just_sold",I=Array.isArray(S.property_photos)?S.property_photos:[],D=S.lead_magnet_file_url||S.lead_magnet_external_url;if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${b}, ${N})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(In,{className:"h-16 w-16 mx-auto mb-4",style:{color:b}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:T?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:m.success_message}),T&&D&&e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:b},children:[e.jsx(Ya,{className:"h-5 w-5"}),"Download ",S.lead_magnet_file_name||"Your File"]}),m.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:m.agent_name}),m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:b},children:[e.jsx(Cn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:b},children:[e.jsx(Vs,{className:"h-3 w-3"})," ",m.agent_email]})]})]})});if(A){const R=$=>{const F=parseFloat($.replace(/[^0-9.]/g,""));return isNaN(F)?$:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&I.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>h(!1),children:[e.jsx("button",{onClick:()=>h(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(vr,{className:"h-8 w-8"})}),e.jsx("button",{onClick:$=>{$.stopPropagation(),c(F=>F===0?I.length-1:F-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($o,{className:"h-6 w-6"})}),e.jsx("img",{src:I[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:$=>$.stopPropagation()}),e.jsx("button",{onClick:$=>{$.stopPropagation(),c(F=>F===I.length-1?0:F+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(va,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[o+1," / ",I.length]})]}),I.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:S.property_status==="just_sold"?"#e74c3c":b},children:S.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),I.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),h(!0)},children:[e.jsx("img",{src:I[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(dj,{className:"h-4 w-4"})," View"]})]}):I.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:I.slice(0,2).map(($,F)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(F),h(!0)},children:e.jsx("img",{src:$,alt:`Property ${F+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},F))}):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),h(!0)},children:e.jsx("img",{src:I[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),I.slice(1,5).map(($,F)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(F+1),h(!0)},children:[e.jsx("img",{src:$,alt:`Property ${F+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),F===3&&I.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",I.length-5," more"]})]},F))]}),I.length>2&&e.jsxs("button",{onClick:()=>{c(0),h(!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(dj,{className:"h-4 w-4"})," View all ",I.length," photos"]})]}),I.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:m.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${m.hero_image_url}) center/cover`:`linear-gradient(135deg, ${b}, ${N})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[m.logo_url&&e.jsx("img",{src:m.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:m.hero_headline}),m.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:m.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:[S.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:b},children:R(S.property_price)}),S.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(Ca,{className:"h-5 w-5 shrink-0"})," ",S.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[S.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(Ny,{className:"h-5 w-5",style:{color:b}})," ",S.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),S.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(Xf,{className:"h-5 w-5",style:{color:b}})," ",S.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),S.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(J4,{className:"h-5 w-5",style:{color:b}})," ",Number(S.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),S.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:S.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:b},children:S.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!"}),m.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[m.agent_photo_url&&e.jsx("img",{src:m.agent_photo_url,alt:m.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:m.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Cn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"})," ",m.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:w,className:"space-y-3",children:[y.map($=>e.jsxs("div",{children:[e.jsxs(he,{className:"text-xs font-medium",children:[$.label,$.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Dbe($,i,l)]},$.id)),e.jsx(G,{type:"submit",className:"w-full text-white",style:{backgroundColor:b},disabled:v.isPending,children:v.isPending?"Submitting...":"Submit"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return m.theme_style!=="classic"&&!T?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx(vOs,{page:m,fields:y,answers:i,setAnswers:l,onSubmit:w,isSubmitting:v.isPending,renderField:Dbe}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:m.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${m.hero_image_url}) center/cover`:`linear-gradient(135deg, ${b}, ${N})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[m.logo_url&&e.jsx("img",{src:m.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:m.hero_headline}),m.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:m.hero_subtext}),T&&S.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(Ya,{className:"h-4 w-4"}),"Free Download: ",S.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:[T&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),m.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[m.agent_photo_url&&e.jsx("img",{src:m.agent_photo_url,alt:m.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:m.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[m.agent_phone&&e.jsxs("a",{href:`tel:${m.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Cn,{className:"h-3 w-3"})," ",m.agent_phone]}),m.agent_email&&e.jsxs("a",{href:`mailto:${m.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Vs,{className:"h-3 w-3"})," ",m.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:w,className:"space-y-4",children:[y.map(R=>e.jsxs("div",{children:[e.jsxs(he,{className:"text-sm font-medium",children:[R.label,R.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),Dbe(R,i,l)]},R.id)),e.jsx(G,{type:"submit",className:"w-full text-white",style:{backgroundColor:b},disabled:v.isPending,children:v.isPending?"Submitting...":T?"Get My Free Download":"Submit"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function Dbe(s,t,r,n){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(Ne,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(or,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(Is,{value:String(a),onValueChange:l=>r(o=>({...o,[s.label]:l})),children:[e.jsx(As,{className:"mt-1",children:e.jsx(Ls,{placeholder:"Select..."})}),e.jsx(Ms,{children:i.map(l=>e.jsx(ct,{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(Si,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(h=>h!==l);r(h=>({...h,[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(_r,{checked:!!a,onCheckedChange:l=>r(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(Ne,{value:String(a),onChange:l=>r(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function _Os(){const t=ec().pathname.slice(1).split("/")[0];return k.useEffect(()=>{document.body.classList.add("landing-page-public");const r=()=>{['[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"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("landing-page-public"),n.forEach(clearTimeout)}},[]),t?e.jsx(Lxt,{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 wOs=[{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}],ZUs={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",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"},XUs={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",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"},LVe={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner","lifestyle_gallery","market_pulse","concierge_services"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase"]};function QUs(s){return LVe[s]||LVe.basic}function jOs(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:wOs,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 NOs(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function kOs(){const s=NOs(),{data:t,isLoading:r,error:n}=mt({queryKey:["lead-site",s],queryFn:async()=>{var h;if(!s)return null;const{data:a,error:i}=await V.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 V.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:m}=await V.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();m&&((h=m.teams)!=null&&h.avatar_url)&&(o=m.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,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,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(m=>m&&typeof m=="object"&&m.text).map(m=>({name:String(m.name||"Client"),text:String(m.text),rating:typeof m.rating=="number"?m.rating:5,location:m.location?String(m.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=jOs(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:r,error:n,slug:s}}async function SOs(s,t){try{await V.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(r){console.warn("Lead notification failed:",r)}}const Pxt=k.createContext(null);function Kxe(){const s=k.useContext(Pxt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function COs({siteConfig:s,children:t}){const[r,n]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(!0);k.useEffect(()=>{const{data:{subscription:m}}=V.auth.onAuthStateChange(async(x,y)=>{const v=(y==null?void 0:y.user)??null;if(n(v),v){const{data:w}=await V.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",v.id).eq("lead_site_id",s.id).maybeSingle();w&&i({...w,email:v.email||""})}else i(null);o(!1)});return V.auth.getSession().then(({data:{session:x}})=>{n((x==null?void 0:x.user)??null),x!=null&&x.user?V.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",x.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:y})=>{y&&i({...y,email:x.user.email||""}),o(!1)}):o(!1)}),()=>m.unsubscribe()},[s.id]);const c=k.useCallback(async m=>{const x=m.email.toLowerCase().trim(),y=m.phone.replace(/\D/g,""),{data:v,error:w}=await V.auth.signUp({email:x,password:y,options:{data:{full_name:m.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(w){if(w.message.includes("already registered")){await d(x,y);return}throw w}if(v.user){const{error:b}=await V.from("lead_site_consumer_profiles").insert({user_id:v.user.id,lead_site_id:s.id,name:m.name.trim(),phone:m.phone.trim()});b&&console.warn("Consumer profile insert error:",b);const{error:N}=await V.from("lead_site_leads").insert({lead_site_id:s.id,name:m.name.trim(),email:x,phone:m.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});N&&console.error("Lead insert error (CRM sync may not trigger):",N),SOs(s.id,{name:m.name.trim(),email:x,phone:m.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=k.useCallback(async(m,x)=>{const y=x.replace(/\D/g,""),{error:v}=await V.auth.signInWithPassword({email:m.toLowerCase().trim(),password:y});if(v)throw v},[]),h=k.useCallback(async()=>{await V.auth.signOut(),n(null),i(null)},[]);return e.jsx(Pxt.Provider,{value:{user:r,profile:a,isLoading:l,signUp:c,signIn:d,signOut:h},children:t})}function WEe({open:s,mode:t,siteConfig:r,onComplete:n,onSkip:a,theme:i="default",accentColor:l}){var X;const{signUp:o,signIn:c}=Kxe(),[d,h]=k.useState(!1),[m,x]=k.useState(""),[y,v]=k.useState(""),[w,b]=k.useState(""),[N,S]=k.useState(!1),[T,A]=k.useState(""),I=t==="required",D=i==="luxury",R=l||(D?"#c9a96e":"#2563eb"),$=((X=r.agent)==null?void 0:X.full_name)||"the agent",F={borderColor:`${R}66`,"--tw-ring-color":`${R}66`},z=async Z=>{var le;if(Z.preventDefault(),A(""),!y.trim()||!w.trim()){A("Email and phone number are required.");return}if(!d&&!m.trim()){A("Name is required.");return}if(w.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}S(!0);try{d?await c(y,w):await o({name:m,email:y,phone:w}),n()}catch(oe){(le=oe==null?void 0:oe.message)!=null&&le.includes("Invalid login")?A("Invalid email or phone number. Please try again."):A((oe==null?void 0:oe.message)||"Something went wrong. Please try again.")}finally{S(!1)}},Q=D?"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",K=D?F:void 0;return e.jsx(fs,{open:s,onOpenChange:I?void 0:Z=>{Z||a()},children:e.jsxs(ms,{className:`sm:max-w-md ${D?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:I?Z=>Z.preventDefault():void 0,onEscapeKeyDown:I?Z=>Z.preventDefault():void 0,children:[e.jsxs(ys,{children:[e.jsx(gs,{className:"text-xl",style:D?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":I?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Hr,{className:D?"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 ${$}.`})]}),e.jsxs("form",{onSubmit:z,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:m,onChange:Z=>x(Z.target.value),className:Q,style:K}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:y,onChange:Z=>v(Z.target.value),className:Q,style:K}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:w,onChange:Z=>b(Z.target.value),className:Q,style:K}),e.jsx("p",{className:`text-xs mt-1 ${D?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),T&&e.jsx("p",{className:"text-red-600 text-sm",children:T}),e.jsx("button",{type:"submit",disabled:N,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${D?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:D?{backgroundColor:R}:void 0,children:N?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{h(!d),A("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:R},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!I&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${D?"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 ${D?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function KEe({siteConfig:s,pagePath:t}){const r=s.agent;if(!r)return null;const n=`https://${s.subdomainSlug}.thelocalmove.com`,i=(r.areas_served||"").split(/,|;|\|/).map(T=>T.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(d.map(T=>T.toUpperCase()))],m=s.testimonials||[],x=m.length?{"@type":"AggregateRating",ratingValue:(m.reduce((T,A)=>T+(A.rating||5),0)/m.length).toFixed(1),reviewCount:m.length,bestRating:5,worstRating:1}:void 0,y=[r.facebook_url,r.instagram_url,r.linkedin_url].filter(Boolean),v={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${n}/#agent`,name:r.full_name,url:n,image:r.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||r.avatar_url||void 0,email:r.email,telephone:r.phone||void 0,jobTitle:r.title||"Real Estate Agent",description:r.bio||`${r.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...y.length&&{sameAs:y},...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(T=>{const[A,I]=T.split(/,\s*/);return{"@type":"City",name:A,...I&&{containedInPlace:{"@type":"State",name:I}}}})},...x&&{aggregateRating:x},...m.length&&{review:m.slice(0,10).map(T=>({"@type":"Review",author:{"@type":"Person",name:T.name},reviewBody:T.text,reviewRating:{"@type":"Rating",ratingValue:T.rating||5,bestRating:5,worstRating:1},...T.location&&{locationCreated:{"@type":"Place",name:T.location}}}))}},w={"@context":"https://schema.org","@type":"Person","@id":`${n}/#person`,name:r.full_name,jobTitle:r.title||"Real Estate Agent",description:r.bio||void 0,image:r.avatar_url||void 0,url:n,email:r.email,telephone:r.phone||void 0,...y.length&&{sameAs:y},...r.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...h.length&&{hasCredential:h.map(T=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:T}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},b={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:s.siteTitle||`${r.full_name} Real Estate`,url:n,publisher:{"@id":`${n}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},N=[{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 ${r.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],S={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:N.map((T,A)=>({"@type":"SiteNavigationElement",position:A+1,name:T.name,description:T.description,url:`${n}${T.path}`}))};return e.jsxs(nl,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(w)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(b)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(S)})]})}function JUs({items:s,siteConfig:t}){const r=`https://${t.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${r}${a.path}`}))};return e.jsx(nl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function eqs({listing:s,siteConfig:t}){var a;const r=`https://${t.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${r}/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(nl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function TOs({faqs:s}){if(!s.length)return null;const t={"@context":"https://schema.org","@type":"FAQPage",mainEntity:s.map(r=>({"@type":"Question",name:r.question,acceptedAnswer:{"@type":"Answer",text:r.answer}}))};return e.jsx(nl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function tqs({title:s,description:t,publishedAt:r,imageUrl:n,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:r,...n&&{image:n},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(nl,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function YEe({siteConfig:s}){var y;const t=s.agent;if(!t)return null;const r=t.full_name,n=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((y=a.split(/,|;|\|/)[0])==null?void 0:y.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,h=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],m=[...new Set(h.map(v=>v.toUpperCase()))],x=[{question:`Who is ${r}?`,answer:`${r} is a ${t.title||"REALTOR®"} with ${n}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${r} serve?`,answer:`${r} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${r.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${r}?`,answer:`You can reach ${r} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...m.length?[{question:`What real estate designations does ${r} hold?`,answer:`${r} holds the following professional designations: ${m.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${r} a licensed real estate agent?`,answer:`Yes, ${r} is a fully licensed real estate professional (License #${d}) with ${n}.`}]:[],{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:`${r} 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 ${r.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 ${r}. ${r.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(TOs,{faqs:x})}const PVe="ls_visitor_geo",EOs=1e3*60*60;function AOs(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 MOs(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(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return s}}async function IOs(){try{const s=localStorage.getItem(PVe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,IOs().then(l=>{a.current=l}))},[]),k.useEffect(()=>{if(!(s!=null&&s.id))return;const l=r.pathname;if(l===n.current)return;n.current=l;const o=AOs(l),c=MOs(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=a.current;V.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,visitor_city:(h==null?void 0:h.city)||null,visitor_region:(h==null?void 0:h.region)||null,visitor_country:(h==null?void 0:h.country)||null,visitor_lat:(h==null?void 0:h.lat)||null,visitor_lng:(h==null?void 0:h.lng)||null}).then(({error:m})=>{m&&console.error("[PageTracking] insert failed:",m.message)})},[r.pathname,s==null?void 0:s.id,t])}const LOs=3e4;function XEe(s,t){const r=ec(),n=k.useRef(null),a=k.useRef(null),i=k.useRef(0),l=r.pathname,o=POs(l),c=DOs(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const h=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,m=async()=>{const{data:x,error:y}=await V.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:h,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();!y&&x&&(n.current=x.id,i.current>=2&&!x.notified_agent&&V.functions.invoke("lead-site-presence-notify",{body:{visitor_id:x.id,lead_site_id:s.id}}).catch(()=>{}))};return m(),a.current&&clearInterval(a.current),a.current=setInterval(m,LOs),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const h=()=>{n.current&&V.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",h),()=>window.removeEventListener("beforeunload",h)},[s==null?void 0:s.id,t])}function POs(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 DOs(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(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");default:return s}}const Zn=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},ROs=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=OOs},OOs=Number.MAX_SAFE_INTEGER||9007199254740991;let La=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}({}),ar=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}({}),ht=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 ao={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ua={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class hE{constructor(t,r=0,n=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_=r,this.totalWeight_=n}sample(t,r){const n=Math.pow(this.alpha_,t);this.estimate_=r*(1-n)+n*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 FOs{constructor(t,r,n,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_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new hE(t),this.fast_=new hE(r),this.defaultTTFB_=a,this.ttfb_=new hE(t)}update(t,r){const{slow_:n,fast_:a,ttfb_:i}=this;n.halfLife!==t&&(this.slow_=new hE(t,n.getEstimate(),n.getTotalWeight())),a.halfLife!==r&&(this.fast_=new hE(r,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new hE(t,i.getEstimate(),i.getTotalWeight()))}sample(t,r){t=Math.max(t,this.minDelayMs_);const n=8*r,a=t/1e3,i=n/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}sampleTTFB(t){const r=t/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,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 BOs(s,t,r){return(t=$Os(t))in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function zl(){return zl=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):uw}function RVe(s,t,r){return t[s]?t[s].bind(t):qOs(s,r)}const $ke=zke();function VOs(s,t,r){const n=zke();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{n[i]=RVe(i,s,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return zke()}a.forEach(i=>{$ke[i]=RVe(i,s)})}else zl($ke,n);return n}const Al=$ke;function zj(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function HOs(s){return typeof self<"u"&&s===self.ManagedMediaSource}function Dxt(s,t){const r=Object.keys(s),n=Object.keys(t),a=r.length,i=n.length;return!a||!i||a===i&&!r.some(l=>n.indexOf(l)===-1)}function ex(s,t=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(t){const h=d.indexOf("\0");return h!==-1?d.substring(0,h):d}return d.replace(/\0/g,"")}const r=s.length;let n,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(n);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((n&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((n&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function qh(s){let t="";for(let r=0;r1||a===1&&(r=this.levelkeys[n[0]])!=null&&r.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(!Zn(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Yd(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 r=this.levelkeys;if(r){var n;const a=r[t];a&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=a.getDecryptData(this.sn,r))}}abortRequests(){var t,r;(t=this.loader)==null||t.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(t,r,n,a,i,l=!1){const{elementaryStreams:o}=this,c=o[t];if(!c){o[t]={startPTS:r,endPTS:n,startDTS:a,endDTS:i,partial:l};return}c.startPTS=Math.min(c.startPTS,r),c.endPTS=Math.max(c.endPTS,n),c.startDTS=Math.min(c.startDTS,a),c.endDTS=Math.max(c.endDTS,i)}}class KOs extends Oxt{constructor(t,r,n,a,i){super(n),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=r,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 Fxt(s,t){const r=Object.getPrototypeOf(s);if(r){const n=Object.getOwnPropertyDescriptor(r,t);return n||Fxt(r,t)}}function YOs(s,t){const r=Fxt(s,t);r&&(r.enumerable=!0,Object.defineProperty(s,t,r))}const FVe=Math.pow(2,32)-1,ZOs=[].push,Bxt={video:1,audio:2,id3:3,text:4};function Pu(s){return String.fromCharCode.apply(null,s)}function zxt(s,t){const r=s[t]<<8|s[t+1];return r<0?65536+r:r}function Ni(s,t){const r=$xt(s,t);return r<0?4294967296+r:r}function BVe(s,t){let r=Ni(s,t);return r*=Math.pow(2,32),r+=Ni(s,t+4),r}function $xt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function XOs(s){const t=s.byteLength;for(let r=0;r8&&s[r+4]===109&&s[r+5]===111&&s[r+6]===111&&s[r+7]===102)return!0;r=n>1?r+n:t}return!1}function so(s,t){const r=[];if(!t.length)return r;const n=s.byteLength;for(let a=0;a1?a+i:n;if(l===t[0])if(t.length===1)r.push(s.subarray(a+8,o));else{const c=so(s.subarray(a+8,o),t.slice(1));c.length&&ZOs.apply(r,c)}a=o}return r}function QOs(s){const t=[],r=s[0];let n=8;const a=Ni(s,n);n+=4;let i=0,l=0;r===0?(i=Ni(s,n),l=Ni(s,n+4),n+=8):(i=BVe(s,n),l=BVe(s,n+8),n+=16),n+=2;let o=s.length+l;const c=zxt(s,n);n+=2;for(let d=0;d>>31===1)return Al.warn("SIDX has hierarchical references (not supported)"),null;const v=Ni(s,h);h+=4,t.push({referenceSize:x,subsegmentDuration:v,info:{duration:v/a,start:o,end:o+x-1}}),o+=x,h+=4,n=h}return{earliestPresentationTime:i,timescale:a,version:r,referencesCount:c,references:t}}function Uxt(s){const t=[],r=so(s,["moov","trak"]);for(let a=0;a{const i=Ni(a,4),l=t[i];l&&(l.default={duration:Ni(a,12),flags:Ni(a,20)})}),t}function JOs(s){const t=s.subarray(8),r=t.subarray(86),n=Pu(t.subarray(4,8));let a=n,i;const l=n==="enca"||n==="encv";if(l){const d=so(t,[n])[0].subarray(n==="enca"?28:78);so(d,["sinf"]).forEach(m=>{const x=so(m,["schm"])[0];if(x){const y=Pu(x.subarray(4,8));if(y==="cbcs"||y==="cenc"){const v=so(m,["frma"])[0];v&&(a=Pu(v))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=so(r,["avcC"])[0];c&&c.length>3&&(a+="."+eU(c[1])+eU(c[2])+eU(c[3]),i=J$(o==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const c=so(t,[n])[0],d=so(c.subarray(28),["esds"])[0];if(d&&d.length>7){let h=4;if(d[h++]!==3)break;h=Fbe(d,h),h+=2;const m=d[h++];if(m&128&&(h+=2),m&64&&(h+=d[h++]),d[h++]!==4)break;h=Fbe(d,h);const x=d[h++];if(x===64)a+="."+eU(x);else break;if(h+=12,d[h++]!==5)break;h=Fbe(d,h);const y=d[h++];let v=(y&248)>>3;v===31&&(v+=1+((y&7)<<3)+((d[h]&224)>>5)),a+="."+v}break}case"hvc1":case"hev1":{const c=so(r,["hvcC"])[0];if(c&&c.length>12){const d=c[1],h=["","A","B","C"][d>>6],m=d&31,x=Ni(c,2),y=(d&32)>>5?"H":"L",v=c[12],w=c.subarray(6,12);a+="."+h+m,a+="."+e8s(x).toString(16).toUpperCase(),a+="."+y+v;let b="";for(let N=w.length;N--;){const S=w[N];(S||b)&&(b="."+S.toString(16).toUpperCase()+b)}a+=b}i=J$(o=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=J$(a,r)||a;break}case"vp09":{const c=so(r,["vpcC"])[0];if(c&&c.length>6){const d=c[4],h=c[5],m=c[6]>>4&15;a+="."+M0(d)+"."+M0(h)+"."+M0(m)}break}case"av01":{const c=so(r,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,h=c[1]&31,m=c[2]>>>7?"H":"M",x=(c[2]&64)>>6,y=(c[2]&32)>>5,v=d===2&&x?y?12:10:x?10:8,w=(c[2]&16)>>4,b=(c[2]&8)>>3,N=(c[2]&4)>>2,S=c[2]&3;a+="."+d+"."+M0(h)+m+"."+M0(v)+"."+w+"."+b+N+S+"."+M0(1)+"."+M0(1)+"."+M0(1)+"."+0,i=J$("dav1",r)}break}}return{codec:a,encrypted:l,supplemental:i}}function J$(s,t){const r=so(t,["dvvC"]),n=r.length?r[0]:so(t,["dvcC"])[0];if(n){const a=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return s+"."+M0(a)+"."+M0(i)}}function e8s(s){let t=0;for(let r=0;r<32;r++)t|=(s>>r&1)<<31-r;return t>>>0}function Fbe(s,t){const r=t+5;for(;s[t++]&128&&t{const i=n.subarray(8,24);i.some(l=>l!==0)||(Al.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${qh(i)} -> ${qh(r)}`),n.set(r,8))})}function s8s(s){const t=[];return qxt(s,r=>t.push(r.subarray(8,24))),t}function qxt(s,t){so(s,["moov","trak"]).forEach(n=>{const a=so(n,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=so(i,["enca"]);const o=l.length>0;o||(l=so(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);so(d,["sinf"]).forEach(m=>{const x=Vxt(m);x&&t(x,o)})})})}function Vxt(s){const t=so(s,["schm"])[0];if(t){const r=Pu(t.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=so(s,["schi","tenc"])[0];if(n)return n}}}function r8s(s,t,r){const n={},a=so(s,["moof","traf"]);for(let i=0;in[i].duration)){let i=1/0,l=0;const o=so(s,["sidx"]);for(let c=0;cm+x.info.duration||0,0);l=Math.max(l,h+d.earliestPresentationTime/d.timescale)}}l&&Zn(l)&&Object.keys(n).forEach(c=>{n[c].duration||(n[c].duration=l*n[c].timescale-n[c].start)})}return n}function n8s(s){const t={valid:null,remainder:null},r=so(s,["moof"]);if(r.length<2)return t.remainder=s,t;const n=r[r.length-1];return t.valid=s.slice(0,n.byteOffset-8),t.remainder=s.slice(n.byteOffset-8),t}function gg(s,t){const r=new Uint8Array(s.length+t.length);return r.set(s),r.set(t,s.length),r}function zVe(s,t){const r=[],n=t.samples,a=t.timescale,i=t.id;let l=!1;return so(n,["moof"]).map(c=>{const d=c.byteOffset-8;so(c,["traf"]).map(m=>{const x=so(m,["tfdt"]).map(y=>{const v=y[0];let w=Ni(y,4);return v===1&&(w*=Math.pow(2,32),w+=Ni(y,8)),w/a})[0];return x!==void 0&&(s=x),so(m,["tfhd"]).map(y=>{const v=Ni(y,4),w=Ni(y,0)&16777215,b=(w&1)!==0,N=(w&2)!==0,S=(w&8)!==0;let T=0;const A=(w&16)!==0;let I=0;const D=(w&32)!==0;let R=8;v===i&&(b&&(R+=8),N&&(R+=4),S&&(T=Ni(y,R),R+=4),A&&(I=Ni(y,R),R+=4),D&&(R+=4),t.type==="video"&&(l=Yxe(t.codec)),so(m,["trun"]).map($=>{const F=$[0],z=Ni($,0)&16777215,Q=(z&1)!==0;let K=0;const X=(z&4)!==0,Z=(z&256)!==0;let re=0;const le=(z&512)!==0;let oe=0;const ne=(z&1024)!==0,ie=(z&2048)!==0;let ye=0;const ce=Ni($,4);let ve=8;Q&&(K=Ni($,ve),ve+=4),X&&(ve+=4);let be=K+d;for(let Ue=0;Ue>1&63;return r===39||r===40}else return(t&31)===6}function eAe(s,t,r,n){const a=Hxt(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 h=i;if(od){Al.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[h++]===181){const x=zxt(a,h);if(h+=2,x===49){const y=Ni(a,h);if(h+=4,y===1195456820){const v=a[h++];if(v===3){const w=a[h++],b=31&w,N=64&w,S=N?2+b*3:0,T=new Uint8Array(S);if(N){T[0]=w;for(let A=1;A16){const m=[];for(let v=0;v<16;v++){const w=a[h++].toString(16);m.push(w.length==1?"0"+w:w),(v===3||v===5||v===7||v===9)&&m.push("-")}const x=o-16,y=new Uint8Array(x);for(let v=0;v>24&255,i[1]=n>>16&255,i[2]=n>>8&255,i[3]=n&255,i.set(s,4),a=0,n=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 r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),o8s([112,115,115,104],new Uint8Array([n,0,0,0]),s,i,a,l,r)}function c8s(s){const t=[];if(s instanceof ArrayBuffer){const r=s.byteLength;let n=0;for(;n+32>>24;if(i!==0&&i!==1)return{offset:r,size:t};const l=s.buffer,o=qh(new Uint8Array(l,r+12,16));let c=null,d=null,h=0;if(i===0)h=28;else{const x=s.getUint32(28);if(!x||n<32+x*16)return{offset:r,size:t};c=[];for(let y=0;y/\(Windows.+Firefox\//i.test(navigator.userAgent),kI={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 tAe(s,t){const r=kI[t];return!!r&&!!r[s.slice(0,4)]}function jF(s,t,r=!0){return!s.split(",").some(n=>!sAe(n,t,r))}function sAe(s,t,r=!0){var n;const a=zj(r);return(n=a==null?void 0:a.isTypeSupported(NF(s,t)))!=null?n:!1}function NF(s,t){return`${t}/mp4;codecs=${s}`}function $Ve(s){if(s){const t=s.substring(0,4);return kI.video[t]}return 2}function ame(s){const t=Gxt();return s.split(",").reduce((r,n)=>{const i=t&&Yxe(n)?9:kI.video[n];return i?(i*2+r)/(r?3:2):(kI.audio[n]+r)/(r?2:1)},0)}const Bbe={};function u8s(s,t=!0){if(Bbe[s])return Bbe[s];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;au8s(r.toLowerCase(),t))}function m8s(s,t){const r=[];if(s){const n=s.split(",");for(let a=0;a4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(UVe(s,"audio")||UVe(s,"video")))return s;if(t){const r=t.split(",");if(r.length>1){if(s){for(let n=r.length;n--;)if(r[n].substring(0,4)===s.substring(0,4))return r[n]}return r[0]}}return t||s}function UVe(s,t){return tAe(s,t)&&sAe(s,t)}function f8s(s){const t=s.split(",");for(let r=0;r2&&n[0]==="avc1"&&(t[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(",")}function p8s(s){if(s.startsWith("av01.")){const t=s.split("."),r=["0","111","01","01","01","0"];for(let n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return s}function qVe(s){const t=zj(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 Uke(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const x8s={supported:!0,powerEfficient:!0,smooth:!0},g8s={supported:!1,smooth:!1,powerEfficient:!1},Wxt={supported:!0,configurations:[],decodingInfoResults:[x8s]};function Kxt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[g8s],error:s}}function y8s(s,t,r,n,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,h=d?parseInt(d):c?1/0:2;let m=null;if(o!=null&&o.length)try{o.length===1&&o[0]?m=t.groups[o[0]].channels:m=o.reduce((x,y)=>{if(y){const v=t.groups[y];if(!v)throw new Error(`Audio track group ${y} not found`);Object.keys(v.channels).forEach(w=>{x[w]=(x[w]||0)+v.channels[w]})}return x},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(x=>Yxe(x))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(n,30)||s.videoRange!=="SDR"&&s.videoRange!==r||s.bitrate>Math.max(a,8e6))||!!m&&Zn(h)&&Object.keys(m).some(x=>parseInt(x)>h)}function Yxt(s,t,r,n={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!r)return Promise.resolve(Wxt);const i=[],l=v8s(s),o=l.length,c=b8s(s,t,o>0),d=c.length;for(let h=o||1*d||1;h--;){const m={type:"media-source"};if(o&&(m.video=l[h%o]),d){m.audio=c[h%d];const x=m.audio.bitrate;m.video&&x&&(m.video.bitrate-=x)}i.push(m)}if(a){const h=navigator.userAgent;if(a.split(",").some(m=>Yxe(m))&&Gxt())return Promise.resolve(Kxt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),i))}return Promise.all(i.map(h=>{const m=w8s(h);return n[m]||(n[m]=r.decodingInfo(h))})).then(h=>({supported:!h.some(m=>!m.supported),configurations:i,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:i,decodingInfoResults:[],error:h}))}function v8s(s){var t;const r=(t=s.videoCodec)==null?void 0:t.split(","),n=Zxt(s),a=s.width||640,i=s.height||480,l=s.frameRate||30,o=s.videoRange.toLowerCase();return r?r.map(c=>{const d={contentType:NF(p8s(c),"video"),width:a,height:i,bitrate:n,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function b8s(s,t,r){var n;const a=(n=s.audioCodec)==null?void 0:n.split(","),i=Zxt(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((h,m)=>{if(m.groupId===o){const x=parseFloat(m.channels||"");a.forEach(y=>{const v={contentType:NF(y,"audio"),bitrate:r?_8s(y,i):i};x&&(v.channels=""+x),h.push(v)})}return h},l):l},[]):[]}function _8s(s,t){if(t<=1)return 1;let r=128e3;return s==="ec-3"?r=768e3:s==="ac-3"&&(r=64e4),Math.min(t/2,r)}function Zxt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function w8s(s){let t="";const{audio:r,video:n}=s;if(n){const a=Uke(n.contentType);t+=`${a}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const a=Uke(r.contentType);t+=`${n?"_":""}${a}_c${r.channels}`}return t}const qke=["NONE","TYPE-0","TYPE-1",null];function j8s(s){return qke.indexOf(s)>-1}const ome=["SDR","PQ","HLG"];function N8s(s){return!!s&&ome.indexOf(s)>-1}var Ace={No:"",Yes:"YES",v2:"v2"};function VVe(s){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=s,a=n!!n).map(n=>n.substring(0,4)).join(","),"supplemental"in t){var r;this.supplemental=t.supplemental;const n=(r=t.supplemental)==null?void 0:r.videoCodec;n&&n!==t.videoCodec&&(this.codecSet+=`,${n.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 GVe(this._audioGroups,t)}hasSubtitleGroup(t){return GVe(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,r){if(r){if(t==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(t==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}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 GVe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function k8s(){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 S8s(s,t){let r=!1,n=[];if(s&&(r=s!=="SDR",n=[s]),t){n=t.allowedVideoRanges||ome.slice(0);const a=n.join("")!=="SDR"&&!t.videoCodec;r=t.preferHDR!==void 0?t.preferHDR:a&&k8s(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const C8s=s=>{const t=new WeakSet;return(r,n)=>{if(s&&(n=s(r,n)),typeof n=="object"&&n!==null){if(t.has(n))return;t.add(n)}return n}},Ql=(s,t)=>JSON.stringify(s,C8s(t));function T8s(s,t,r,n,a){const i=Object.keys(s),l=n==null?void 0:n.channels,o=n==null?void 0:n.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let h=!1,m=!1,x=1/0,y=1/0,v=1/0,w=1/0,b=0,N=[];const{preferHDR:S,allowedVideoRanges:T}=S8s(t,a);for(let $=i.length;$--;){const F=s[i[$]];h||(h=F.channels[2]>0),x=Math.min(x,F.minHeight),y=Math.min(y,F.minFramerate),v=Math.min(v,F.minBitrate),T.filter(Q=>F.videoRanges[Q]>0).length>0&&(m=!0)}x=Zn(x)?x:0,y=Zn(y)?y:0;const A=Math.max(1080,x),I=Math.max(30,y);v=Zn(v)?v:r,r=Math.max(v,r),m||(t=void 0);const D=i.length>1;return{codecSet:i.reduce(($,F)=>{const z=s[F];if(F===$)return $;if(N=m?T.filter(Q=>z.videoRanges[Q]>0):[],D){if(z.minBitrate>r)return b0(F,`min bitrate of ${z.minBitrate} > current estimate of ${r}`),$;if(!z.hasDefaultAudio)return b0(F,"no renditions with default or auto-select sound found"),$;if(o&&F.indexOf(o.substring(0,4))%5!==0)return b0(F,`audio codec preference "${o}" not found`),$;if(l&&!d){if(!z.channels[l])return b0(F,`no renditions with ${l} channel sound found (channels options: ${Object.keys(z.channels)})`),$}else if((!o||d)&&h&&z.channels[2]===0)return b0(F,"no renditions with stereo sound found"),$;if(z.minHeight>A)return b0(F,`min resolution of ${z.minHeight} > maximum of ${A}`),$;if(z.minFramerate>I)return b0(F,`min framerate of ${z.minFramerate} > maximum of ${I}`),$;if(!N.some(Q=>z.videoRanges[Q]>0))return b0(F,`no variants with VIDEO-RANGE of ${Ql(N)} found`),$;if(c&&F.indexOf(c.substring(0,4))%5!==0)return b0(F,`video codec preference "${c}" not found`),$;if(z.maxScore=ame($)||z.fragmentError>s[$].fragmentError)?$:(w=z.minIndex,b=z.maxScore,F)},void 0),videoRanges:N,preferHDR:S,minFramerate:y,minBitrate:v,minIndex:w}}function b0(s,t){Al.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function Xxt(s){return s.reduce((t,r)=>{let n=t.groups[r.groupId];n||(n=t.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const a=r.channels||"2";return n.channels[a]=(n.channels[a]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(t.hasDefaultAudio=!0),n.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function E8s(s,t,r,n){return s.slice(r,n+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(h=>{if(!h)return;const m=t.groups[h];m&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(m.channels).forEach(x=>{c.channels[x]=(c.channels[x]||0)+m.channels[x]}))}),a},{})}function WVe(s){if(!s)return s;const{lang:t,assocLang:r,characteristics:n,channels:a,audioCodec:i}=s;return{lang:t,assocLang:r,characteristics:n,channels:a,audioCodec:i}}function Z0(s,t,r){if("attrs"in s){const n=t.indexOf(s);if(n!==-1)return n}for(let n=0;nn.indexOf(a)===-1)}function GC(s,t){const{audioCodec:r,channels:n}=s;return(r===void 0||(t.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(t.channels||"2"))}function I8s(s,t,r,n,a){const i=t[n],o=t.reduce((x,y,v)=>{const w=y.uri;return(x[w]||(x[w]=[])).push(v),x},{})[i.uri];o.length>1&&(n=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,h=i.codecSet.substring(0,4),m=KVe(t,n,x=>{if(x.videoRange!==c||x.frameRate!==d||x.codecSet.substring(0,4)!==h)return!1;const y=x.audioGroups,v=r.filter(w=>!y||y.indexOf(w.groupId)!==-1);return Z0(s,v,a)>-1});return m>-1?m:KVe(t,n,x=>{const y=x.audioGroups,v=r.filter(w=>!y||y.indexOf(w.groupId)!==-1);return Z0(s,v,a)>-1})}function KVe(s,t,r){for(let n=t;n>-1;n--)if(r(s[n]))return n;for(let n=t+1;n{var n;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),h=i?i.stats:a.stats,m=i?i.duration:a.duration,x=d-h.loading.start,y=l.minAutoLevel,v=a.level,w=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||v<=y){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const b=w>-1&&w!==v,N=!!r||b;if(!N&&(c.paused||!c.playbackRate||!c.readyState))return;const S=l.mainForwardBufferInfo;if(!N&&S===null)return;const T=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(x<=Math.max(T,1e3*(m/(A*2))))return;const I=S?S.len/A:0,D=h.loading.first?h.loading.first-h.loading.start:-1,R=h.loaded&&D>-1,$=this.getBwEstimate(),F=l.levels,z=F[v],Q=Math.max(h.loaded,Math.round(m*(a.bitrate||z.averageBitrate)/8));let K=R?x-D:x;K<1&&R&&(K=Math.min(x,h.loaded*8/$));const X=R?h.loaded*1e3/K:0,Z=T/1e3,re=X?(Q-h.loaded)/X:Q*8/$+Z;if(re<=I)return;const le=X?X*8:$,oe=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,ne=this.hls.config.abrBandWidthUpFactor;let ie=Number.POSITIVE_INFINITY,ye;for(ye=v-1;ye>y;ye--){const Ue=F[ye].maxBitrate,Be=!F[ye].details||oe;if(ie=this.getTimeToLoadFrag(Z,le,m*Ue,Be),ie=re||ie>m*10)return;R?this.bwEstimator.sample(x-Math.min(T,D),h.loaded):this.bwEstimator.sampleTTFB(x);const ce=F[ye].maxBitrate;this.getBwEstimate()*ne>ce&&this.resetEstimator(ce);const ve=this.findBestLevel(ce,y,ye,0,I,1,1);ve>-1&&(ye=ve),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${v} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${I.toFixed(3)} s Estimated load time for current fragment: ${re.toFixed(3)} s Estimated load time for down switch fragment: ${ie.toFixed(3)} s TTFB estimate: ${D|0} ms Current BW estimate: ${Zn($)?$|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${ye} @ ${ce|0} bps`),l.nextLoadLevel=l.nextAutoLevel=ye,this.clearTimer();const be=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===ye&&ye>0){const Ue=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ye>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${Ue.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,ye>y){let Be=this.findBestLevel(this.hls.levels[y].bitrate,y,ye,0,Ue,1,1);Be===-1&&(Be=y),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Be,this.resetEstimator(this.hls.levels[Be].bitrate)}}};b||re>ie*2?be():this.timer=self.setInterval(be,ie*1e3),l.trigger(ht.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:h})},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 FOs(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.FRAG_LOADING,this.onFragLoading,this),t.on(ht.FRAG_LOADED,this.onFragLoaded,this),t.on(ht.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ht.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ht.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(ht.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.FRAG_LOADING,this.onFragLoading,this),t.off(ht.FRAG_LOADED,this.onFragLoaded,this),t.off(ht.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ht.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ht.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(ht.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,r){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,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var a;this.fragCurrent=n,this.partCurrent=(a=r.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,r){this.clearTimer()}onError(t,r){if(!r.fatal)switch(r.details){case ar.BUFFER_ADD_CODEC_ERROR:case ar.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ar.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:a,partCurrent:i}=this;if(n&&a&&n.sn===a.sn&&n.level===a.level){const l=performance.now(),o=i?i.stats:n.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const m=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(m,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,r,n,a){const i=t+n/r,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,r){const n=this.hls.config,{loading:a}=r.stats,i=a.end-a.first;Zn(i)&&(this.lastLevelLoadSec=i/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(r.levelInfo)}onFragLoaded(t,{frag:r,part:n}){const a=n?n.stats:r.stats;if(r.type===ua.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=n?n.duration:r.duration,l=this.hls.levels[r.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(r.bitrateTest){const i={stats:a,frag:r,part:n,id:r.type};this.onFragBuffered(ht.FRAG_BUFFERED,i),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(t,r){const{frag:n,part:a}=r,i=a!=null&&a.stats.loaded?a.stats:n.stats;if(i.aborted||this.ignoreFragment(n))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(),n.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==ua.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,r,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,r),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,n=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!n||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=n&&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:r,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=n,o=r?r.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let h=i.abrBandWidthFactor,m=i.abrBandWidthUpFactor;if(d){const b=this.findBestLevel(c,l,a,d,0,h,m);if(b>=0)return this.rebufferNotice=-1,b}let x=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const b=this.bitrateTestDelay;b&&(x=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-b,this.info(`bitrate test took ${Math.round(1e3*b)}ms, set first fragment max fetchDuration to ${Math.round(1e3*x)} ms`),h=m=1)}const y=this.findBestLevel(c,l,a,d,x,h,m);if(this.rebufferNotice!==y&&(this.rebufferNotice=y,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${y}`)),y>-1)return y;const v=n.levels[l],w=n.loadLevelObj;return w&&(v==null?void 0:v.bitrate)=r;le--){var re;const oe=v[le],ne=le>m;if(!oe)continue;if(N.useMediaCapabilities&&!oe.supportedResult&&!oe.supportedPromise){const Be=navigator.mediaCapabilities;typeof(Be==null?void 0:Be.decodingInfo)=="function"&&y8s(oe,z,D,R,t,$)?(oe.supportedPromise=Yxt(oe,z,Be,this.supportedCache),oe.supportedPromise.then(De=>{if(!this.hls)return;oe.supportedResult=De;const Ae=this.hls.levels,He=Ae.indexOf(oe);De.error?this.warn(`MediaCapabilities decodingInfo error: "${De.error}" for level ${He} ${Ql(De)}`):De.supported?De.decodingInfoResults.some(Le=>Le.smooth===!1||Le.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${He} not smooth or powerEfficient: ${Ql(De)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${He} ${Ql(De)}`),He>-1&&Ae.length>1&&(this.log(`Removing unsupported level ${He}`),this.hls.removeLevel(He),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(De=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${De}`)})):oe.supportedResult=Wxt}if((I&&oe.codecSet!==I||D&&oe.videoRange!==D||ne&&R>oe.frameRate||!ne&&R>0&&RBe.smooth===!1))&&(!A||le!==Q)){Z.push(le);continue}const ie=oe.details,ye=(y?ie==null?void 0:ie.partTarget:ie==null?void 0:ie.averagetargetduration)||K;let ce;ne?ce=o*t:ce=l*t;const ve=K&&a>=K*2&&i===0?oe.averageBitrate:oe.maxBitrate,be=this.getTimeToLoadFrag(X,ce,ve*ye,ie===void 0);if(ce>=ve&&(le===h||oe.loadError===0&&oe.fragmentError===0)&&(be<=X||!Zn(be)||T&&!this.bitrateTestDelay||be${le} adjustedbw(${Math.round(ce)})-bitrate=${Math.round(ce-ve)} ttfb:${X.toFixed(1)} avgDuration:${ye.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${be.toFixed(1)} firstSelection:${A} codecSet:${oe.codecSet} videoRange:${oe.videoRange} hls.loadLevel:${b}`)),A&&(this.firstSelection=le),le}}return-1}set nextAutoLevel(t){const r=this.deriveNextAutoLevel(t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}deriveNextAutoLevel(t){const{maxAutoLevel:r,minAutoLevel:n}=this.hls;return Math.min(Math.max(t,n),r)}}const Qxt={search:function(s,t){let r=0,n=s.length-1,a=null,i=null;for(;r<=n;){a=(r+n)/2|0,i=s[a];const l=t(i);if(l>0)r=a+1;else if(l<0)n=a-1;else return i}return null}};function P8s(s,t,r){if(t===null||!Array.isArray(s)||!s.length||!Zn(t))return null;const n=s[0].programDateTime;if(t<(n||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(r+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else r===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&YVe(r,n,i)===0||D8s(i,s,Math.min(a,n))))return i;const l=Qxt.search(t,YVe.bind(null,r,n));return l&&(l!==s||!i)?l:i}function D8s(s,t,r){if(t&&t.start===0&&t.level0){const n=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),r);return s.start<=n}return!1}function YVe(s=0,t=0,r){if(r.start<=s&&r.start+r.duration>s)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=s?1:r.start-n>s&&r.start?-1:0}function R8s(s,t,r){const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>s}function Jxt(s,t,r){if(s&&s.startCC<=t&&s.endCC>=t){let n=s.fragments;const{fragmentHint:a}=s;a&&(n=n.concat(a));let i;return Qxt.search(n,l=>l.cct?-1:(i=l,l.end<=r?1:l.start>r?-1:0)),i||null}return null}function cme(s){switch(s.details){case ar.FRAG_LOAD_TIMEOUT:case ar.KEY_LOAD_TIMEOUT:case ar.LEVEL_LOAD_TIMEOUT:case ar.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function egt(s){return s.details.startsWith("key")}function tgt(s){return egt(s)&&!!s.frag&&!s.frag.decryptdata}function ZVe(s,t){const r=cme(t);return s.default[`${r?"timeout":"error"}Retry`]}function rAe(s,t){const r=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(r*s.retryDelayMs,s.maxRetryDelayMs)}function XVe(s){return Sl(Sl({},s),{errorRetry:null,timeoutRetry:null})}function dme(s,t,r,n){if(!s)return!1;const a=n==null?void 0:n.code,i=t499)}function Vke(s){return s===0&&navigator.onLine===!1}var Uh={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Tp={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class F8s extends Sg{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(ht.ERROR,this.onError,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(ht.ERROR,this.onError,this),t.off(ht.ERROR,this.onErrorOut,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.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)===ua.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const r=this.hls,n=r.currentLevel;return(t=r.loadLevelObj)!=null&&t.details||n===-1?r.loadLevel:n}variantHasKey(t,r){if(t){var n;if((n=t.details)!=null&&n.hasKey(r))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(r)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,r){var n;if(r.fatal)return;const a=this.hls,i=r.context;switch(r.details){case ar.FRAG_LOAD_ERROR:case ar.FRAG_LOAD_TIMEOUT:case ar.KEY_LOAD_ERROR:case ar.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case ar.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=XA();return}case ar.FRAG_GAP:case ar.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=Uh.SendAlternateToPenaltyBox;return}case ar.LEVEL_EMPTY_ERROR:case ar.LEVEL_PARSING_ERROR:{var l;const c=r.parent===ua.MAIN?r.level:a.loadLevel;r.details===ar.LEVEL_EMPTY_ERROR&&((l=r.context)!=null&&(l=l.levelDetails)!=null&&l.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,c):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,c))}return;case ar.LEVEL_LOAD_ERROR:case ar.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.level));return;case ar.AUDIO_TRACK_LOAD_ERROR:case ar.AUDIO_TRACK_LOAD_TIMEOUT:case ar.SUBTITLE_LOAD_ERROR:case ar.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===ao.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===ao.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.loadLevel),r.errorAction.action=Uh.SendAlternateToPenaltyBox,r.errorAction.flags=Tp.MoveAllAlternatesMatchingHost;return}}return;case ar.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:Uh.SendAlternateToPenaltyBox,flags:Tp.MoveAllAlternatesMatchingHDCP};return;case ar.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ar.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ar.KEY_SYSTEM_NO_SESSION:r.errorAction={action:Uh.SendAlternateToPenaltyBox,flags:Tp.MoveAllAlternatesMatchingKey};return;case ar.BUFFER_ADD_CODEC_ERROR:case ar.REMUX_ALLOC_ERROR:case ar.BUFFER_APPEND_ERROR:if(!r.errorAction){var o;r.errorAction=this.getLevelSwitchAction(r,(o=r.level)!=null?o:a.loadLevel)}return;case ar.INTERNAL_EXCEPTION:case ar.BUFFER_APPENDING_ERROR:case ar.BUFFER_FULL_ERROR:case ar.LEVEL_SWITCH_ERROR:case ar.BUFFER_STALLED_ERROR:case ar.BUFFER_SEEK_OVER_HOLE:case ar.BUFFER_NUDGE_ON_STALL:r.errorAction=XA();return}r.type===La.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=XA())}getPlaylistRetryOrSwitchAction(t,r){const n=this.hls,a=ZVe(n.config.playlistLoadPolicy,t),i=this.playlistError++;if(dme(a,i,cme(t),t.response))return{action:Uh.RetryRequest,flags:Tp.None,retryConfig:a,retryCount:i};const o=this.getLevelSwitchAction(t,r);return a&&(o.retryConfig=a,o.retryCount=i),o}getFragRetryOrSwitchAction(t){const r=this.hls,n=this.getVariantLevelIndex(t.frag),a=r.levels[n],{fragLoadPolicy:i,keyLoadPolicy:l}=r.config,o=ZVe(egt(t)?l:i,t),c=r.levels.reduce((h,m)=>h+m.fragmentError,0);if(a&&(t.details!==ar.FRAG_GAP&&a.fragmentError++,!tgt(t)&&dme(o,c,cme(t),t.response)))return{action:Uh.RetryRequest,flags:Tp.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,n);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,r){const n=this.hls;r==null&&(r=n.loadLevel);const a=this.hls.levels[r];if(a){var i,l;const d=t.details;a.loadError++,d===ar.BUFFER_APPEND_ERROR&&a.fragmentError++;let h=-1;const{levels:m,loadLevel:x,minAutoLevel:y,maxAutoLevel:v}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const w=(i=t.frag)==null?void 0:i.type,N=(w===ua.AUDIO&&d===ar.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===ar.BUFFER_ADD_CODEC_ERROR||d===ar.BUFFER_APPEND_ERROR))&&m.some(({audioCodec:D})=>a.audioCodec!==D),T=t.sourceBufferName==="video"&&(d===ar.BUFFER_ADD_CODEC_ERROR||d===ar.BUFFER_APPEND_ERROR)&&m.some(({codecSet:D,audioCodec:R})=>a.codecSet!==D&&a.audioCodec===R),{type:A,groupId:I}=(l=t.context)!=null?l:{};for(let D=m.length;D--;){const R=(D+x)%m.length;if(R!==x&&R>=y&&R<=v&&m[R].loadError===0){var o,c;const $=m[R];if(d===ar.FRAG_GAP&&w===ua.MAIN&&t.frag){const F=m[R].details;if(F){const z=e5(t.frag,F.fragments,t.frag.start);if(z!=null&&z.gap)continue}}else{if(A===ao.AUDIO_TRACK&&$.hasAudioGroup(I)||A===ao.SUBTITLE_TRACK&&$.hasSubtitleGroup(I))continue;if(w===ua.AUDIO&&(o=a.audioGroups)!=null&&o.some(F=>$.hasAudioGroup(F))||w===ua.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(F=>$.hasSubtitleGroup(F))||N&&a.audioCodec===$.audioCodec||T&&a.codecSet===$.codecSet||!N&&a.codecSet!==$.codecSet)continue}h=R;break}}if(h>-1&&n.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:Uh.SendAlternateToPenaltyBox,flags:Tp.None,nextAutoLevel:h}}return{action:Uh.SendAlternateToPenaltyBox,flags:Tp.MoveAllAlternatesMatchingHost}}onErrorOut(t,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case Uh.DoNothing:break;case Uh.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==ar.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const r=this.hls,n=t.errorAction;if(!n)return;const{flags:a}=n,i=n.nextAutoLevel;switch(a){case Tp.None:this.switchLevel(t,i);break;case Tp.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=r.levels[c],h=d==null?void 0:d.attrs["HDCP-LEVEL"];if(n.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){r.maxHdcpLevel=qke[qke.indexOf(h)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case Tp.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,h=d.length;for(let x=h;x--;)if(this.variantHasKey(d[x],c)){var l,o;this.log(`Banned key found in level ${x} (${d[x].bitrate}bps) or audio group "${(l=d[x].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${qh(c.keyId||[])}`),d[x].fragmentError++,d[x].loadError++,this.log(`Removing level ${x} with key error (${t.error})`),this.hls.removeLevel(x)}const m=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===n&&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(h=>{const m=!this.isTimeBuffered(h.startPTS,h.endPTS,r);return m&&this.removeFragment(c.body),m})}})}detectPartialFragments(t){const r=this.timeRanges;if(!r||t.frag.sn==="initSegment")return;const n=t.frag,a=mE(n),i=this.fragments[a];if(!i||i.buffered&&n.gap)return;const l=!n.relurl;Object.keys(r).forEach(o=>{const c=n.elementaryStreams[o];if(!c)return;const d=r[o],h=l||c.partial===!0;i.range[o]=this.getBufferedTimes(n,t.part,h,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),tU(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}bufferedEnd(t,r){t.buffered=!0,(t.body.endList=r.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=QVe(n,a=>a.fragment.sn>=t))}fragBuffered(t,r){const n=mE(t);let a=this.fragments[n];!a&&r&&(a=this.fragments[n]={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,r,n,a){const i={time:[],partial:n},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let h=0;h=m&&c<=x){i.time.push({startPTS:Math.max(l,a.start(h)),endPTS:Math.min(o,a.end(h))});break}else if(lm){const y=Math.max(l,a.start(h)),v=Math.min(o,a.end(h));v>y&&(i.partial=!0,i.time.push({startPTS:y,endPTS:v}))}else if(o<=m)break}return i}getPartialFragment(t){let r=null,n,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const h=c[d];h&&tU(h)&&(a=h.body.start-o,i=h.body.end+o,t>=a&&t<=i&&(n=Math.min(t-a,i-t),l<=n&&(r=h.body,l=n)))}),r}isEndListAppended(t){const r=this.endListFragments[t];return r!==void 0&&(r.buffered||tU(r))}getState(t){const r=mE(t),n=this.fragments[r];return n?n.buffered?tU(n)?Ou.PARTIAL:Ou.OK:Ou.APPENDING:Ou.NOT_LOADED}isTimeBuffered(t,r,n){let a,i;for(let l=0;l=a&&r<=i)return!0;if(r<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,r){if(r.frag.sn==="initSegment"||r.frag.bitrateTest)return;const n=r.frag,a=r.part?null:r,i=mE(n);this.fragments[i]={body:n,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,r){const{frag:n,part:a,timeRanges:i,type:l}=r;if(n.sn==="initSegment")return;const o=n.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,r){this.detectPartialFragments(r)}hasFragment(t){const r=mE(t);return!!this.fragments[r]}hasFragments(t){const{fragments:r}=this,n=Object.keys(r);if(!t)return n.length>0;for(let a=n.length;a--;){const i=r[n[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var r;return!!((r=this.activePartLists[t])!=null&&r.length)}removeFragmentsInRange(t,r,n,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!==n||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const r=mE(t);t.clearElementaryStreamInfo();const n=this.activePartLists[t.type];if(n){const a=t.sn;this.activePartLists[t.type]=QVe(n,i=>i.fragment.sn!==a)}delete this.fragments[r],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 r=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function tU(s){var t,r,n;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(r=s.range.audio)!=null&&r.partial||(n=s.range.audiovideo)!=null&&n.partial)}function mE(s){return`${s.type}_${s.level}_${s.sn}`}function QVe(s,t){return s.filter(r=>{const n=t(r);return n||r.clearElementaryStreamInfo(),n})}var $j={cbc:0,ctr:1};class z8s{constructor(t,r,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=r,this.aesMode=n}decrypt(t,r){switch(this.aesMode){case $j.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,t);case $j.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},r,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function $8s(s){const t=s.byteLength,r=t&&new DataView(s.buffer).getUint8(t-1);return r?s.slice(0,t-r):s}class U8s{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 r=new DataView(t),n=new Uint32Array(4);for(let a=0;a<4;a++)n[a]=r.getUint32(a*4);return n}initTable(){const t=this.sBox,r=this.invSBox,n=this.subMix,a=n[0],i=n[1],l=n[2],o=n[3],c=this.invSubMix,d=c[0],h=c[1],m=c[2],x=c[3],y=new Uint32Array(256);let v=0,w=0,b=0;for(b=0;b<256;b++)b<128?y[b]=b<<1:y[b]=b<<1^283;for(b=0;b<256;b++){let N=w^w<<1^w<<2^w<<3^w<<4;N=N>>>8^N&255^99,t[v]=N,r[N]=v;const S=y[v],T=y[S],A=y[T];let I=y[N]*257^N*16843008;a[v]=I<<24|I>>>8,i[v]=I<<16|I>>>16,l[v]=I<<8|I>>>24,o[v]=I,I=A*16843009^T*65537^S*257^v*16843008,d[N]=I<<24|I>>>8,h[N]=I<<16|I>>>16,m[N]=I<<8|I>>>24,x[N]=I,v?(v=S^y[y[y[A^S]]],w^=y[y[w]]):v=w=1}}expandKey(t){const r=this.uint8ArrayToUint32Array_(t);let n=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,r,n,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),r,n,a)}softwareDecrypt(t,r,n,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==$j.cbc||r.byteLength!==16)return Al.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=gg(o,t),this.remainderData=null);const c=this.getValidChunk(t);if(!c.length)return null;i&&(n=i);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new U8s),d.expandKey(r);const h=l;return this.currentResult=d.decrypt(c.buffer,0,n),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(t,r,n,a){if(this.key!==r||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,r,n,a));this.key=r,this.fastAesKey=new q8s(this.subtle,r,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new z8s(this.subtle,new Uint8Array(n),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Al.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,r,n,a)))}onWebCryptoError(t,r,n,a){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,r,n,a);const l=this.flush();if(l)return l.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let r=t;const n=t.length-t.length%H8s;return n!==t.length&&(r=t.slice(0,n),this.remainderData=t.slice(n)),r}logOnce(t){this.logEnabled&&(Al.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const JVe=Math.pow(2,17);class G8s{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,r){const n=t.url;if(!n)return Promise.reject(new q1({type:La.NETWORK_ERROR,details:ar.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${n?"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(v=>v[0]==="GAP")){c(tHe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),h=eHe(t);t.loader=d;const m=XVe(a.fragLoadPolicy.default),x={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:JVe};t.stats=d.stats;const y={onSuccess:(v,w,b,N)=>{this.resetLoader(t,d);let S=v.data;b.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16)),o({frag:t,part:null,payload:S,networkDetails:N})},onError:(v,w,b,N)=>{this.resetLoader(t,d),c(new q1({type:La.NETWORK_ERROR,details:ar.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Sl({url:n,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:b,stats:N}))},onAbort:(v,w,b)=>{this.resetLoader(t,d),c(new q1({type:La.NETWORK_ERROR,details:ar.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:b,stats:v}))},onTimeout:(v,w,b)=>{this.resetLoader(t,d),c(new q1({type:La.NETWORK_ERROR,details:ar.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${x.timeout}ms`),networkDetails:b,stats:v}))}};r&&(y.onProgress=(v,w,b,N)=>r({frag:t,part:null,payload:b,networkDetails:N})),d.load(h,x,y)})}loadPart(t,r,n){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||r.gap){c(tHe(t,r));return}const d=this.loader=i?new i(a):new l(a),h=eHe(t,r);t.loader=d;const m=XVe(a.fragLoadPolicy.default),x={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:JVe};r.stats=d.stats,d.load(h,x,{onSuccess:(y,v,w,b)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,r);const N={frag:t,part:r,payload:y.data,networkDetails:b};n(N),o(N)},onError:(y,v,w,b)=>{this.resetLoader(t,d),c(new q1({type:La.NETWORK_ERROR,details:ar.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:r,response:Sl({url:h.url,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:w,stats:b}))},onAbort:(y,v,w)=>{t.stats.aborted=r.stats.aborted,this.resetLoader(t,d),c(new q1({type:La.NETWORK_ERROR,details:ar.INTERNAL_ABORTED,fatal:!1,frag:t,part:r,error:new Error("Aborted"),networkDetails:w,stats:y}))},onTimeout:(y,v,w)=>{this.resetLoader(t,d),c(new q1({type:La.NETWORK_ERROR,details:ar.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:r,error:new Error(`Timeout after ${x.timeout}ms`),networkDetails:w,stats:y}))}})})}updateStatsFromPart(t,r){const n=t.stats,a=r.stats,i=a.total;if(n.loaded+=a.loaded,i){const c=Math.round(t.duration/r.duration),d=Math.min(Math.round(n.loaded/i),c),m=(c-d)*Math.round(n.loaded/d);n.total=n.loaded+m}else n.total=Math.max(n.loaded,n.total);const l=n.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,r){t.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function eHe(s,t=null){const r=t||s,n={frag:s,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=r.byteRangeStartOffset,i=r.byteRangeEndOffset;if(Zn(a)&&Zn(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&W8s((l=s.decryptdata)==null?void 0:l.method)){const d=i-a;d%16&&(c=i+(16-d%16)),a!==0&&(n.resetIV=!0,o=a-16)}n.rangeStart=o,n.rangeEnd=c}return n}function tHe(s,t){const r=new Error(`GAP ${s.gap?"tag":"attribute"} found`),n={type:La.MEDIA_ERROR,details:ar.FRAG_GAP,fatal:!1,frag:s,error:r,networkDetails:null};return t&&(n.part=t),(t||s).stats.aborted=!0,new q1(n)}function W8s(s){return s==="AES-128"||s==="AES-256"}class q1 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class sgt extends Sg{constructor(t,r){super(t,r),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 aAe{constructor(t,r,n,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=sU(),this.buffering={audio:sU(),video:sU(),audiovideo:sU()},this.level=t,this.sn=r,this.id=n,this.size=a,this.part=i,this.partial=l}}function sU(){return{start:0,executeStart:0,executeEnd:0,end:0}}const sHe={length:0,start:()=>0,end:()=>0};class Ai{static isBuffered(t,r){if(t){const n=Ai.getBuffered(t);for(let a=n.length;a--;)if(r>=n.start(a)&&r<=n.end(a))return!0}return!1}static bufferedRanges(t){if(t){const r=Ai.getBuffered(t);return Ai.timeRangesToArray(r)}return[]}static timeRangesToArray(t){const r=[];for(let n=0;n1&&t.sort((h,m)=>h.start-m.start||m.end-h.end);let a=-1,i=[];if(n)for(let h=0;h=t[h].start&&r<=t[h].end&&(a=h);const m=i.length;if(m){const x=i[m-1].end;t[h].start-xx&&(i[m-1].end=t[h].end):i.push(t[h])}else i.push(t[h])}else i=t;let l=0,o,c=r,d=r;for(let h=0;h=m&&r<=x&&(a=h),r+n>=m&&r{const a=n.substring(2,n.length-1),i=r==null?void 0:r[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),n):i})}return t}function nHe(s,t,r){let n=s.variableList;n||(s.variableList=n={});let a,i;if("QUERYPARAM"in t){a=t.QUERYPARAM;try{const l=new self.URL(r).searchParams;if(l.has(a))i=l.get(a);else throw new Error(`"${a}" does not match any query parameter in URI: "${r}"`)}catch(l){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${l.message}`))}}else a=t.NAME,i=t.VALUE;a in n?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${a}"`)):n[a]=i||""}function K8s(s,t,r){const n=t.IMPORT;if(r&&n in r){let a=s.variableList;a||(s.variableList=a={}),a[n]=r[n]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const Y8s=/^(\d+)x(\d+)$/,aHe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ed{constructor(t,r){typeof t=="string"&&(t=ed.parseAttrList(t,r)),zl(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const r=parseInt(this[t],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(t){if(this[t]){let r=(this[t]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let a=0;aNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,r){const n=this[t];return n?parseFloat(n):r}enumeratedString(t){return this[t]}enumeratedStringList(t,r){const n=this[t];return(n?n.split(/[ ,]+/):[]).reduce((a,i)=>(a[i.toLowerCase()]=!0,a),r)}bool(t){return this[t]==="YES"}decimalResolution(t){const r=Y8s.exec(this[t]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(t,r){let n;const a={},i='"';for(aHe.lastIndex=0;(n=aHe.exec(t))!==null;){const l=n[1].trim();let o=n[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(r&&(c||d))o=Hke(r,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":Al.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const Z8s="com.apple.hls.interstitial";function X8s(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function Q8s(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class ngt{constructor(t,r,n=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=(r==null?void 0:r.tagAnchor)||null,this.tagOrder=(a=r==null?void 0:r.tagOrder)!=null?a:n,r){const i=r.attr;for(const l in i)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==i[l]){Al.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=zl(new ed({}),i,t)}if(this.attr=t,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(r==null?void 0:r.endDate)||new Date(this.attr["END-DATE"]);Zn(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?(Al.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 r=this.duration;return r!==null?this._dateAtEnd=new Date(this._startDate.getTime()+r*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Zn(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===Z8s}get isValid(){return!!this.id&&!this._badValueForSameId&&Zn(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 J8s=10;class eFs{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 r=this.lastPartSn-t.lastPartSn,n=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>t.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(r=>{let n=r.decryptdata;return n||(r.setKeyFormat(t.keyFormat),n=r.decryptdata),!!n&&t.matches(n)})}get hasProgramDateTime(){return this.fragments.length?Zn(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||J8s}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 r=this.lastPartIndex;if(r!==-1){for(let n=t.length;n--;)if(t[n].index>r)return t[n].index;return r}}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 ume(s,t){return s.length===t.length?!s.some((r,n)=>r!==t[n]):!1}function iHe(s,t){return!s&&!t?!0:!s||!t?!1:ume(s,t)}function QA(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function iAe(s){switch(s){case"AES-128":case"AES-256":return $j.cbc;case"AES-256-CTR":return $j.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function oAe(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function Gke(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function tFs(s){const t=Gke(s).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function agt(s){const t=function(n,a,i){const l=n[a];n[a]=n[i],n[i]=l};t(s,0,3),t(s,1,2),t(s,4,5),t(s,6,7)}function igt(s){const t=s.split(":");let r=null;if(t[0]==="data"&&t.length===2){const n=t[1].split(";"),a=n[n.length-1].split(",");if(a.length===2){const i=a[0]==="base64",l=a[1];i?(n.splice(-1,1),r=oAe(l)):r=tFs(l)}}return r}const hme=typeof self<"u"?self:void 0;var od={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Gh={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Mce(s){switch(s){case Gh.FAIRPLAY:return od.FAIRPLAY;case Gh.PLAYREADY:return od.PLAYREADY;case Gh.WIDEVINE:return od.WIDEVINE;case Gh.CLEARKEY:return od.CLEARKEY}}function zbe(s){switch(s){case od.FAIRPLAY:return Gh.FAIRPLAY;case od.PLAYREADY:return Gh.PLAYREADY;case od.WIDEVINE:return Gh.WIDEVINE;case od.CLEARKEY:return Gh.CLEARKEY}}function UD(s){const{drmSystems:t,widevineLicenseUrl:r}=s,n=t?[od.FAIRPLAY,od.WIDEVINE,od.PLAYREADY,od.CLEARKEY].filter(a=>!!t[a]):[];return!n[od.WIDEVINE]&&r&&n.push(od.WIDEVINE),n}const ogt=function(s){return hme!=null&&(s=hme.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function sFs(s,t,r,n){let a;switch(s){case od.FAIRPLAY:a=["cenc","sinf"];break;case od.WIDEVINE:case od.PLAYREADY:a=["cenc"];break;case od.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return rFs(a,t,r,n)}function rFs(s,t,r,n){return[{initDataTypes:s,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function nFs(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(r=>r==="persistent-license")))}function lgt(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),n=r.substring(r.indexOf("<"),r.length),l=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=oAe(o).subarray(0,16);return agt(c),c}}return null}let fE={};class wj{static clearKeyUriToKeyIdMap(){fE={}}static setKeyIdForUri(t,r){fE[t]=r}static addKeyIdForUri(t){const r=Object.keys(fE).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),fE[t]=n,n}constructor(t,r,n,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=r,this.keyFormat=n,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!QA(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(Rxt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&ume(t.keyFormatVersions,this.keyFormatVersions)&&iHe(t.iv,this.iv)&&iHe(t.keyId,this.keyId)}isSupported(){if(this.method){if(QA(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Gh.FAIRPLAY:case Gh.WIDEVINE:case Gh.PLAYREADY:case Gh.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,r){if(!this.encrypted||!this.uri)return null;if(QA(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Al.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=iFs(t)),new wj(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=fE[this.uri];if(i&&!ume(this.keyId,i)&&wj.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=igt(this.uri);if(n)switch(this.keyFormat){case Gh.WIDEVINE:if(this.pssh=n,!this.keyId){const i=c8s(n.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=oHe(r));break;case Gh.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=l8s(i,null,n),this.keyId=lgt(n);break}default:{let i=n.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=aFs(r),i||(i=oHe(r),i||(i=fE[this.uri])),i&&(this.keyId=i,wj.setKeyIdForUri(this.uri,i))}return this}}function aFs(s){const t=s==null?void 0:s[Gh.WIDEVINE];return t?t.keyId:null}function oHe(s){const t=s==null?void 0:s[Gh.PLAYREADY];if(t){const r=igt(t.uri);if(r)return lgt(r)}return null}function iFs(s){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=s>>8*(15-r)&255;return t}const lHe=/#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,cHe=/#EXT-X-MEDIA:(.*)/g,oFs=/^#EXT(?:INF|-X-TARGETDURATION):/m,$be=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),lFs=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 X0{static findGroup(t,r){for(let n=0;n0&&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(cHe.lastIndex=0;(a=cHe.exec(t))!==null;){const d=new ed(a[1],n),h=d.TYPE;if(h){const m=o[h],x=i[h]||[];i[h]=x;const y=d.LANGUAGE,v=d["ASSOC-LANGUAGE"],w=d.CHANNELS,b=d.CHARACTERISTICS,N=d["INSTREAM-ID"],S={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||y||"",type:h,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:y,url:d.URI?X0.resolve(d.URI,r):""};if(v&&(S.assocLang=v),w&&(S.channels=w),b&&(S.characteristics=b),N&&(S.instreamId=N),m!=null&&m.length){const T=X0.findGroup(m,S.groupId)||m[0];mHe(S,T,"audioCodec"),mHe(S,T,"textCodec")}x.push(S)}}return i}static parseLevelPlaylist(t,r,n,a,i,l){var o;const c={url:r},d=new eFs(r),h=d.fragments,m=[];let x=null,y=0,v=0,w=0,b=0,N=0,S=null,T=new Obe(a,c),A,I,D,R=-1,$=!1,F=null,z;if($be.lastIndex=0,d.m3u8=t,d.hasVariableRefs=rHe(t),((o=$be.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=$be.exec(t))!==null;){$&&($=!1,T=new Obe(a,c),T.playlistOffset=w,T.setStart(w),T.sn=y,T.cc=b,N&&(T.bitrate=N),T.level=n,x&&(T.initSegment=x,x.rawProgramDateTime&&(T.rawProgramDateTime=x.rawProgramDateTime,x.rawProgramDateTime=null),F&&(T.setByteRange(F),F=null)));const Z=A[1];if(Z){T.duration=parseFloat(Z);const re=(" "+A[2]).slice(1);T.title=re||null,T.tagList.push(re?["INF",Z,re]:["INF",Z])}else if(A[3]){if(Zn(T.duration)){T.playlistOffset=w,T.setStart(w),D&&pHe(T,D,d),T.sn=y,T.level=n,T.cc=b,h.push(T);const re=(" "+A[3]).slice(1);T.relurl=Hke(d,re),Wke(T,S,m),S=T,w+=T.duration,y++,v=0,$=!0}}else{if(A=A[0].match(lFs),!A){Al.warn("No matches on slow regex match for level playlist!");continue}for(I=1;I0&&xHe(d,re,A),y=d.startSN=parseInt(le);break;case"SKIP":{d.skippedSegments&&P1(d,re,A);const ne=new ed(le,d),ie=ne.decimalInteger("SKIPPED-SEGMENTS");if(Zn(ie)){d.skippedSegments+=ie;for(let ce=ie;ce--;)h.push(null);y+=ie}const ye=ne.enumeratedString("RECENTLY-REMOVED-DATERANGES");ye&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ye.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&P1(d,re,A),d.targetduration=Math.max(parseInt(le),1);break;case"VERSION":d.version!==null&&P1(d,re,A),d.version=parseInt(le);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||P1(d,re,A),d.live=!1;break;case"#":(le||oe)&&T.tagList.push(oe?[le,oe]:[le]);break;case"DISCONTINUITY":b++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([re]);break;case"BITRATE":T.tagList.push([re,le]),N=parseInt(le)*1e3,Zn(N)?T.bitrate=N:N=0;break;case"DATERANGE":{const ne=new ed(le,d),ie=new ngt(ne,d.dateRanges[ne.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ie.isValid||d.skippedSegments?d.dateRanges[ie.id]=ie:Al.warn(`Ignoring invalid DATERANGE tag: "${le}"`),T.tagList.push(["EXT-X-DATERANGE",le]);break}case"DEFINE":{{const ne=new ed(le,d);"IMPORT"in ne?K8s(d,ne,l):nHe(d,ne,r)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?P1(d,re,A):h.length>0&&xHe(d,re,A),d.startCC=b=parseInt(le);break;case"KEY":{const ne=dHe(le,r,d);if(ne.isSupported()){if(ne.method==="NONE"){D=void 0;break}D||(D={});const ie=D[ne.keyFormat];ie!=null&&ie.matches(ne)||(ie&&(D=zl({},D)),D[ne.keyFormat]=ne)}else Al.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${le}"`);break}case"START":d.startTimeOffset=uHe(le);break;case"MAP":{const ne=new ed(le,d);if(T.duration){const ie=new Obe(a,c);fHe(ie,ne,n,D),x=ie,T.initSegment=x,x.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=x.rawProgramDateTime)}else{const ie=T.byteRangeEndOffset;if(ie){const ye=T.byteRangeStartOffset;F=`${ie-ye}@${ye}`}else F=null;fHe(T,ne,n,D),x=T,$=!0}x.cc=b;break}case"SERVER-CONTROL":{z&&P1(d,re,A),z=new ed(le),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&&P1(d,re,A);const ne=new ed(le);d.partTarget=ne.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ne=d.partList;ne||(ne=d.partList=[]);const ie=v>0?ne[ne.length-1]:void 0,ye=v++,ce=new ed(le,d),ve=new KOs(ce,T,c,ye,ie);ne.push(ve),T.duration+=ve.duration;break}case"PRELOAD-HINT":{const ne=new ed(le,d);d.preloadHint=ne;break}case"RENDITION-REPORT":{const ne=new ed(le,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ne);break}default:Al.warn(`line parsed but not handled: ${A}`);break}}}S&&!S.relurl?(h.pop(),w-=S.duration,d.partList&&(d.fragmentHint=S)):d.partList&&(Wke(T,S,m),T.cc=b,d.fragmentHint=T,D&&pHe(T,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const Q=h.length,K=h[0],X=h[Q-1];if(w+=d.skippedSegments*d.targetduration,w>0&&Q&&X){d.averagetargetduration=w/Q;const Z=X.sn;d.endSN=Z!=="initSegment"?Z:0,d.live||(X.endList=!0),R>0&&(dFs(h,R),K&&m.unshift(K))}return d.fragmentHint&&(w+=d.fragmentHint.duration),d.totalduration=w,m.length&&d.dateRangeTagCount&&K&&cgt(m,d),d.endCC=b,d}}function cgt(s,t){let r=s.length;if(!r)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),r++}else return;const n=s[r-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=n.ref;for(let h=r;h--;){var l;if(((l=s[h])==null?void 0:l.sn)=o||n===0){var l;const c=(((l=r[n+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=r[n].sn-s.startSN;if(d<0)return-1;const h=s.fragments;if(h.length>r.length){const x=(r[n+1]||h[h.length-1]).sn-s.startSN;for(let y=x;y>d;y--){const v=h[y].programDateTime;if(t>=v&&tn);["video","audio","text"].forEach(n=>{const a=r.filter(i=>tAe(i,n));a.length&&(t[`${n}Codec`]=a.map(i=>i.split("/")[0]).join(","),r=r.filter(i=>a.indexOf(i)===-1))}),t.unknownCodecs=r}function mHe(s,t,r){const n=t[r];n&&(s[r]=n)}function dFs(s,t){let r=s[t];for(let n=t;n--;){const a=s[n];if(!a)return;a.programDateTime=r.programDateTime-a.duration*1e3,r=a}}function Wke(s,t,r){s.rawProgramDateTime?r.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function fHe(s,t,r,n){s.relurl=t.URI,t.BYTERANGE&&s.setByteRange(t.BYTERANGE),s.level=r,s.sn="initSegment",n&&(s.levelkeys=n),s.initSegment=null}function pHe(s,t,r){s.levelkeys=t;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==t)&&Object.keys(t).some(a=>t[a].isCommonEncryption)&&n.push(s)}function P1(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function xHe(s,t,r){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function Ube(s,t){const r=t.startPTS;if(Zn(r)){let n=0,a;t.sn>s.sn?(n=r-s.start,a=s):(n=s.start-r,a=t),a.duration!==n&&a.setDuration(n)}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 dgt(s,t,r,n,a,i,l){n-r<=0&&(l.warn("Fragment should have a positive duration",t),n=r+t.duration,i=a+t.duration);let c=r,d=n;const h=t.startPTS,m=t.endPTS;if(Zn(h)){const N=Math.abs(h-r);s&&N>s.totalduration?l.warn(`media timestamps and playlist times differ by ${N}s for level ${t.level} ${s.url}`):Zn(t.deltaPTS)?t.deltaPTS=Math.max(N,t.deltaPTS):t.deltaPTS=N,c=Math.max(r,h),r=Math.min(r,h),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(n,m),n=Math.max(n,m),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const x=r-t.start;t.start!==0&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=c,t.startDTS=a,t.endPTS=n,t.minEndPTS=d,t.endDTS=i;const y=t.sn;if(!s||ys.endSN)return 0;let v;const w=y-s.startSN,b=s.fragments;for(b[w]=t,v=w;v>0;v--)Ube(b[v],b[v-1]);for(v=w;v=0;h--){const m=a[h].initSegment;if(m){n=m;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;fFs(s,t,(h,m,x,y)=>{if((!t.startCC||t.skippedSegments)&&m.cc!==h.cc){const v=h.cc-m.cc;for(let w=x;w{var m;h&&(!h.initSegment||h.initSegment.relurl===((m=n)==null?void 0:m.relurl))&&(h.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(h=>!h),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=t.skippedSegments;h--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=hFs(s.dateRanges,t,r));const h=s.fragments.filter(m=>m.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let m=1;m{m.elementaryStreams=h.elementaryStreams,m.stats=h.stats}),i?dgt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,r):ugt(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 h=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=h),t.driftEndTime=d,t.driftEnd=h}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function hFs(s,t,r){const{dateRanges:n,recentlyRemovedDateranges:a}=t,i=zl({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(n).forEach(c=>{const d=i[c],h=new ngt(n[c].attr,d);h.isValid?(i[c]=h,d||(h.tagOrder+=o)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ql(n[c].attr)}"`)}),i):n}function mFs(s,t,r){if(s&&t){let n=0;for(let a=0,i=s.length;a<=i;a++){const l=s[a],o=t[a+n];l&&o&&l.index===o.index&&l.fragment.sn===o.fragment.sn?r(l,o):n--}}}function fFs(s,t,r){const n=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(n?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 h=c[l+d];let m=o[d];if(n&&!m&&h&&(m=t.fragments[d]=h),h&&m){r(h,m,d,o);const x=h.relurl,y=m.relurl;if(x&&pFs(x,y)){t.playlistParsingError=gHe(`media sequence mismatch ${m.sn}:`,s,t,h,m);return}else if(h.cc!==m.cc){t.playlistParsingError=gHe(`discontinuity sequence mismatch (${h.cc}!=${m.cc})`,s,t,h,m);return}}}}function gHe(s,t,r,n,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function ugt(s,t,r=!0){const n=t.startSN+t.skippedSegments-s.startSN,a=s.fragments,i=n>=0;let l=0;if(i&&nt){const i=n[n.length-1].duration*1e3;i{var n;(n=t.details)==null||n.fragments.forEach(a=>{a.level=r,a.initSegment&&(a.initSegment.level=r)})})}function pFs(s,t){return s!==t&&t?vHe(s)!==vHe(t):!1}function vHe(s){return s.replace(/\?[^?]*$/,"")}function OO(s,t){for(let n=0,a=s.length;ns.startCC)}function bHe(s,t){const r=s.start+t;s.startPTS=r,s.setStart(r),s.endPTS=r+s.duration}function xgt(s,t){const r=t.fragments;for(let n=0,a=r.length;n{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:h}=this,m=c?c.currentTime:0,x=Ai.bufferInfo(d||c,m,l.maxBufferHole),y=!x.len;if(this.log(`Media seeking to ${Zn(m)?m.toFixed(3):m}, state: ${h}, ${y?"out of":"in"} buffer`),this.state===Or.ENDED)this.resetLoadingState();else if(o){const v=l.maxFragLookUpTolerance,w=o.start-v,b=o.start+o.duration+v;if(y||bx.end){const N=m>b;(mv&&(this.lastCurrentTime=m),!this.loadingParts){const w=Math.max(x.end,m),b=this.shouldLoadParts(this.getLevelDetails(),w);b&&(this.log(`LL-Part loading ON after seeking to ${m.toFixed(2)} with buffer @${w.toFixed(2)}`),this.loadingParts=b)}}this.hls.hasEnoughToStart||(this.log(`Setting ${y?"startPosition":"nextLoadPosition"} to ${m} for seek without enough to start`),this.nextLoadPosition=m,y&&(this.startPosition=m)),y&&this.state===Or.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 G8s(t.config),this.keyLoader=n,this.fragmentTracker=r,this.config=t.config,this.decrypter=new nAe(t.config)}registerListeners(){const{hls:t}=this;t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ht.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ht.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Or.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=Or.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:r}=this;return r===-1&&t?t:r}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,r){if(r.live||!this.media)return!1;const n=t.end||0,a=this.config.timelineOffset||0;if(n<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=Ai.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,r,n,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===Or.FRAG_LOADING||!this.fragCurrent&&l===Or.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Or.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(ht.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===Or.STOPPED||this.state===Or.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var r;const{fragmentTracker:n}=this;if(n.getState(t)===Ou.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))&&n.removeFragment(t)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(t.type)&&(n.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),n.getState(t)===Ou.PARTIAL&&n.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const r=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const r=t.details;return(r==null?void 0:r.live)&&r.type!=="EVENT"&&(this.levelLastLoaded!==t||r.expired)}flushMainBuffer(t,r,n=null){if(!(t-r))return;const a={startOffset:t,endOffset:r,type:n};this.hls.trigger(ht.BUFFER_FLUSHING,a)}_loadInitSegment(t,r){this._doFragLoad(t,r).then(n=>{const a=n==null?void 0:n.frag;if(!a||this.fragContextChanged(a)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:a}=this,{frag:i,payload:l}=n,o=i.decryptdata;if(l&&l.byteLength>0&&o!=null&&o.key&&o.iv&&QA(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,iAe(o.method)).catch(d=>{throw a.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const h=self.performance.now();return a.trigger(ht.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:h}}),n.payload=d,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===Or.STOPPED||this.state===Or.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=t.frag.stats;this.state!==Or.STOPPED&&(this.state=Or.IDLE),t.frag.data=new Uint8Array(t.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,r){var n,a;const i=t.tracks;if(i&&!r.encrypted&&((n=i.audio)!=null&&n.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(r)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(ht.ERROR,{type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:r}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:r}=this;return!t||!r||t.sn!==r.sn||t.level!==r.level}fragBufferedComplete(t,r){const n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)} > buffer:${n?yFs.toString(Ai.getBuffered(n)):"(detached)"})`),Yd(t)){var a;if(t.type!==ua.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=Or.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=Or.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new aAe(n.level,n.sn,n.stats.chunkCount+1,0,a?a.index:-1,!l);r.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,r,n=null,a){var i;this.fragCurrent=t;const l=r.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=Or.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(x=>{if(!this.fragContextChanged(x.frag))return this.hls.trigger(ht.KEY_LOADED,x),this.state===Or.KEY_LOADING&&(this.state=Or.IDLE),x}),this.hls.trigger(ht.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(Yd(t)&&(!c||t.sn!==c.sn)){const x=this.shouldLoadParts(r.details,t.end);x!==this.loadingParts&&(this.log(`LL-Part loading ${x?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=x)}if(n=Math.max(t.start,n||0),this.loadingParts&&Yd(t)){const x=l.partList;if(x&&a){n>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const y=this.getNextPart(x,t,n);if(y>-1){const v=x[y];t=this.fragCurrent=v.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${v.index} (${y}/${x.length-1}) of ${this.fragInfo(t,!1,v)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=v.start+v.duration,this.state=Or.FRAG_LOADING;let w;return o?w=o.then(b=>!b||this.fragContextChanged(b.frag)?null:this.doFragPartsLoad(t,v,r,a)).catch(b=>this.handleFragLoadError(b)):w=this.doFragPartsLoad(t,v,r,a).catch(b=>this.handleFragLoadError(b)),this.hls.trigger(ht.FRAG_LOADING,{frag:t,part:v,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):w}else if(!t.url||this.loadedEndOfParts(x,n))return Promise.resolve(null)}}if(Yd(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(x=>x.loaded).map(x=>`[${x.start}-${x.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(n.toFixed(3))}`),Zn(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Or.FRAG_LOADING;const h=this.config.progressive&&t.type!==ua.SUBTITLE;let m;return h&&o?m=o.then(x=>!x||this.fragContextChanged(x.frag)?null:this.fragmentLoader.load(t,a)).catch(x=>this.handleFragLoadError(x)):m=Promise.all([this.fragmentLoader.load(t,h?a:void 0),o]).then(([x])=>(!h&&a&&a(x),x)).catch(x=>this.handleFragLoadError(x)),this.hls.trigger(ht.FRAG_LOADING,{frag:t,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):m}doFragPartsLoad(t,r,n,a){return new Promise((i,l)=>{var o;const c=[],d=(o=n.details)==null?void 0:o.partList,h=m=>{this.fragmentLoader.loadPart(t,m,a).then(x=>{c[m.index]=x;const y=x.part;this.hls.trigger(ht.FRAG_LOADED,x);const v=yHe(n.details,t.sn,m.index+1)||fgt(d,t.sn,m.index+1);if(v)h(v);else return i({frag:t,part:y,partsLoaded:c})}).catch(l)};h(r)})}handleFragLoadError(t){if("data"in t){const r=t.data;r.frag&&r.details===ar.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===La.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(ht.ERROR,r)}else this.hls.trigger(ht.ERROR,{type:La.OTHER_ERROR,details:ar.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const r=this.getCurrentContext(t);if(!r||this.state!==Or.PARSING){!this.fragCurrent&&this.state!==Or.STOPPED&&this.state!==Or.ERROR&&(this.state=Or.IDLE);return}const{frag:n,part:a,level:i}=r,l=self.performance.now();n.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(n,a,i,t.partial)}shouldLoadParts(t,r){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var n;const i=t.partList[0];if(i.fragment.type===ua.SUBTITLE)return!1;const l=i.end+(((n=t.fragmentHint)==null?void 0:n.duration)||0);if(r>=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:r,fragCurrent:n}=this,{level:a,sn:i,part:l}=t;if(!(r!=null&&r[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=r[a],c=o.details,d=l>-1?yHe(c,i,l):null,h=d?d.fragment:mgt(c,i,n);return h?(n&&n!==h&&(h.stats=n.stats),{frag:h,part:d,level:o}):null}bufferFragmentData(t,r,n,a,i){if(this.state!==Or.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=gg(l,o)),!c.length)return;const d=this.initPTS[r.cc],h=d?-d.baseTime/d.timescale:void 0,m={type:t.type,frag:r,part:n,chunkMeta:a,offset:h,parent:r.type,data:c};if(this.hls.trigger(ht.BUFFER_APPENDING,m),t.dropped&&t.independent&&!n){if(i)return;this.flushBufferGap(r)}}flushBufferGap(t){const r=this.media;if(!r)return;if(!Ai.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,t.start);return}const n=r.currentTime,a=Ai.bufferInfo(r,n,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),n+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,r){var n;const a=this.getLoadPosition();if(!Zn(a))return null;const l=this.lastCurrentTime>a||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,r,l)}getFwdBufferInfoAtPos(t,r,n,a){const i=Ai.bufferInfo(t,r,a);if(i.len===0&&i.nextStart!==void 0){const l=this.fragmentTracker.getBufferedFrag(r,n);if(l&&(i.nextStart<=l.end||l.gap)){const o=Math.max(Math.min(i.nextStart,l.end)-r,a);return Ai.bufferInfo(t,r,o)}}return i}getMaxBufferLength(t){const{config:r}=this;let n;return t?n=Math.max(8*r.maxBufferSize/t,r.maxBufferLength):n=r.maxBufferLength,Math.min(n,r.maxMaxBufferLength)}exceedsMaxBuffer(t,r,n){const a=t.nextStart;if(a&&n.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=r}}return!1}reduceMaxBufferLength(t,r){const n=this.config,a=Math.max(Math.min(t-r,n.maxBufferLength),r),i=Math.max(t-r*3,n.maxMaxBufferLength/2,a);return i>=a?(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t,r=ua.MAIN){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,r):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(t,r){const n=r.fragments,a=n.length;if(!a)return null;const{config:i}=this,l=r.fragmentStart,o=i.lowLatencyMode&&!!r.partList;let c=null;if(r.live){const m=i.initialLiveManifestSize;if(a=l?(b=y,N=y===x?"config":"next load start"):v!==null?(b=v,N="live edge"):(b=t,N="buffer pos"),b=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(_He(this.config)){var t;if((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,r){if(!t)return t;if(_He(this.config)&&t.type!==ua.SUBTITLE){const n=this.hls.interstitialsManager,a=n==null?void 0:n.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&&(r==null?void 0:r.live)===!1||t.start>a.end&&a.nextEvent&&(a.nextEvent.appendInPlace||t.start-a.end>1))return null}const i=n==null?void 0:n.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,r,n){let a=-1,i=!1,l=!0;for(let o=0,c=t.length;o-1&&nn.start)return!0}return!1}getInitialLiveFragment(t){const r=t.fragments,n=this.fragPrevious;let a=null;if(n){if(t.hasProgramDateTime&&(a=P8s(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance),a&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!a){const i=n.sn+1;if(i>=t.startSN&&i<=t.endSN){const l=r[i-t.startSN];n.cc===l.cc&&(a=l,this.log(`Live playlist, switching playlist, load frag with next SN: ${a.sn}`))}a||(a=Jxt(t,n.cc,n.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,r,n){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=n;const{fragmentHint:c}=n,{maxFragLookUpTolerance:d}=a,h=n.partList,m=!!(this.loadingParts&&h!=null&&h.length&&c);m&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let x;if(tr-d||(y=this.media)!=null&&y.paused||!this.startFragRequested?0:d;x=e5(i,l,t,w)}else x=l[l.length-1];if(x){const v=x.sn-n.startSN,w=this.fragmentTracker.getState(x);if((w===Ou.OK||w===Ou.PARTIAL&&x.gap)&&(i=x),i&&x.sn===i.sn&&(!m||h[0].fragment.sn>x.sn||!n.live)&&x.level===i.level){const N=l[v+1];x.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,r){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(t,r){this.transmuxer&&t.type===this.playlistType&&Yd(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${r?" part "+r.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==Or.FRAG_LOADING_WAITING_RETRY)&&(this.state=Or.IDLE)}onFragmentOrKeyLoadError(t,r){var n;if(r.chunkMeta&&!r.frag){const N=this.getCurrentContext(r.chunkMeta);N&&(r.frag=N.frag)}const a=r.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=r.details===ar.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=r.errorAction;if(!o){this.state=Or.ERROR;return}const{action:c,flags:d,retryCount:h=0,retryConfig:m}=o,x=!!m,y=x&&c===Uh.RetryRequest,v=x&&!o.resolved&&d===Tp.MoveAllAlternatesMatchingHost,w=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!y&&v&&Yd(a)&&!a.endList&&w&&!tgt(r))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((y||v)&&h=r||n&&!Vke(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Or.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Or.PARSING||this.state===Or.PARSED){const r=t.frag,n=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,n),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(r==null?void 0:r.duration)||10);const l=!i;return l&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===ua.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Or.STOPPED&&(this.state=Or.IDLE)}afterBufferFlushed(t,r,n){if(!t)return;const a=Ai.getBuffered(t);this.fragmentTracker.detectEvictedFragments(r,a,n),this.state===Or.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Or.STOPPED&&(this.state=Or.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,r=t?t.details:null;r!=null&&r.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(r,r.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,r,n,a){const i=n.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const h=t.elementaryStreams[d];if(h){const m=h.endPTS-h.startPTS;if(m<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${m})`),c||!1;const x=a?0:dgt(i,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(ht.LEVEL_PTS_UPDATED,{details:i,level:n,drift:x,type:d,frag:t,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((n.fragmentError===0||c&&(n.fragmentError<2||t.endList))&&this.treatAsGap(t,n),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(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Or.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${r?" part: "+r.index:""} of ${this.fragInfo(t,!1,r)})`),this.hls.trigger(ht.FRAG_PARSED,{frag:t,part:r})}playlistLabel(){return this.playlistType===ua.MAIN?"level":"track"}fragInfo(t,r=!0,n){var a,i;return`${this.playlistLabel()} ${t.level} (${n?"part":"frag"}:[${((a=r&&!n?t.startPTS:(n||t).start)!=null?a:NaN).toFixed(3)}-${((i=r&&!n?t.endPTS:(n||t).end)!=null?i:NaN).toFixed(3)}]${n&&t.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""}`}treatAsGap(t,r){r&&r.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 r=this._state;r!==t&&(this._state=t,this.log(`${r}->${t}`))}get state(){return this._state}}function _He(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class ygt{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:r}=this;let n;if(t.length)t.length===1?n=t[0]:n=vFs(t,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function vFs(s,t){const r=new Uint8Array(t);let n=0;for(let a=0;a0)return s.subarray(r,r+n)}function SFs(s,t,r,n){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[r+2],l=i>>2&15;if(l>12){const y=new Error(`invalid ADTS sampling index:${l}`);s.emit(ht.ERROR,ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_PARSING_ERROR,fatal:!0,error:y,reason:y.message});return}const o=(i>>6&3)+1,c=t[r+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,h=a[l];let m=l;(o===5||o===29)&&(m-=3);const x=[o<<3|(m&14)>>1,(m&1)<<7|c<<3];return Al.log(`manifest codec:${n}, parsed codec:${d}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${l})`),{config:x,samplerate:h,channelCount:c,codec:d,parsedCodec:d,manifestCodec:n}}function bgt(s,t){return s[t]===255&&(s[t+1]&246)===240}function _gt(s,t){return s[t+1]&1?7:9}function uAe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function CFs(s,t){return t+5=s.length)return!1;const n=uAe(s,t);if(n<=r)return!1;const a=t+n;return a===s.length||fme(s,a)}return!1}function wgt(s,t,r,n,a){if(!s.samplerate){const i=SFs(t,r,n,a);if(!i)return;zl(s,i)}}function jgt(s){return 1024*9e4/s}function AFs(s,t){const r=_gt(s,t);if(t+r<=s.length){const n=uAe(s,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function Ngt(s,t,r,n,a){const i=jgt(s.samplerate),l=n+a*i,o=AFs(t,r);let c;if(o){const{frameLength:m,headerLength:x}=o,y=x+m,v=Math.max(0,r+y-t.length);v?(c=new Uint8Array(y-x),c.set(t.subarray(r+x,t.length),0)):c=t.subarray(r+x,r+y);const w={unit:c,pts:l};return v||s.samples.push(w),{sample:w,length:y,missing:v}}const d=t.length-r;return c=new Uint8Array(d),c.set(t.subarray(r,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function MFs(s,t){return dAe(s,t)&&Zxe(s,t+6)+10<=s.length-t}function IFs(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Vbe(s,t=0,r=1/0){return LFs(s,t,r,Uint8Array)}function LFs(s,t,r,n){const a=PFs(s);let i=1;"BYTES_PER_ELEMENT"in n&&(i=n.BYTES_PER_ELEMENT);const l=DFs(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(d+Math.max(r,0),o));return new n(a,d,h-d)}function PFs(s){return s instanceof ArrayBuffer?s:s.buffer}function DFs(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function RFs(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(s.size<2)return;if(s.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=s.data.subarray(1).indexOf(0);if(n===-1)return;const a=ex(Vbe(s.data,1,n)),i=s.data[2+n],l=s.data.subarray(3+n).indexOf(0);if(l===-1)return;const o=ex(Vbe(s.data,3+n,l));let c;return a==="-->"?c=ex(Vbe(s.data,4+n+l)):c=IFs(s.data.subarray(4+n+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function OFs(s){if(s.size<2)return;const t=ex(s.data,!0),r=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:r.buffer}}function FFs(s){if(s.size<2)return;if(s.type==="TXXX"){let r=1;const n=ex(s.data.subarray(r),!0);r+=n.length+1;const a=ex(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=ex(s.data.subarray(1));return{key:s.type,info:"",data:t}}function BFs(s){if(s.type==="WXXX"){if(s.size<2)return;let r=1;const n=ex(s.data.subarray(r),!0);r+=n.length+1;const a=ex(s.data.subarray(r));return{key:s.type,info:n,data:a}}const t=ex(s.data);return{key:s.type,info:"",data:t}}function zFs(s){return s.type==="PRIV"?OFs(s):s.type[0]==="W"?BFs(s):s.type==="APIC"?RFs(s):FFs(s)}function $Fs(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),r=Zxe(s,4),n=10;return{type:t,size:r,data:s.subarray(n,n+r)}}const rU=10,UFs=10;function kgt(s){let t=0;const r=[];for(;dAe(s,t);){const n=Zxe(s,t+6);s[t+5]>>6&1&&(t+=rU),t+=rU;const a=t+n;for(;t+UFs0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Rp.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Zn(s))return s*90;const n=r?r.baseTime*9e4/r.timescale:0;return t*9e4+n};let nU=null;const HFs=[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],GFs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],WFs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],KFs=[0,1,1,4];function Cgt(s,t,r,n,a){if(r+24>t.length)return;const i=Tgt(t,r);if(i&&r+i.frameLength<=t.length){const l=i.samplesPerFrame*9e4/i.sampleRate,o=n+a*l,c={unit:t.subarray(r,r+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 Tgt(s,t){const r=s[t+1]>>3&3,n=s[t+1]>>1&3,a=s[t+2]>>4&15,i=s[t+2]>>2&3;if(r!==1&&a!==0&&a!==15&&i!==3){const l=s[t+2]>>1&1,o=s[t+3]>>6,c=r===3?3-n:n===3?3:4,d=HFs[c*14+a-1]*1e3,m=GFs[(r===3?0:r===2?1:2)*3+i],x=o===3?1:2,y=WFs[r][n],v=KFs[n],w=y*8*v,b=Math.floor(y*d/m+l)*v;if(nU===null){const T=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);nU=T?parseInt(T[1]):0}return!!nU&&nU<=87&&n===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:m,channelCount:x,frameLength:b,samplesPerFrame:w}}}function fAe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function Egt(s,t){return t+1{let r=0,n=5;t+=n;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;n>0;){l[0]=s[t];const o=Math.min(n,8),c=8-o;i[0]=4278190080>>>24+c<>c,r=r?r<t.length||t[r]!==11||t[r+1]!==119)return-1;const i=t[r+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[r+4]&63,h=[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(r+h>t.length)return-1;const m=t[r+6]>>5;let x=0;m===2?x+=2:(m&1&&m!==1&&(x+=2),m&4&&(x+=2));const y=(t[r+6]<<8|t[r+7])>>12-x&1,w=[2,1,2,3,3,4,4,5][m]+y,b=t[r+5]>>3,N=t[r+5]&7,S=new Uint8Array([i<<6|b<<1|N>>2,(N&3)<<6|m<<3|y<<2|c>>4,c<<4&224]),T=1536/o*9e4,A=n+a*T,I=t.subarray(r,r+h);return s.config=S,s.channelCount=w,s.samplerate=o,s.samples.push({unit:I,pts:A}),h}class QFs extends mAe{resetInitSegment(t,r,n,a){super.resetInitSegment(t,r,n,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const r=CF(t,0);let n=(r==null?void 0:r.length)||0;if(r&&t[n]===11&&t[n+1]===119&&hAe(r)!==void 0&&Mgt(t,n)<=16)return!1;for(let a=t.length;n{const l=i8s(i);if(JFs.test(l.schemeIdUri)){const o=jHe(l,r);let c=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=l.payload;n.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:Rp.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=jHe(l,r);n.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:Rp.misbklv,duration:Number.POSITIVE_INFINITY})}})}return n}demuxSampleAes(t,r,n){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 jHe(s,t){return Zn(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class tBs{constructor(t,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new nAe(r,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,$j.cbc)}decryptAacSample(t,r,n){const a=t[r].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,r+1,n)}).catch(n)}decryptAacSamples(t,r,n){for(;;r++){if(r>=t.length){n();return}if(!(t[r].unit.length<32)&&(this.decryptAacSample(t,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const r=Math.floor((t.length-48)/160)*16+16,n=new Int8Array(r);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,r,n+1,a)}).catch(a)}decryptAvcSamples(t,r,n,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=t.length){a();return}const i=t[r].units;for(;!(n>=i.length);n++){const l=i[n];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,r,n,a,l),!this.decrypter.isSync()))return}}}}class Lgt{constructor(){this.VideoSample=null}createVideoSample(t,r,n){return{key:t,frame:!1,pts:r,dts:n,units:[],length:0}}getLastNalUnit(t){var r;let n=this.VideoSample,a;if((!n||n.units.length===0)&&(n=t[t.length-1]),(r=n)!=null&&r.units){const i=n.units;a=i[i.length-1]}return a}pushAccessUnit(t,r){if(t.units.length&&t.frame){if(t.pts===void 0){const n=r.samples,a=n.length;if(a){const i=n[a-1];t.pts=i.pts,t.dts=i.dts}else{r.dropped++;return}}r.samples.push(t)}}parseNALu(t,r,n){const a=r.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,h,m,x=-1,y=0;for(i===-1&&(x=0,y=this.getNALuType(r,0),i=0,c=1);c=0){const v={data:r.subarray(x,h),type:y};o.push(v)}else{const v=this.getLastNalUnit(t.samples);v&&(l&&c<=4-l&&v.state&&(v.data=v.data.subarray(0,v.data.byteLength-l)),h>0&&(v.data=gg(v.data,r.subarray(0,h)),v.state=0))}c=0&&i>=0){const v={data:r.subarray(x,a),type:y,state:i};o.push(v)}if(o.length===0){const v=this.getLastNalUnit(t.samples);v&&(v.data=gg(v.data,r))}return t.naluState=i,o}}class FO{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,r=this.bytesAvailable,n=t.byteLength-r,a=new Uint8Array(4),i=Math.min(4,r);if(i===0)throw new Error("no bytes available");a.set(t.subarray(n,n+i)),this.word=new DataView(a.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let r;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,r=t>>3,t-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let r=Math.min(this.bitsAvailable,t);const n=this.word>>>32-r;if(t>32&&Al.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=t-r,r>0&&this.bitsAvailable?n<>>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 sBs extends Lgt{parsePES(t,r,n,a){const i=this.parseNALu(t,n.data,a);let l=this.VideoSample,o,c=!1;n.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(d=>{var h,m;switch(d.type){case 1:{let w=!1;o=!0;const b=d.data;if(c&&b.length>4){const N=this.readSliceType(b);(N===2||N===4||N===7||N===9)&&(w=!0)}if(w){var x;(x=l)!=null&&x.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.frame=!0,l.key=w;break}case 5:o=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,eAe(d.data,1,n.pts,r.samples);break}case 7:{var y,v;o=!0,c=!0;const w=d.data,b=this.readSPS(w);if(!t.sps||t.width!==b.width||t.height!==b.height||((y=t.pixelRatio)==null?void 0:y[0])!==b.pixelRatio[0]||((v=t.pixelRatio)==null?void 0:v[1])!==b.pixelRatio[1]){t.width=b.width,t.height=b.height,t.pixelRatio=b.pixelRatio,t.sps=[w];const N=w.subarray(1,4);let S="avc1.";for(let T=0;T<3;T++){let A=N[T].toString(16);A.length<2&&(A="0"+A),S+=A}t.codec=S}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.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,r){return t[r]&31}readSliceType(t){const r=new FO(t);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(t,r){let n=8,a=8,i;for(let l=0;l{var h,m;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,n.pts,n.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var x;(x=l)!=null&&x.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(h=l)!=null&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,eAe(d.data,2,n.pts,r.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=zl(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 y=this.readSPS(d.data);t.width=y.width,t.height=y.height,t.pixelRatio=y.pixelRatio,t.codec=y.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const v in y.params)t.params[v]=y.params[v]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const y=this.readPPS(d.data);for(const v in y)t.params[v]=y[v]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(m=l)!=null&&m.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,r,n){(n&&n[0]===this.initVPS||!n&&!t.length)&&t.push(r)}getNALuType(t,r){return(t[r]&126)>>>1}ebsp2rbsp(t){const r=new Uint8Array(t.byteLength);let n=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(r[n]=t[a],n++);return new Uint8Array(r.buffer,0,n)}pushAccessUnit(t,r){super.pushAccessUnit(t,r),this.initVPS&&(this.initVPS=null)}readVPS(t){const r=new FO(t);r.readUByte(),r.readUByte(),r.readBits(4),r.skipBits(2),r.readBits(6);const n=r.readBits(3),a=r.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:a}}readSPS(t){const r=new FO(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const a=r.readBits(2),i=r.readBoolean(),l=r.readBits(5),o=r.readUByte(),c=r.readUByte(),d=r.readUByte(),h=r.readUByte(),m=r.readUByte(),x=r.readUByte(),y=r.readUByte(),v=r.readUByte(),w=r.readUByte(),b=r.readUByte(),N=r.readUByte(),S=[],T=[];for(let Oe=0;Oe0)for(let Oe=n;Oe<8;Oe++)r.readBits(2);for(let Oe=0;Oe1&&r.readEG();for(let tt=0;tt0&&Ke<16?(ve=Ze[Ke-1],be=lt[Ke-1]):Ke===255&&(ve=r.readBits(16),be=r.readBits(16))}if(r.readBoolean()&&r.readBoolean(),r.readBoolean()&&(r.readBits(3),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.readUByte(),r.readUByte())),r.readBoolean()&&(r.readUEG(),r.readUEG()),r.readBoolean(),r.readBoolean(),r.readBoolean(),Ae=r.readBoolean(),Ae&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(Be=r.readBits(32),De=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const lt=r.readBoolean(),xt=r.readBoolean();let Xe=!1;(lt||xt)&&(Xe=r.readBoolean(),Xe&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),Xe&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let Je=0;Je<=n;Je++){Ue=r.readBoolean();const jt=Ue||r.readBoolean();let ns=!1;jt?r.readEG():ns=r.readBoolean();const Ns=ns?1:r.readUEG()+1;if(lt)for(let Ys=0;Ys>Oe&1)<<31-Oe)>>>0;let fe=et.toString(16);return l===1&&fe==="2"&&(fe="6"),{codecString:`hvc1.${Te}${l}.${fe}.${i?"H":"L"}${N}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,h],general_constraint_indicator_flags:[m,x,y,v,w,b],general_level_idc:N,bit_depth:K+8,bit_depth_luma_minus8:K,bit_depth_chroma_minus8:X,min_spatial_segmentation_idc:ce,chroma_format_idc:A,frame_rate:{fixed:Ue,fps:De/Be}},width:Le,height:Ie,pixelRatio:[ve,be]}}readPPS(t){const r=new FO(this.ebsp2rbsp(t));r.readUByte(),r.readUByte(),r.skipUEG(),r.skipUEG(),r.skipBits(2),r.skipBits(3),r.skipBits(2),r.skipUEG(),r.skipUEG(),r.skipEG(),r.skipBits(2),r.readBoolean()&&r.skipUEG(),r.skipEG(),r.skipEG(),r.skipBits(4);const a=r.readBoolean(),i=r.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,r){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,r).substr(3)}}const ch=188;class hw{constructor(t,r,n,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=r,this.typeSupported=n,this.logger=a,this.videoParser=null}static probe(t,r){const n=hw.syncOffset(t);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(t){const r=t.length;let n=Math.min(ch*5,r-ch)+1,a=0;for(;a1&&(l===0&&o>2||c+ch>n))return l}else{if(o)return-1;break}a++}return-1}static createTrack(t,r){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Bxt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?r:void 0}}resetInitSegment(t,r,n,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=hw.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=hw.createTrack("audio",a),this._id3Track=hw.createTrack("id3"),this._txtTrack=hw.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:r,_id3Track:n}=this;t&&(t.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,r,n=!1,a=!1){n||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let h=l.pid,m=l.pesData,x=o.pid,y=c.pid,v=o.pesData,w=c.pesData,b=null,N=this.pmtParsed,S=this._pmtId,T=t.length;if(this.remainderData&&(t=gg(this.remainderData,t),T=t.length,this.remainderData=null),T>4;let Q;if(z>1){if(Q=R+5+t[R+4],Q===R+ch)continue}else Q=R+4;switch(F){case h:$&&(m&&(i=pE(m,this.logger))&&(this.readyVideoParser(l.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(l,d,i,!1)),m={data:[],size:0}),m&&(m.data.push(t.subarray(Q,R+ch)),m.size+=R+ch-Q);break;case x:if($){if(v&&(i=pE(v,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}v={data:[],size:0}}v&&(v.data.push(t.subarray(Q,R+ch)),v.size+=R+ch-Q);break;case y:$&&(w&&(i=pE(w,this.logger))&&this.parseID3PES(c,i),w={data:[],size:0}),w&&(w.data.push(t.subarray(Q,R+ch)),w.size+=R+ch-Q);break;case 0:$&&(Q+=t[Q]+1),S=this._pmtId=nBs(t,Q);break;case S:{$&&(Q+=t[Q]+1);const K=aBs(t,Q,this.typeSupported,n,this.observer,this.logger);h=K.videoPid,h>0&&(l.pid=h,l.segmentCodec=K.segmentVideoCodec),x=K.audioPid,x>0&&(o.pid=x,o.segmentCodec=K.segmentAudioCodec),y=K.id3Pid,y>0&&(c.pid=y),b!==null&&!N&&(this.logger.warn(`MPEG-TS PMT found at ${R} after unknown PID '${b}'. Backtracking to sync byte @${A} to parse all TS packets.`),b=null,R=A-188),N=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=F;break}}else I++;I>0&&Zke(this.observer,new Error(`Found ${I} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=m,o.pesData=v,c.pesData=w;const D={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(D),D}flush(){const{remainderData:t}=this;this.remainderData=null;let r;return t?r=this.demux(t,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(t){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:i}=t,l=n.pesData,o=r.pesData,c=a.pesData;let d;if(l&&(d=pE(l,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,d,!0),n.pesData=null)):n.pesData=l,o&&(d=pE(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,d);break;case"mp3":this.parseMPEGPES(r,d);break;case"ac3":this.parseAC3PES(r,d);break}r.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;c&&(d=pE(c,this.logger))?(this.parseID3PES(a,d),a.pesData=null):a.pesData=c}demuxSampleAes(t,r,n){const a=this.demux(t,n,!0,!this.config.progressive),i=this.sampleAes=new tBs(this.observer,this.config,r);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new sBs:t==="hevc"&&(this.videoParser=new rBs))}decrypt(t,r){return new Promise(n=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?r.decryptAacSamples(a.samples,0,()=>{i.samples?r.decryptAvcSamples(i.samples,0,0,()=>{n(t)}):n(t)}):i.samples&&r.decryptAvcSamples(i.samples,0,0,()=>{n(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,r){let n=0;const a=this.aacOverFlow;let i=r.data;if(a){this.aacOverFlow=null;const m=a.missing,x=a.sample.unit.byteLength;if(m===-1)i=gg(a.sample.unit,i);else{const y=x-m;a.sample.unit.set(i.subarray(0,m),y),t.samples.push(a.sample),n=a.missing}}let l,o;for(l=n,o=i.length;l0;)o+=c}}parseID3PES(t,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=zl({},r,{type:this._videoTrack?Rp.emsg:Rp.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(n)}}function Yke(s,t){return((s[t+1]&31)<<8)+s[t+2]}function nBs(s,t){return(s[t+10]&31)<<8|s[t+11]}function aBs(s,t,r,n,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 x=t+5,y=m;for(;y>2;){switch(s[x]){case 106:r.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3");break}const w=s[x+1]+2;x+=w,y-=w}}break;case 194:case 135:return Zke(a,new Error("Unsupported EC-3 in M2TS found"),void 0,i),l;case 36:l.videoPid===-1&&(l.videoPid=h,l.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=m+5}return l}function Zke(s,t,r,n){n.warn(`parsing error: ${t.message}`),s.emit(ht.ERROR,ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Hbe(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function pE(s,t){let r=0,n,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]=gg(c[0],c[1]),c.splice(1,1);if(n=c[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(a=(n[4]<<8)+n[5],a&&a>s.size-6)return null;const h=n[7];h&192&&(l=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,h&64?(o=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[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=n[8];let m=i+9;if(s.size<=m)return null;s.size-=m;const x=new Uint8Array(s.size);for(let y=0,v=c.length;yw){m-=w;continue}else n=n.subarray(m),w-=m,m=0;x.set(n,r),r+=w}return a&&(a-=i+3),{data:x,pts:l,dts:o,len:a}}return null}class iBs{static getSilentFrame(t,r){switch(t){case"mp4a.40.2":if(r===1)return new Uint8Array([0,200,0,128,35,128]);if(r===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(r===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(r===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(r===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(r===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(r===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(r===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(r===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 q_=Math.pow(2,32)-1;class rr{static init(){rr.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 rr.types)rr.types.hasOwnProperty(t)&&(rr.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const r=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]),n=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]);rr.HDLR_TYPES={video:r,audio:n};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]);rr.STTS=rr.STSC=rr.STCO=i,rr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),rr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),rr.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]);rr.FTYP=rr.box(rr.types.ftyp,l,c,l,o),rr.DINF=rr.box(rr.types.dinf,rr.box(rr.types.dref,a))}static box(t,...r){let n=8,a=r.length;const i=a;for(;a--;)n+=r[a].byteLength;const l=new Uint8Array(n);for(l[0]=n>>24&255,l[1]=n>>16&255,l[2]=n>>8&255,l[3]=n&255,l.set(t,4),a=0,n=8;a>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return rr.box(rr.types.mdia,rr.mdhd(t.timescale||0,t.duration||0),rr.hdlr(t.type),rr.minf(t))}static mfhd(t){return rr.box(rr.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"?rr.box(rr.types.minf,rr.box(rr.types.smhd,rr.SMHD),rr.DINF,rr.stbl(t)):rr.box(rr.types.minf,rr.box(rr.types.vmhd,rr.VMHD),rr.DINF,rr.stbl(t))}static moof(t,r,n){return rr.box(rr.types.moof,rr.mfhd(t),rr.traf(n,r))}static moov(t){let r=t.length;const n=[];for(;r--;)n[r]=rr.trak(t[r]);return rr.box.apply(null,[rr.types.moov,rr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(rr.mvex(t)))}static mvex(t){let r=t.length;const n=[];for(;r--;)n[r]=rr.trex(t[r]);return rr.box.apply(null,[rr.types.mvex,...n])}static mvhd(t,r){r*=t;const n=Math.floor(r/(q_+1)),a=Math.floor(r%(q_+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,n>>24,n>>16&255,n>>8&255,n&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 rr.box(rr.types.mvhd,i)}static sdtp(t){const r=t.samples||[],n=new Uint8Array(4+r.length);let a,i;for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));const o=rr.box(rr.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),c=t.width,d=t.height,h=t.pixelRatio[0],m=t.pixelRatio[1];return rr.box(rr.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,rr.box(rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rr.box(rr.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,m>>24,m>>16&255,m>>8&255,m&255])))}static esds(t){const r=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,...r,6,1,2])}static audioStsd(t){const r=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,r>>8&255,r&255,0,0])}static mp4a(t){return rr.box(rr.types.mp4a,rr.audioStsd(t),rr.box(rr.types.esds,rr.esds(t)))}static mp3(t){return rr.box(rr.types[".mp3"],rr.audioStsd(t))}static ac3(t){return rr.box(rr.types["ac-3"],rr.audioStsd(t),rr.box(rr.types.dac3,t.config))}static stsd(t){const{segmentCodec:r}=t;if(t.type==="audio"){if(r==="aac")return rr.box(rr.types.stsd,rr.STSD,rr.mp4a(t));if(r==="ac3"&&t.config)return rr.box(rr.types.stsd,rr.STSD,rr.ac3(t));if(r==="mp3"&&t.codec==="mp3")return rr.box(rr.types.stsd,rr.STSD,rr.mp3(t))}else if(t.pps&&t.sps){if(r==="avc")return rr.box(rr.types.stsd,rr.STSD,rr.avc1(t));if(r==="hevc"&&t.vps)return rr.box(rr.types.stsd,rr.STSD,rr.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${r}/${t.codec})`)}static tkhd(t){const r=t.id,n=(t.duration||0)*(t.timescale||0),a=t.width||0,i=t.height||0,l=Math.floor(n/(q_+1)),o=Math.floor(n%(q_+1));return rr.box(rr.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&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,r){const n=rr.sdtp(t),a=t.id,i=Math.floor(r/(q_+1)),l=Math.floor(r%(q_+1));return rr.box(rr.types.traf,rr.box(rr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),rr.box(rr.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])),rr.trun(t,n.length+16+20+8+16+8+8),n)}static trak(t){return t.duration=t.duration||4294967295,rr.box(rr.types.trak,rr.tkhd(t),rr.mdia(t))}static trex(t){const r=t.id;return rr.box(rr.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,r){const n=t.samples||[],a=n.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,h,m,x;for(r+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.degradPrio&15,x>>>24&255,x>>>16&255,x>>>8&255,x&255],12+16*o);return rr.box(rr.types.trun,l)}static initSegment(t){rr.types||rr.init();const r=rr.moov(t);return gg(rr.FTYP,r)}static hvc1(t){const r=t.params,n=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),a-1|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let l=i.length;for(let v=0;v>8,n[v][w].length&255]),l),l+=2,o.set(n[v][w],l),l+=n[v][w].length}const d=rr.box(rr.types.hvcC,o),h=t.width,m=t.height,x=t.pixelRatio[0],y=t.pixelRatio[1];return rr.box(rr.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,h>>8&255,h&255,m>>8&255,m&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,rr.box(rr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),rr.box(rr.types.pasp,new Uint8Array([x>>24,x>>16&255,x>>8&255,x&255,y>>24,y>>16&255,y>>8&255,y&255])))}}rr.types=void 0;rr.HDLR_TYPES=void 0;rr.STTS=void 0;rr.STSC=void 0;rr.STCO=void 0;rr.STSZ=void 0;rr.VMHD=void 0;rr.SMHD=void 0;rr.STSD=void 0;rr.FTYP=void 0;rr.DINF=void 0;const Pgt=9e4;function pAe(s,t,r=1,n=!1){const a=s*t*r;return n?Math.round(a):a}function oBs(s,t,r=1,n=!1){return pAe(s,t,1/r,n)}function _D(s,t=!1){return pAe(s,1e3,1/Pgt,t)}function lBs(s,t=1){return pAe(s,Pgt,1/t)}function NHe(s){const{baseTime:t,timescale:r,trackId:n}=s;return`${t/r} (${t}/${r}) trackId: ${n}`}const cBs=10*1e3,dBs=1024,uBs=1152,hBs=1536;let xE=null,Gbe=null;function kHe(s,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class Ice extends Sg{constructor(t,r,n,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=r,this.typeSupported=n,this.ISGenerated=!1,xE===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);xE=l?parseInt(l[1]):0}if(Gbe===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);Gbe=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const r=this._initPTS;(!r||!t||t.trackId!==r.trackId||t.baseTime!==r.baseTime||t.timescale!==r.timescale)&&this.log(`Reset initPTS: ${r&&NHe(r)} > ${t&&NHe(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 r=!1;const n=t[0].pts,a=t.reduce((i,l)=>{let o=l.pts,c=o-i;return c<-4294967296&&(r=!0,o=Ep(o,n),c=o-i),c>0?i:o},n);return r&&this.debug("PTS rollover detected"),a}remux(t,r,n,a,i,l,o,c){let d,h,m,x,y,v,w=i,b=i;const N=t.pid>-1,S=r.pid>-1,T=r.samples.length,A=t.samples.length>0,I=o&&T>0||T>1;if((!N||A)&&(!S||I)||this.ISGenerated||o){if(this.ISGenerated){var R,$,F,z;const Z=this.videoTrackConfig;(Z&&(r.width!==Z.width||r.height!==Z.height||((R=r.pixelRatio)==null?void 0:R[0])!==(($=Z.pixelRatio)==null?void 0:$[0])||((F=r.pixelRatio)==null?void 0:F[1])!==((z=Z.pixelRatio)==null?void 0:z[1]))||!Z&&I||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(m=this.generateIS(t,r,i,l));const Q=this.isVideoContiguous;let K=-1,X;if(I&&(K=mBs(r.samples),!Q&&this.config.forceKeyFrameOnDiscontinuity))if(v=!0,K>0){this.warn(`Dropped ${K} out of ${T} video samples due to a missing keyframe`);const Z=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(K),r.dropped+=K,b+=(r.samples[0].pts-Z)/r.inputTimeScale,X=b}else K===-1&&(this.warn(`No keyframe found out of ${T} video samples`),v=!1);if(this.ISGenerated){if(A&&I){const Z=this.getVideoStartPts(r.samples),le=(Ep(t.samples[0].pts,Z)-Z)/r.inputTimeScale;w+=Math.max(0,le),b+=Math.max(0,-le)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(t,r,i,l)),h=this.remuxAudio(t,w,this.isAudioContiguous,l,S||I||c===ua.AUDIO?b:void 0),I){const Z=h?h.endPTS-h.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),m=this.generateIS(t,r,i,l)),d=this.remuxVideo(r,b,Q,Z)}}else I&&(d=this.remuxVideo(r,b,Q,0));d&&(d.firstKeyFrame=K,d.independent=K!==-1,d.firstKeyFramePTS=X)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(y=Dgt(n,i,this._initPTS,this._initDTS)),a.samples.length&&(x=Rgt(a,i,this._initPTS))),{audio:h,video:d,initSegment:m,independent:v,text:x,id3:y}}computeInitPts(t,r,n,a){const i=Math.round(n*r);let l=Ep(t,i);if(l0?ce-1:ce].dts&&(S=!0)}S&&l.sort(function(ce,ve){const be=ce.dts-ve.dts,Ue=ce.pts-ve.pts;return be||Ue}),v=l[0].dts,w=l[l.length-1].dts;const A=w-v,I=A?Math.round(A/(c-1)):y||t.inputTimeScale/30;if(n){const ce=v-T,ve=ce>I,be=ce<-1;if((ve||be)&&(ve?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${_D(ce,!0)} ms (${ce}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${_D(-ce,!0)} ms (${ce}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!be||T>=l[0].pts||xE)){v=T;const Ue=l[0].pts-ce;if(ve)l[0].dts=v,l[0].pts=Ue;else{let Be=!0;for(let De=0;DeUe&&Be);De++){const Ae=l[De].pts;if(l[De].dts-=ce,l[De].pts-=ce,De0?ve.dts-l[ce-1].dts:I;if(Be=ce>0?ve.pts-l[ce-1].pts:I,Ae.stretchShortVideoTrack&&this.nextAudioTs!==null){const Le=Math.floor(Ae.maxBufferHole*i),Ie=(a?b+a*i:this.nextAudioTs+h)-ve.pts;Ie>Le?(y=Ie-He,y<0?y=He:K=!0,this.log(`It is approximately ${Ie/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=He}else y=He}const De=Math.round(ve.pts-ve.dts);X=Math.min(X,y),re=Math.max(re,y),Z=Math.min(Z,Be),le=Math.max(le,Be),o.push(kHe(ve.key,y,Ue,De))}if(o.length){if(xE){if(xE<70){const ce=o[0].flags;ce.dependsOn=2,ce.isNonSync=0}}else if(Gbe&&le-Z0&&(a&&Math.abs(T-(N+S))<9e3||Math.abs(Ep(w[0].pts,T)-(N+S))<20*h),w.forEach(function(le){le.pts=Ep(le.pts,T)}),!n||N<0){const le=w.length;if(w=w.filter(oe=>oe.pts>=0),le!==w.length&&this.warn(`Removed ${w.length-le} of ${le} samples (initPTS ${S} / ${l})`),!w.length)return;i===0?N=0:a&&!v?N=Math.max(0,T-S):N=w[0].pts-S}if(t.segmentCodec==="aac"){const le=this.config.maxAudioFramesDrift;for(let oe=0,ne=N+S;oe=le*h&&ve0){R+=b;try{D=new Uint8Array(R)}catch(ve){this.observer.emit(ht.ERROR,ht.ERROR,{type:La.MUX_ERROR,details:ar.REMUX_ALLOC_ERROR,fatal:!1,error:ve,bytes:R,reason:`fail allocating audio mdat ${R}`});return}x||(new DataView(D.buffer).setUint32(0,R),D.set(rr.types.mdat,4))}else return;D.set(ie,b);const ce=ie.byteLength;b+=ce,y.push(kHe(!0,d,ce,0)),I=ye}const F=y.length;if(!F)return;const z=y[y.length-1];N=I-S,this.nextAudioTs=N+c*z.duration;const Q=x?new Uint8Array(0):rr.moof(t.sequenceNumber++,A/c,zl({},t,{samples:y}));t.samples=[];const K=(A-S)/l,X=this.nextAudioTs/l,re={data1:Q,data2:D,startPTS:K,endPTS:X,startDTS:K,endDTS:X,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,re}}function Ep(s,t){let r;if(t===null)return s;for(t4294967296;)s+=r;return s}function mBs(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class fBs extends Sg{constructor(t,r,n,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 r=this.initPTS;r&&t&&r.baseTime===t.baseTime&&r.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,r,n,a){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(t,a),this.emitInitSegment=!0}generateInitSegment(t,r){let{audioCodec:n,videoCodec:a}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:l}=this.initData=Uxt(t);if(r)t8s(t,r);else{const c=i||l;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(n=SHe(i,Hl.AUDIO,this)),l&&(a=SHe(l,Hl.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:n+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:n,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,r,n,a,i,l){var o,c;let{initPTS:d,lastEndTime:h}=this;const m={audio:void 0,video:void 0,text:a,id3:n,initSegment:void 0};Zn(h)||(h=this.lastEndTime=i||0);const x=r.samples;if(!x.length)return m;const y={initPTS:void 0,timescale:void 0,trackId:void 0};let v=this.initData;if((o=v)!=null&&o.length||(this.generateInitSegment(x),v=this.initData),!((c=v)!=null&&c.length))return this.warn("Failed to generate initSegment."),m;this.emitInitSegment&&(y.tracks=this.initTracks,this.emitInitSegment=!1);const w=r8s(x,v,this),b=v.audio?w[v.audio.id]:null,N=v.video?w[v.video.id]:null,S=aU(N,1/0),T=aU(b,1/0),A=aU(N,0,!0),I=aU(b,0,!0);let D=i,R=0;const $=b&&(!N||!d&&T0?this.lastEndTime=Q:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const K=!!v.audio,X=!!v.video;let Z="";K&&(Z+="audio"),X&&(Z+="video");const re=(v.audio?v.audio.encrypted:!1)||(v.video?v.video.encrypted:!1),le={data1:x,startPTS:z,startDTS:z,endPTS:Q,endDTS:Q,type:Z,hasAudio:K,hasVideo:X,nb:1,dropped:0,encrypted:re};m.audio=K&&!X?le:void 0,m.video=X?le:void 0;const oe=N==null?void 0:N.sampleCount;if(oe){const ne=N.keyFrameIndex,ie=ne!==-1;le.nb=oe,le.dropped=ne===0||this.isVideoContiguous?0:ie?ne:oe,le.independent=ie,le.firstKeyFrame=ne,ie&&N.keyFrameStart&&(le.firstKeyFramePTS=(N.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(m.independent=ie),this.isVideoContiguous||(this.isVideoContiguous=ie),le.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ne}/${oe} dropped: ${le.dropped} start: ${le.firstKeyFramePTS||"NA"}`)}return m.initSegment=y,m.id3=Dgt(n,i,d,d),a.samples.length&&(m.text=Rgt(a,i,d)),m}}function aU(s,t,r=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(r?s.duration:0))/s.timescale:t}function pBs(s,t,r,n){if(s===null)return!0;const a=Math.max(n,1),i=t-s.baseTime/s.timescale;return Math.abs(i-r)>a}function SHe(s,t,r){const n=s.codec;return n&&n.length>4?n:t===Hl.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?ime(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let V1;try{V1=self.performance.now.bind(self.performance)}catch{V1=Date.now}const Lce=[{demux:eBs,remux:fBs},{demux:hw,remux:Ice},{demux:ZFs,remux:Ice},{demux:QFs,remux:Ice}];Lce.splice(2,0,{demux:XFs,remux:Ice});class CHe{constructor(t,r,n,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=r,this.config=n,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,r,n,a){const i=n.transmuxing;i.executeStart=V1();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:h,trackSwitch:m,accurateTimeOffset:x,timeOffset:y,initSegmentChange:v}=a||o,{audioCodec:w,videoCodec:b,defaultInitPts:N,duration:S,initSegmentData:T}=c,A=xBs(l,r);if(A&&QA(A.method)){const $=this.getDecrypter(),F=iAe(A.method);if($.isSync()){let z=$.softwareDecrypt(l,A.key.buffer,A.iv.buffer,F);if(n.part>-1){const K=$.flush();z=K&&K.buffer}if(!z)return i.executeEnd=V1(),Wbe(n);l=new Uint8Array(z)}else return this.asyncResult=!0,this.decryptionPromise=$.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,F).then(z=>{const Q=this.push(z,null,n);return this.decryptionPromise=null,Q}),this.decryptionPromise}const I=this.needsProbing(h,m);if(I){const $=this.configureTransmuxer(l);if($)return this.logger.warn(`[transmuxer] ${$.message}`),this.observer.emit(ht.ERROR,ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_PARSING_ERROR,fatal:!1,error:$,reason:$.message}),i.executeEnd=V1(),Wbe(n)}(h||m||v||I)&&this.resetInitSegment(T,w,b,S,r),(h||v||I)&&this.resetInitialTimestamp(N),d||this.resetContiguity();const D=this.transmux(l,A,y,x,n);this.asyncResult=TF(D);const R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,i.executeEnd=V1(),D}flush(t){const r=t.transmuxing;r.executeStart=V1();const{decrypter:n,currentTransmuxState:a,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const l=[],{timeOffset:o}=a;if(n){const m=n.flush();m&&l.push(this.push(m.buffer,null,t))}const{demuxer:c,remuxer:d}=this;if(!c||!d){r.executeEnd=V1();const m=[Wbe(t)];return this.asyncResult?Promise.resolve(m):m}const h=c.flush(o);return TF(h)?(this.asyncResult=!0,h.then(m=>(this.flushRemux(l,m,t),l))):(this.flushRemux(l,h,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,r,n){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=r,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===ua.MAIN?"level":"track"} ${n.level}`);const h=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:h,chunkMeta:n}),n.transmuxing.executeEnd=V1()}resetInitialTimestamp(t){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(t),n.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(t,r,n,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,r,n,a),o.resetInitSegment(t,r,n,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,r,n,a,i){let l;return r&&r.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,r,n,a,i):l=this.transmuxUnencrypted(t,n,a,i),l}transmuxUnencrypted(t,r,n,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,r,n,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,r,n,a,i){return this.demuxer.demuxSampleAes(t,r,n).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,n,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:r,observer:n,typeSupported:a}=this;let i;for(let m=0,x=Lce.length;m0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(r=t),r}const Wbe=s=>({remuxResult:{},chunkMeta:s});function TF(s){return"then"in s&&s.then instanceof Function}class gBs{constructor(t,r,n,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=r,this.initSegmentData=n,this.duration=a,this.defaultInitPts=i||null}}class yBs{constructor(t,r,n,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=r,this.accurateTimeOffset=n,this.trackSwitch=a,this.timeOffset=i,this.initSegmentChange=l}}let THe=0;class Ogt{constructor(t,r,n,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=THe++,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,h=this.hls;if(!(!h||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var m;const x=(m=this.workerContext)==null?void 0:m.objectURL;x&&self.URL.revokeObjectURL(x);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{h.logger[d.data.logType]&&h.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,h.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(ht.ERROR,{type:La.OTHER_ERROR,details:ar.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const i=t.config;this.hls=t,this.id=r,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=a;const l=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===ht.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new cAe,this.observer.on(ht.FRAG_DECRYPTED,l),this.observer.on(ht.ERROR,l);const o=qVe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||wFs()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${r}"`),this.workerContext=NFs(i.workerPath)):(c.log(`injecting Web Worker for "${r}"`),this.workerContext=jFs());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:r,config:Ql(i)})}catch(h){c.warn(`Error setting up "${r}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new CHe(this.observer,o,i,"",r,t.logger)}return}}this.transmuxer=new CHe(this.observer,o,i,"",r,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=THe++;const r=this.hls.config,n=qVe(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:n,id:this.id,config:Ql(r)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),kFs(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const r=this.transmuxer;r&&(r.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,r,n,a,i,l,o,c,d,h){var m,x;d.transmuxing.start=self.performance.now();const{instanceNo:y,transmuxer:v}=this,w=l?l.start:i.start,b=i.decryptdata,N=this.frag,S=!(N&&i.cc===N.cc),T=!(N&&d.level===N.level),A=N?d.sn-N.sn:-1,I=this.part?d.part-this.part.index:-1,D=A===0&&d.id>1&&d.id===(N==null?void 0:N.stats.chunkCount),R=!T&&(A===1||A===0&&(I===1||D&&I<=0)),$=self.performance.now();(T||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=$),l&&(I||!R)&&(l.stats.parsing.start=$);const F=!(N&&((m=i.initSegment)==null?void 0:m.url)===((x=N.initSegment)==null?void 0:x.url)),z=new yBs(S,R,c,T,w,F);if(!R||S||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===ua.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${S} trackSwitch: ${T} contiguous: ${R} accurateTimeOffset: ${c} timeOffset: ${w} initSegmentChange: ${F}`);const Q=new gBs(n,a,r,o,h);this.configureTransmuxer(Q)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:y,cmd:"demux",data:t,decryptdata:b,chunkMeta:d,state:z},t instanceof ArrayBuffer?[t]:[]);else if(v){const Q=v.push(t,b,d,z);TF(Q)?Q.then(K=>{this.handleTransmuxComplete(K)}).catch(K=>{this.transmuxerError(K,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(Q)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:r,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:t});else if(n){const a=n.flush(t);TF(a)?a.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(a,t)}}transmuxerError(t,r,n){this.hls&&(this.error=t,this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:n}))}handleFlushResult(t,r){t.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}configureTransmuxer(t){const{instanceNo:r,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:r,cmd:"configure",config:t}):n&&n.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const EHe=100;class vBs extends lAe{constructor(t,r,n){super(t,r,n,"audio-stream-controller",ua.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(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ht.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(ht.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ht.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(ht.BUFFER_RESET,this.onBufferReset,this),t.on(ht.BUFFER_CREATED,this.onBufferCreated,this),t.on(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ht.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ht.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ht.FRAG_LOADING,this.onFragLoading,this),t.on(ht.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ht.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(ht.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ht.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(ht.BUFFER_RESET,this.onBufferReset,this),t.off(ht.BUFFER_CREATED,this.onBufferCreated,this),t.off(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ht.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ht.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ht.FRAG_LOADING,this.onFragLoading,this),t.off(ht.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){if(n===ua.MAIN){const o=r.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=r,this.state===Or.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(r,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(r,c)):this.state===Or.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,r){var n;const a=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(r&&(a==null?void 0:a.cc)===r.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=Jxt(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===Or.IDLE&&this.doTickIdle())}startLoad(t,r){if(!this.levels){this.startPosition=t,this.state=Or.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(EHe),n>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n,this.state=Or.IDLE):this.state=Or.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}doTick(){switch(this.state){case Or.IDLE:this.doTickIdle();break;case Or.WAITING_TRACK:{const{levels:t,trackId:r}=this,n=t==null?void 0:t[r],a=n==null?void 0:n.details;if(a&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(a))break;this.state=Or.WAITING_INIT_PTS}break}case Or.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Or.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:r,part:n,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=Or.FRAG_LOADING;const o=a.flush().buffer,c={frag:r,part:n,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=Or.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:r,levels:n,media:a,trackId:i}=this,l=r.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(n!=null&&n[i]))return;const o=n[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=Or.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Hl.AUDIO,ua.AUDIO));const h=this.getFwdBufferInfo(d,ua.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){r.trigger(ht.BUFFER_EOS,{type:"audio"}),this.state=Or.ENDED;return}const m=h.len,x=r.maxBufferLength,y=c.fragments,v=y[0].start,w=this.getLoadPosition(),b=this.flushing?w:h.end;if(this.switchingTrack&&a){const T=w;c.PTSKnown&&Tv||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=v+.05)}if(m>=x&&!this.switchingTrack&&bS.end){const A=this.fragmentTracker.getFragAtPos(b,ua.MAIN);A&&A.end>S.end&&(S=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(N.start>S.end)return}this.loadFragment(N,o,b)}onMediaDetaching(t,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,r)}onAudioTracksUpdated(t,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new kF(n))}onAudioTrackSwitching(t,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),n?(this.switchingTrack=r,this.flushAudioIfNeeded(r),this.state!==Or.STOPPED&&(this.setInterval(EHe),this.state=Or.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=r,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,r){this.mainDetails=r.details;const n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ht.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(t,r){var n;const{levels:a}=this,{details:i,id:l,groupId:o,track:c}=r;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=r,this.state!==Or.STOPPED&&(this.state=Or.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 h=a[l];let m=0;if(i.live||(n=h.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(h.details){var x;m=this.alignPlaylists(i,h.details,(x=this.levelLastLoaded)==null?void 0:x.details)}i.alignedSliding||(ggt(i,d),i.alignedSliding||mme(i,d),m=i.fragmentStart)}h.details=i,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,m),this.hls.trigger(ht.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:r.groupId}),this.state===Or.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Or.IDLE),this.tick()}_handleFragmentLoadProgress(t){var r;const n=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 ${n.sn} of level ${n.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const h=d.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const m=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let x=this.transmuxer;x||(x=this.transmuxer=new Ogt(this.hls,ua.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const y=this.initPTS[n.cc],v=(r=n.initSegment)==null?void 0:r.data;if(y!==void 0){const b=a?a.index:-1,N=b!==-1,S=new aAe(n.level,n.sn,n.stats.chunkCount,i.byteLength,b,N);x.push(i,v,m,"",n,a,h.totalduration,!1,S,y)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:w}=this.waitingData=this.waitingData||{frag:n,part:a,cache:new ygt,complete:!1};w.push(new Uint8Array(i)),this.state!==Or.STOPPED&&(this.state=Or.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,r){this.bufferFlushed=this.flushing=!1;const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(t,r){!this.audioOnly&&r.frag.type===ua.MAIN&&Yd(r.frag)&&(this.mainFragLoading=r,this.state===Or.IDLE&&this.tick())}onFragBuffered(t,r){const{frag:n,part:a}=r;if(n.type!==ua.AUDIO){!this.audioOnly&&n.type===ua.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${a?" p: "+a.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Yd(n)){this.fragPrevious=n;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(ht.AUDIO_TRACK_SWITCHED,Sl({},i)))}this.fragBufferedComplete(n,a),this.media&&this.tick()}onError(t,r){var n;if(r.fatal){this.state=Or.ERROR;return}switch(r.details){case ar.FRAG_GAP:case ar.FRAG_PARSING_ERROR:case ar.FRAG_DECRYPT_ERROR:case ar.FRAG_LOAD_ERROR:case ar.FRAG_LOAD_TIMEOUT:case ar.KEY_LOAD_ERROR:case ar.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ua.AUDIO,r);break;case ar.AUDIO_TRACK_LOAD_ERROR:case ar.AUDIO_TRACK_LOAD_TIMEOUT:case ar.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Or.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===ao.AUDIO_TRACK&&(this.state=Or.IDLE);break;case ar.BUFFER_ADD_CODEC_ERROR:case ar.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case ar.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ar.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(t,{type:r}){r!==Hl.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:r}){if(r!==Hl.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Or.ENDED&&(this.state=Or.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,ua.AUDIO),this.tick())}}_handleTransmuxComplete(t){var r;const n="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:h}=o,{details:m}=h,{audio:x,text:y,id3:v,initSegment:w}=i;if(this.fragContextChanged(c)||!m){this.fragmentTracker.removeFragment(c);return}if(this.state=Or.PARSING,this.switchingTrack&&x&&this.completeAudioSwitch(this.switchingTrack),w!=null&&w.tracks){const b=c.initSegment||c;if(this.unhandledEncryptionError(w,c))return;this._bufferInitSegment(h,w.tracks,b,l),a.trigger(ht.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:n,tracks:w.tracks})}if(x){const{startPTS:b,endPTS:N,startDTS:S,endDTS:T}=x;d&&(d.elementaryStreams[Hl.AUDIO]={startPTS:b,endPTS:N,startDTS:S,endDTS:T}),c.setElementaryStreamInfo(Hl.AUDIO,b,N,S,T),this.bufferFragmentData(x,c,d,l)}if(v!=null&&(r=v.samples)!=null&&r.length){const b=zl({id:n,frag:c,details:m},v);a.trigger(ht.FRAG_PARSING_METADATA,b)}if(y){const b=zl({id:n,frag:c,details:m},y);a.trigger(ht.FRAG_PARSING_USERDATA,b)}}_bufferInitSegment(t,r,n,a){if(this.state!==Or.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const i=r.audio;i.id=ua.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(ht.BUFFER_CODECS,r);const o=i.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:n,part:null,chunkMeta:a,parent:n.type,data:o};this.hls.trigger(ht.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Ou.NOT_LOADED||a===Ou.PARTIAL){var i;if(!Yd(t))this._loadInitSegment(t,r);else if((i=r.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=Or.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==r.details.fragmentStart&&mme(r.details,l)}else super.loadFragment(t,r,n)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;v3({name:r,lang:n,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,GC)||(lme(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:r}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,r.trigger(ht.AUDIO_TRACK_SWITCHED,Sl({},t))}}class xAe extends Sg{constructor(t,r){super(r,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,r,n){const a=r==null?void 0:r.renditionReports;if(a){let i=-1;for(let l=0;l=0&&h>r.partTarget&&(c+=1)}const d=n&&VVe(n);return new HVe(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,r){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,r){if(r)try{return r.addDirectives(t)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return t}playlistLoaded(t,r,n){const{details:a,stats:i}=r,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 h=Math.max(c||0,0);a.appliedTimelineOffset=h,a.fragments.forEach(m=>{m.setStart(m.playlistOffset+h)})}if(a.live||n!=null&&n.live){const h="levelInfo"in r?r.levelInfo:r.track;if(a.reloaded(n),n&&a.fragments.length>0){uFs(n,a,this);const S=a.playlistParsingError;if(S){this.warn(S);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=r;T.trigger(ht.ERROR,{type:La.NETWORK_ERROR,details:ar.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:S,reason:S.message,level:r.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 m=this.hls.mainForwardBufferInfo,x=m?m.end-m.len:0,y=(a.edge-x)*1e3,v=hgt(a,y);if(a.requestScheduled+v0){if(F>a.targetduration*3)this.log(`Playlist last advanced ${$.toFixed(2)}s ago. Omitting segment and part directives.`),b=void 0,N=void 0;else if(n!=null&&n.tuneInGoal&&F-a.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${z} with playlist age: ${a.age}`),z=0;else{const Q=Math.floor(z/a.targetduration);if(b+=Q,N!==void 0){const K=Math.round(z%a.targetduration/a.partTarget);N+=K}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${$.toFixed(2)}s goal: ${z} skip sn ${Q} to part ${N}`)}a.tuneInGoal=z}if(w=this.getDeliveryDirectives(a,r.deliveryDirectives,b,N),S||!R){a.requestScheduled=l,this.loadingPlaylist(h,w);return}}else(a.canBlockReload||a.canSkipUntil)&&(w=this.getDeliveryDirectives(a,r.deliveryDirectives,b,N));w&&b!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(v-o*2,v/2)),this.scheduleLoading(h,w,a)}else this.clearTimer()}scheduleLoading(t,r,n){const a=n||t.details;if(!a){this.loadingPlaylist(t,r);return}const i=self.performance.now(),l=a.requestScheduled;if(i>=l){this.loadingPlaylist(t,r);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,r),o)}getDeliveryDirectives(t,r,n,a){let i=VVe(t);return r!=null&&r.skip&&t.deltaUpdateFailed&&(n=r.msn,a=r.part,i=Ace.No),new HVe(n,a,i)}checkRetry(t){const r=t.details,n=cme(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===Uh.RetryRequest||!a.resolved&&i===Uh.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(n&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const h=rAe(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${r}" in ${h}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function Fgt(s,t){if(s.length!==t.length)return!1;for(let r=0;rs[a]!==t[a])}function Xke(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class bBs extends xAe{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(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ht.LEVEL_LOADING,this.onLevelLoading,this),t.on(ht.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ht.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(ht.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ht.LEVEL_LOADING,this.onLevelLoading,this),t.off(ht.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ht.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(ht.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,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Audio track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Audio track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(x=>!n||n.indexOf(x.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(x=>x.default)&&(this.selectDefaultTrack=!1),o.forEach((x,y)=>{x.id=y});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const x=Z0(c,o,GC);if(x>-1)i=o[x];else{const y=Z0(c,this.tracks);i=this.tracks[y]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(ht.AUDIO_TRACKS_UPDATED,h);const m=this.trackId;if(d!==-1&&m===-1)this.setAudioTrack(d);else if(o.length&&m===-1){var l;const x=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(x.message),this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:x})}}}onError(t,r){r.fatal||!r.context||r.context.type===ao.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&this.checkRetry(r)}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 r=this.hls;if(r.config.audioPreference=t,t){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const a=this.currentTrack;if(a&&v3(t,a,GC))return a;const i=Z0(t,this.tracksInGroup,GC);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i),l}else if(a){let l=r.loadLevel;l===-1&&(l=r.firstAutoLevel);const o=I8s(t,r.levels,n,l,GC);if(o===-1)return null;r.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=Z0(t,n);if(l>-1)return n[l]}}}return null}setAudioTrack(t){const r=this.tracksInGroup;if(t<0||t>=r.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,a=r[t],i=a.details&&!a.details.live;if(t===this.trackId&&a===n&&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(ht.AUDIO_TRACK_SWITCHING,Sl({},a)),i))return;const l=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(l)}findTrackId(t){const r=this.tracksInGroup;for(let n=0;n{const n={label:"async-blocker",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,t)})}prependBlocker(t){return new Promise(r=>{if(this.queues){const n={label:"async-blocker-prepend",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var r;const n=(r=t[0])==null?void 0:r.label;(n==="async-blocker"||n==="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 r=this.queues[t];if(r.length){const a=r[0];try{a.execute()}catch(i){var n;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(n=this.tracks[t])==null?void 0:n.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var r;return((r=this.queues)==null?void 0:r[t][0])||null}toString(){const{queues:t,tracks:r}=this;return t===null||r===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var r,n;return(r=this.queues)!=null&&r[t]||(n=this.tracks)!=null&&n[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var r;const n=(r=this.tracks)==null?void 0:r[t],a=n==null?void 0:n.buffer;return a?`SourceBuffer${a.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`:"none"}listOps(t){var r;return((r=this.queues)==null?void 0:r[t].map(n=>n.label).join(", "))||""}}const AHe=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Bgt="HlsJsTrackRemovedError";class wBs extends Error{constructor(t){super(t),this.name=Bgt}}class jBs extends Sg{constructor(t,r){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=n=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=n=>{const{media:a,mediaSource:i}=this;n&&this.log("Media source opened"),!(!a||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(ht.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:n,_objectUrl:a}=this;n!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${n})`)},this.hls=t,this.fragmentTracker=r,this.appendSource=HOs(zj(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(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ht.BUFFER_RESET,this.onBufferReset,this),t.on(ht.BUFFER_APPENDING,this.onBufferAppending,this),t.on(ht.BUFFER_CODECS,this.onBufferCodecs,this),t.on(ht.BUFFER_EOS,this.onBufferEos,this),t.on(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ht.FRAG_PARSED,this.onFragParsed,this),t.on(ht.FRAG_CHANGED,this.onFragChanged,this),t.on(ht.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ht.BUFFER_RESET,this.onBufferReset,this),t.off(ht.BUFFER_APPENDING,this.onBufferAppending,this),t.off(ht.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ht.BUFFER_EOS,this.onBufferEos,this),t.off(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ht.FRAG_PARSED,this.onFragParsed,this),t.off(ht.FRAG_CHANGED,this.onFragChanged,this),t.off(ht.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:r}=this;if(!t)return null;const n={};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===r?zl(n,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(n[l]=zl({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:r,tracks:n}}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,r){var n;let a=2;(r.audio&&!r.video||!r.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,r){const n=this.media=r.media;this.transferData=this.overrides=void 0;const a=zj(this.appendSource);if(a){const i=!!r.mediaSource;(i||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const l=this.mediaSource=r.mediaSource||new a;if(this.assignMediaSource(l),i)this._objectUrl=n.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{n.removeAttribute("src");const c=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||c&&l instanceof c,MHe(n),NBs(n,o),n.load()}catch{n.src=o}else n.src=o}n.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var r,n;this.log(`${((r=this.transferData)==null?void 0:r.mediaSource)===t?"transferred":"created"} media source: ${(n=t.constructor)==null?void 0:n.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,r=this.transferData;if(!r||!t)return;const n=this.tracks,a=r.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: ${Ql(n,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Ql(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!Dxt(a,n)){r.mediaSource=null,r.tracks=void 0;const c=t.currentTime,d=this.details,h=Math.max(c,(d==null?void 0:d.fragments[0].start)||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(a)}"->"${Object.keys(n)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(ht.MEDIA_DETACHING,{}),this.onMediaAttaching(ht.MEDIA_ATTACHING,r),t.currentTime=h;return}this.transferData=void 0,i.forEach(c=>{const d=c,h=a[d];if(h){const m=h.buffer;if(m){const x=this.fragmentTracker,y=h.id;if(x.hasFragments(y)||x.hasParts(y)){const b=Ai.getBuffered(m);x.detectEvictedFragments(d,b,y,null,!0)}const v=Kbe(d),w=[d,m];this.sourceBuffers[v]=w,m.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const r=(t=this.mediaSource)==null?void 0:t.readyState;return r==="open"||r==="ended"}onMediaDetaching(t,r){const n=!!r.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${n?"transferring":"detaching"}`),n)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),n||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&MHe(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(ht.MEDIA_DETACHED,r)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;if(this.removeBuffer(t),n)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(n)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Kbe(t)]=[null,null];const r=this.tracks[t];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new _Bs(this.tracks)}onBufferCodecs(t,r){var n;const a=this.tracks,i=Object.keys(r);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in r&&(a.audio||a.video)||a.audiovideo&&("audio"in r||"video"in r),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,h;const m=r[c],{id:x,codec:y,levelCodec:v,container:w,metadata:b,supplemental:N}=m;let S=a[c];const T=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=T!=null&&T.buffer?T:S,I=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),D=A==null?void 0:A.levelCodec;S||(S=a[c]={buffer:void 0,listeners:[],codec:y,supplemental:N,container:w,levelCodec:v,metadata:b,id:x});const R=Ece(I,D),$=R==null?void 0:R.replace(AHe,"$1");let F=Ece(y,v);const z=(h=F)==null?void 0:h.replace(AHe,"$1");F&&R&&$!==z&&(c.slice(0,5)==="audio"&&(F=ime(F,this.appendSource)),this.log(`switching codec ${I} to ${F}`),F!==(S.pendingCodec||S.codec)&&(S.pendingCodec=F),S.container=w,this.appendChangeType(c,w,F))}),(this.tracksReady||this.sourceBufferCount)&&(r.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!r.video&&((n=r.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,r)=>{const n=this.tracks[r];return t[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},t},{})}appendChangeType(t,r,n){const a=`${r};codecs=${n}`,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=n,l.container=r)}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 r;const n=t.start,a=n+t.duration*.05;if(((r=this.fragmentTracker.getAppendedFrag(n,ua.MAIN))==null?void 0:r.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>a||c!=null&&c.buffer&&Ai.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,ua.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:r}=this;t&&r&&(this.blockedAudioAppend=null,r.unblockAudio(t.op))}onBufferAppending(t,r){const{tracks:n}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:h}=r,m=d.buffering[i],{sn:x,cc:y}=o,v=self.performance.now();m.start=v;const w=o.stats.buffering,b=c?c.stats.buffering:null;w.start===0&&(w.start=v),b&&b.start===0&&(b.start=v);const N=n.audio;let S=!1;i==="audio"&&(N==null?void 0:N.container)==="audio/mpeg"&&(S=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const T=n.video,A=T==null?void 0:T.buffer;if(A&&x!=="initSegment"){const R=c||o,$=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const z=R.start+R.duration*.05,Q=A.buffered,K=this.currentOp("video");!Q.length&&!K?this.blockAudio(R):!K&&!Ai.isBuffered(A,z)&&this.lastVideoAppendEndz||F{var R;m.executeStart=self.performance.now();const $=(R=this.tracks[i])==null?void 0:R.buffer;$&&(S?this.updateTimestampOffset($,I,.1,i,x,y):h!==void 0&&Zn(h)&&this.updateTimestampOffset($,h,1e-6,i,x,y)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const R=self.performance.now();m.executeEnd=m.end=R,w.first===0&&(w.first=R),b&&b.first===0&&(b.first=R);const $={};this.sourceBuffers.forEach(([F,z])=>{F&&($[F]=Ai.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(ht.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:$})},onError:R=>{var $;const F={type:La.MEDIA_ERROR,parent:o.type,details:ar.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:R,err:R,fatal:!1},z=($=this.media)==null?void 0:$.error;if(R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R)F.details=ar.BUFFER_FULL_ERROR;else if(R.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!z)F.errorAction=XA(!0);else if(R.name===Bgt&&this.sourceBufferCount===0)F.errorAction=XA(!0);else{const Q=++this.appendErrors[i];this.warn(`Failed ${Q}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${z||"no media error"})`),(Q>=this.hls.config.appendErrorMaxRetry||z)&&(F.fatal=!0)}this.hls.trigger(ht.ERROR,F)}};this.log(`queuing "${i}" append sn: ${x}${c?" p: "+c.index:""} of ${o.type===ua.MAIN?"level":"track"} ${o.level} cc: ${y}`),this.append(D,i,this.isPending(this.tracks[i]))}getFlushOp(t,r,n){return this.log(`queuing "${t}" remove ${r}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(t,r,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(ht.BUFFER_FLUSHED,{type:t})},onError:a=>{this.warn(`Failed to remove ${r}-${n} from "${t}" SourceBuffer`,a)}}}onBufferFlushing(t,r){const{type:n,startOffset:a,endOffset:i}=r;n?this.append(this.getFlushOp(n,a,i),n):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,r){const{frag:n,part:a}=r,i=[],l=a?a.elementaryStreams:n.elementaryStreams;l[Hl.AUDIOVIDEO]?i.push("audiovideo"):(l[Hl.AUDIO]&&i.push("audio"),l[Hl.VIDEO]&&i.push("video"));const o=()=>{const c=self.performance.now();n.stats.buffering.end=c,a&&(a.stats.buffering.end=c);const d=a?a.stats:n.stats;this.hls.trigger(ht.FRAG_BUFFERED,{frag:n,part:a,stats:d,id:n.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(o,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,r){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const r=this.tracks[t];if(r)return!r.ended||r.ending}return!1})}onBufferEos(t,r){var n;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!r.type||r.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((n=this.overrides)==null?void 0:n.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(ht.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(ht.BUFFERED_TO_END,void 0)):r.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const r=this.tracks[t];r&&(r.ending=!1)}})}onLevelUpdated(t,{details:r}){r.fragments.length&&(this.details=r,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,r){if(r.details===ar.BUFFER_APPEND_ERROR&&r.frag){var n;const a=(n=r.errorAction)==null?void 0:n.nextAutoLevel;Zn(a)&&a!==r.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:r,media:n}=this;if(!n||r===null||!this.sourceBufferCount)return;const a=t.config,i=n.currentTime,l=r.levelTargetDuration,o=r.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(Zn(o)&&o>=0){const d=Math.max(o,l),h=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,h)}const c=a.frontBufferFlushThreshold;if(Zn(c)&&c>0){const d=Math.max(a.maxBufferLength,c),h=Math.max(d,l),m=Math.floor(i/l)*l+h;this.flushFrontBuffer(i,l,m)}}flushBackBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=Ai.getBuffered(i);if(o.length>0&&n>o.start(0)){var l;this.hls.trigger(ht.BACK_BUFFER_REACHED,{bufferEnd:n});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(ht.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(c!=null&&c.ended){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(ht.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:a})}}})}flushFrontBuffer(t,r,n){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=Ai.getBuffered(i),o=l.length;if(o<2)return;const c=l.start(o-1),d=l.end(o-1);if(n>c||t>=c&&t<=d)return;this.hls.trigger(ht.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:r,mediaSource:n}=this;if(!r||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const a=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&n.setLiveSeekableRange){const d=Math.max(0,r.fragmentStart),h=Math.max(d,a);return{duration:1/0,start:d,end:h}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return Zn(i)?{duration:i}:null;const l=this.media.duration,o=Zn(n.duration)?n.duration:0;return a>o&&a>l||!Zn(l)?{duration:a}:null}updateMediaSource({duration:t,start:r,end:n}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Zn(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),r!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${r}-${n}.`),a.setLiveSeekableRange(r,n)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:r,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${r} codec events expected: ${t}) ${Ql(n)}`),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(([r,n])=>{if(r){const a=this.tracks[r];t[r]={buffer:n,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}}),this.hls.trigger(ht.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([r])=>{this.executeNext(r)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:r,mediaSource:n}=this;if(!n)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":""} ${Ql(o)}`);try{const h=n.addSourceBuffer(d),m=Kbe(l),x=[l,h];r[m]=x,o.buffer=h}catch(h){var a;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,r){const n=t.supplemental;let a=t.codec;n&&(r==="video"||r==="audiovideo")&&jF(n,"video")&&(a=m8s(a,n));const i=Ece(a,t.levelCodec);return i?r.slice(0,5)==="audio"?ime(i,this.appendSource):i:""}trackSourceBuffer(t,r){const n=r.buffer;if(!n)return;const a=this.getTrackCodec(r,t);this.tracks[t]={buffer:n,codec:a,container:r.container,levelCodec:r.levelCodec,supplemental:r.supplemental,metadata:r.metadata,id:r.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(ht.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var t,r;const n=((t=this.media)==null||(r=t.querySelector)==null?void 0:r.call(t,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(t){const r=this.currentOp(t);r&&r.onStart()}onSBUpdateEnd(t){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(t);return}const n=this.currentOp(t);n&&(n.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,r){var n;const a=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${a}`,r),this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,r,n,a,i,l){const o=r-t.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${r} (sn: ${i} cc: ${l})`),t.timestampOffset=r)}removeExecutor(t,r,n){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=Zn(a.duration)?a.duration:1/0,d=Zn(i.duration)?i.duration:1/0,h=Math.max(0,r),m=Math.min(n,c,d);m>h&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${h},${m}] from the ${t} SourceBuffer`),o.remove(h,m)):this.shiftAndExecuteNext(t)}appendExecutor(t,r){const n=this.tracks[r],a=n==null?void 0:n.buffer;if(!a)throw new wBs(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,a.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(r=>{this.warn(`SourceBuffer blocked callback ${r}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(r){this.warn(`Callback run without blocking ${this.operationQueue} ${r}`)}}isUpdating(){return this.sourceBuffers.some(([t,r])=>t&&r.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,r=this.sourceBufferTypes){if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:n}=this,a=r.map(l=>this.appendBlocker(l));return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(a).then(l=>{n===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(r=>{var n;const a=(n=this.tracks[r])==null?void 0:n.buffer;!a||a.updating||this.shiftAndExecuteNext(r)})}append(t,r,n){this.operationQueue&&this.operationQueue.append(t,r,n)}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,r)=>t+(this.isPending(this.tracks[r])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[r])=>t+(r?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,r,n){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=n.bind(this,t);a.listeners.push({event:r,listener:l}),i.addEventListener(r,l)}removeBufferListeners(t){const r=this.tracks[t];if(!r)return;const n=r.buffer;n&&(r.listeners.forEach(a=>{n.removeEventListener(a.event,a.listener)}),r.listeners.length=0)}}function MHe(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(r=>{s.removeChild(r)})}function NBs(s,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,s.appendChild(r)}function Kbe(s){return s==="audio"?1:0}class gAe{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(ht.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ht.BUFFER_CODECS,this.onBufferCodecs,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(ht.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ht.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(t,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(t,r){this.timer&&Zn(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,r){this.hls.config.capLevelToPlayerSize&&r.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 r=this.hls,n=this.getMaxLevel(t.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${t[n].height}p@${t[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(t){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,gAe.getMaxLevelByMediaSize(n,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,r={width:0,height:0};if(t){const n=t.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||t.width||0,r.height=n.bottom-n.top||t.height||0)}return this.clientRect=r,r}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(n=>t.bitrate===n.bitrate&&t.width===n.width&&t.height===n.height)}static getMaxLevelByMediaSize(t,r,n){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(r,n);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}const kBs={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Pf=kBs,SBs={HLS:"h"},CBs=SBs;class Mv{constructor(t,r){Array.isArray(t)&&(t=t.map(n=>n instanceof Mv?n:new Mv(n))),this.value=t,this.params=r}}const TBs="Dict";function EBs(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 ABs(s,t,r,n){return new Error(`failed to ${s} "${EBs(t)}" as ${r}`,{cause:n})}function Iv(s,t,r){return ABs("serialize",s,t,r)}class zgt{constructor(t){this.description=t}}const IHe="Bare Item",MBs="Boolean";function IBs(s){if(typeof s!="boolean")throw Iv(s,MBs);return s?"?1":"?0"}function LBs(s){return btoa(String.fromCharCode(...s))}const PBs="Byte Sequence";function DBs(s){if(ArrayBuffer.isView(s)===!1)throw Iv(s,PBs);return`:${LBs(s)}:`}const RBs="Integer";function OBs(s){return s<-999999999999999||99999999999999912)throw Iv(s,BBs);const r=t.toString();return r.includes(".")?r:`${r}.0`}const $Bs="String",UBs=/[\x00-\x1f\x7f]+/;function qBs(s){if(UBs.test(s))throw Iv(s,$Bs);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function VBs(s){return s.description||s.toString().slice(7,-1)}const HBs="Token";function LHe(s){const t=VBs(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Iv(t,HBs);return t}function Qke(s){switch(typeof s){case"number":if(!Zn(s))throw Iv(s,IHe);return Number.isInteger(s)?$gt(s):zBs(s);case"string":return qBs(s);case"symbol":return LHe(s);case"boolean":return IBs(s);case"object":if(s instanceof Date)return FBs(s);if(s instanceof Uint8Array)return DBs(s);if(s instanceof zgt)return LHe(s);default:throw Iv(s,IHe)}}const GBs="Key";function Jke(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Iv(s,GBs);return s}function yAe(s){return s==null?"":Object.entries(s).map(([t,r])=>r===!0?`;${Jke(t)}`:`;${Jke(t)}=${Qke(r)}`).join("")}function qgt(s){return s instanceof Mv?`${Qke(s.value)}${yAe(s.params)}`:Qke(s)}function WBs(s){return`(${s.value.map(qgt).join(" ")})${yAe(s.params)}`}function KBs(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw Iv(s,TBs);const r=s instanceof Map?s.entries():Object.entries(s),n=t!=null&&t.whitespace?" ":"";return Array.from(r).map(([a,i])=>{i instanceof Mv||(i=new Mv(i));let l=Jke(a);return i.value===!0?l+=yAe(i.params):(l+="=",Array.isArray(i.value)?l+=WBs(i):l+=qgt(i)),l}).join(`,${n}`)}function Vgt(s,t){return KBs(s,t)}const _0="CMCD-Object",_d="CMCD-Request",CN="CMCD-Session",V_="CMCD-Status",YBs={br:_0,ab:_0,d:_0,ot:_0,tb:_0,tpb:_0,lb:_0,tab:_0,lab:_0,url:_0,pb:_d,bl:_d,tbl:_d,dl:_d,ltc:_d,mtp:_d,nor:_d,nrr:_d,rc:_d,sn:_d,sta:_d,su:_d,ttfb:_d,ttfbb:_d,ttlb:_d,cmsdd:_d,cmsds:_d,smrt:_d,df:_d,cs:_d,ts:_d,cid:CN,pr:CN,sf:CN,sid:CN,st:CN,v:CN,msd:CN,bs:V_,bsd:V_,cdn:V_,rtp:V_,bg:V_,pt:V_,ec:V_,e:V_},ZBs={REQUEST:_d};function XBs(s){return Object.keys(s).reduce((t,r)=>{var n;return(n=s[r])===null||n===void 0||n.forEach(a=>t[a]=r),t},{})}function QBs(s,t){const r={};if(!s)return r;const n=Object.keys(s),a=t?XBs(t):{};return n.reduce((i,l)=>{var o;const c=YBs[l]||a[l]||ZBs.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},r)}function JBs(s){return["ot","sf","st","e","sta"].includes(s)}function ezs(s){return typeof s=="number"?Zn(s):s!=null&&s!==""&&s!==!1}const Hgt="event";function tzs(s,t){const r=new URL(s),n=new URL(t);if(r.origin!==n.origin)return s;const a=r.pathname.split("/").slice(1),i=n.pathname.split("/").slice(1,-1);for(;a[0]===i[0];)a.shift(),i.shift();for(;i.length;)i.shift(),a.unshift("..");return a.join("/")+r.search+r.hash}const Pce=s=>Math.round(s),eSe=(s,t)=>Array.isArray(s)?s.map(r=>eSe(r,t)):s instanceof Mv&&typeof s.value=="string"?new Mv(eSe(s.value,t),s.params):(t.baseUrl&&(s=tzs(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),iU=s=>Pce(s/100)*100,szs=(s,t)=>{let r=s;return t.version>=2&&(s instanceof Mv&&typeof s.value=="string"?r=new Mv([s]):typeof s=="string"&&(r=[s])),eSe(r,t)},rzs={br:Pce,d:Pce,bl:iU,dl:iU,mtp:iU,nor:szs,rtp:iU,tb:Pce},Ggt="request",Wgt="response",vAe=["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"],nzs=["e"],azs=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Xxe(s){return azs.test(s)}function izs(s){return vAe.includes(s)||nzs.includes(s)||Xxe(s)}const Kgt=["d","dl","nor","ot","rtp","su"];function ozs(s){return vAe.includes(s)||Kgt.includes(s)||Xxe(s)}const lzs=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function czs(s){return vAe.includes(s)||Kgt.includes(s)||lzs.includes(s)||Xxe(s)}const dzs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function uzs(s){return dzs.includes(s)||Xxe(s)}const hzs={[Wgt]:czs,[Hgt]:izs,[Ggt]:ozs};function Ygt(s,t={}){const r={};if(s==null||typeof s!="object")return r;const n=t.version||s.v||1,a=t.reportingMode||Ggt,i=n===1?uzs:hzs[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===Wgt||a===Hgt;c&&!l.includes("ts")&&l.push("ts"),n>1&&!l.includes("v")&&l.push("v");const d=zl({},rzs,t.formatters),h={version:n,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(m=>{let x=s[m];const y=d[m];if(typeof y=="function"&&(x=y(x,h)),m==="v"){if(n===1)return;x=n}m=="pr"&&x===1||(c&&m==="ts"&&!Zn(x)&&(x=Date.now()),ezs(x)&&(JBs(m)&&typeof x=="string"&&(x=new zgt(x)),r[m]=x))}),r}function mzs(s,t={}){const r={};if(!s)return r;const n=Ygt(s,t),a=QBs(n,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=Vgt(o,{whitespace:!1});return c&&(i[l]=c),i},r)}function fzs(s,t,r){return zl(s,mzs(t,r))}const pzs="CMCD";function xzs(s,t={}){return s?Vgt(Ygt(s,t),{whitespace:!1}):""}function gzs(s,t={}){if(!s)return"";const r=xzs(s,t);return encodeURIComponent(r)}function yzs(s,t={}){if(!s)return"";const r=gzs(s,t);return`${pzs}=${r}`}const PHe=/CMCD=[^&#]+/;function vzs(s,t,r){const n=yzs(t,r);if(!n)return s;if(PHe.test(s))return s.replace(PHe,n);const a=s.includes("?")?"&":"?";return`${s}${a}${n}`}class bzs{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:Pf.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===Pf.VIDEO||c===Pf.AUDIO||c==Pf.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const h=l?this.getNextPart(l):this.getNextFrag(i);h!=null&&h.url&&h.url!==i.url&&(d.nor=h.url),this.apply(a,d)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=t;const r=this.config=t.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHED,this.onMediaDetached,this),t.on(ht.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHED,this.onMediaDetached,this),t.off(ht.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,r){this.media=r.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,r){var n,a;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(a=r.tracks.video)==null?void 0:a.buffer}createData(){var t;return{v:1,sf:CBs.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,r={}){zl(r,this.createData());const n=r.ot===Pf.INIT||r.ot===Pf.VIDEO||r.ot===Pf.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:a}=this;a&&(r=Object.keys(r).reduce((l,o)=>(a.includes(o)&&(l[o]=r[o]),l),{}));const i={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),fzs(t.headers,r,i)):t.url=vzs(t.url,r,i)}getNextFrag(t){var r;const n=(r=this.hls.levels[t.level])==null?void 0:r.details;if(n){const a=t.sn-n.startSN;return n.fragments[a+1]}}getNextPart(t){var r;const{index:n,fragment:a}=t,i=(r=this.hls.levels[a.level])==null||(r=r.details)==null?void 0:r.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===n&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t){const{type:r}=t;if(r==="subtitle")return Pf.TIMED_TEXT;if(t.sn==="initSegment")return Pf.INIT;if(r==="audio")return Pf.AUDIO;if(r==="main")return this.hls.audioTracks.length?Pf.VIDEO:Pf.MUXED}getTopBandwidth(t){let r=0,n;const a=this.hls;if(t===Pf.AUDIO)n=a.audioTracks;else{const i=a.maxAutoLevel,l=i>-1?i+1:a.levels.length;n=a.levels.slice(0,l)}return n.forEach(i=>{i.bitrate>r&&(r=i.bitrate)}),r>0?r:NaN}getBufferLength(t){const r=this.media,n=t===Pf.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:Ai.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,r=this.applyPlaylistData,n=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(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){r(i),this.loader.load(i,l,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,r=this.applyFragmentData,n=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new n(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){r(i),this.loader.load(i,l,o)}}}}const _zs=3e5;class wzs extends Sg{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(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ht.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ht.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,r)=>(t.indexOf(r.pathwayId)===-1&&t.push(r.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 r=this.levels;r&&(this.levels=r.filter(n=>n!==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,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(t,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(t,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===Uh.SendAlternateToPenaltyBox&&n.flags===Tp.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(r.context){const{groupId:o,pathwayId:c,type:d}=r.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),n.resolved=this.pathwayId!==l),r.details===ar.BUFFER_APPEND_ERROR&&!r.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${Ql(i)} penalized: ${Ql(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==t.length&&this.log(`Found ${r.length}/${t.length} levels in Pathway "${this.pathwayId}"`),r}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(r=>t===r.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let r;const n=this.penalizedPathways,a=performance.now();Object.keys(n).forEach(i=>{a-n[i]>_zs&&delete n[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,pgt(r),this.hls.trigger(ht.LEVELS_UPDATED,{levels:r});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,r,n){const a=this.getLevelsForPathway(n).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(r.some(h=>h.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(h=>{const m=new ed(h.attrs);m["PATHWAY-ID"]=l;const x=m.AUDIO&&`${m.AUDIO}_clone_${l}`,y=m.SUBTITLES&&`${m.SUBTITLES}_clone_${l}`;x&&(n[m.AUDIO]=x,m.AUDIO=x),y&&(a[m.SUBTITLES]=y,m.SUBTITLES=y);const v=Zgt(h.uri,m["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),w=new kF({attrs:m,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:v,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let b=1;b{this.log(`Loaded steering manifest: "${a}"`);const v=h.data;if((v==null?void 0:v.VERSION)!==1){this.log(`Steering VERSION ${v.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=v.TTL;const{"RELOAD-URI":w,"PATHWAY-CLONES":b,"PATHWAY-PRIORITY":N}=v;if(w)try{this.uri=new self.URL(w,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${w}`);return}this.scheduleRefresh(this.uri||x.url),b&&this.clonePathways(b);const S={steeringManifest:v,url:a.toString()};this.hls.trigger(ht.STEERING_MANIFEST_LOADED,S),N&&this.updatePathwayPriority(N)},onError:(h,m,x,y)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${m.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${m.url} no longer available`);return}let v=this.timeToLoad*1e3;if(h.code===429){const w=this.loader;if(typeof(w==null?void 0:w.getResponseHeader)=="function"){const b=w.getResponseHeader("Retry-After");b&&(v=parseFloat(b)*1e3)}this.log(`Steering manifest ${m.url} rate limited`);return}this.scheduleRefresh(this.uri||m.url,v)},onTimeout:(h,m,x)=>{this.log(`Timeout loading steering manifest (${m.url})`),this.scheduleRefresh(this.uri||m.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const a=(n=this.hls)==null?void 0:n.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},r)}}function DHe(s,t,r,n){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=zl({},l);return o.details=void 0,o.attrs=new ed(o.attrs),o.url=o.attrs.URI=Zgt(l.url,l.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),o.groupId=o.attrs["GROUP-ID"]=t[a],o.attrs["PATHWAY-ID"]=n,o});s.push(...i)})}function Zgt(s,t,r,n){const{HOST:a,PARAMS:i,[r]:l}=n;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 JA extends Sg{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=JA.CDMCleanupPromise?[JA.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:a}=r,i=`"${r.type}" event: init data type: "${n}"`;if(this.debug(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=UD(this.config));const o=l.map(zbe).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=Mce(l);if(n!=="sinf"||o!==od.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${o}`);return}let c;try{const y=Pu(new Uint8Array(a)),v=oAe(JSON.parse(y).sinf),w=Vxt(v);if(!w)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(w.subarray(8,24))}catch(y){this.warn(`${i} Failed to parse sinf: ${y}`);return}const d=qh(c),{keyIdToKeySessionPromise:h,mediaKeySessions:m}=this;let x=h[d];for(let y=0;ythis.generateRequestWithPreferredKeySession(v,n,a,"encrypted-event-key-match")),x.catch(N=>this.handleError(N));break}}x||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${m.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=r=>{this.log(`"${r.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(ht.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(ht.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(ht.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(ht.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(ht.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(ht.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(ht.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:r,widevineLicenseUrl:n}=this.config,a=r==null?void 0:r[t];if(a)return a.licenseUrl;if(t===od.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(t){const r=this.getLicenseServerUrl(t);if(r===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return r}getServerCertificateUrl(t){const{drmSystems:r}=this.config,n=r==null?void 0:r[t];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const r=this.hls.levels,n=(l,o,c)=>!!l&&c.indexOf(l)===o,a=r.map(l=>l.audioCodec).filter(n),i=r.map(l=>l.videoCodec).filter(n);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const h=d.shift();this.getMediaKeysPromise(h,a,i).then(m=>l({keySystem:h,mediaKeys:m})).catch(m=>{d.length?c(d):m instanceof kp?o(m):o(new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_NO_ACCESS,error:m,fatal:!0},m.message))})};c(t)})}requestMediaKeySystemAccess(t,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let a=`Configured requestMediaKeySystemAccess is not a function ${n}`;return ogt===null&&self.location.protocol==="http:"&&(a=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(a))}return n(t,r)}getMediaKeysPromise(t,r,n){var a;const i=sFs(t,r,n,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: ${Ql(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 h=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const m=c.mediaKeys=d.createMediaKeys().then(x=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,h.then(y=>y?this.setMediaKeysServerCertificate(x,t,y):x)));return m.catch(x=>{this.error(`Failed to create media-keys for "${t}"}: ${x}`)}),m})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${qh(t.keyId||[])} keyUri: ${t.uri}`);const a=n.createSession(),i={decryptdata:t,keySystem:r,mediaKeys:n,mediaKeysSession:a,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const r=t.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(t),a=oU(r),i="cenc";this.keyIdToKeySessionPromise[a]=this.generateRequestWithPreferredKeySession(n,i,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,r){const n=t.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${qh(t.decryptdata.keyId||[])} } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>zbe(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(t){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:a})=>{const i=zbe(a);i?r(i):n(new Error(`Unable to find format for key-system "${a}"`))}).catch(n)})}selectKeySystemFormat(t){const r=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(t){const r=UD(this.config),n=t.map(Mce).filter(a=>!!a&&r.indexOf(a)!==-1);return this.selectKeySystem(n)}getKeyStatus(t){const{mediaKeySessions:r}=this;for(let n=0;n(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:r}))))).then(c=>{const d="cenc",h=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,h,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[n]=o,o}return l.catch(o=>{if(o instanceof kp){const c=Sl({},o.data);this.getKeyStatus(r)==="internal-error"&&(c.decryptdata=r);const d=new kp(c,o.message);this.handleError(d,t.frag)}}),l}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,r){if(this.hls)if(t instanceof kp){r&&(t.data.frag=r);const n=t.data.decryptdata;this.error(`${t.message}${n?` (${qh(n.keyId||[])})`:""}`),this.hls.trigger(ht.ERROR,t.data)}else this.error(t.message),this.hls.trigger(ht.ERROR,{type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const r=oU(t),n=this.keyIdToKeySessionPromise[r];if(!n){const a=Mce(t.keyFormat),i=a?[a]:UD(this.config);return this.attemptKeySystemAccess(i)}return n}getKeySystemSelectionPromise(t){if(t.length||(t=UD(this.config)),t.length===0)throw new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ql({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):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=r,this.media.setMediaKeys(r).then(i).catch(l)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),n.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>n.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,r,n,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const v=l.call(this.hls,r,n,t);if(!v)throw new Error("Invalid response from configured generateRequest filter");r=v.initDataType,n=v.initData?v.initData:null,t.decryptdata.pssh=n?new Uint8Array(n):null}catch(v){if(this.warn(v.message),this.hls&&this.hls.config.debug)throw v}if(n===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=oU(t.decryptdata),c=t.decryptdata.uri;this.log(`Generating key-session request for "${a}" keyId: ${o} URI: ${c} (init data type: ${r} length: ${n.byteLength})`);const d=new cAe,h=t._onmessage=v=>{const w=t.mediaKeysSession;if(!w){d.emit("error",new Error("invalid state"));return}const{messageType:b,message:N}=v;this.log(`"${b}" message event for session "${w.sessionId}" message size: ${N.byteLength}`),b==="license-request"||b==="license-renewal"?this.renewLicense(t,N).catch(S=>{d.eventNames().length?d.emit("error",S):this.handleError(S)}):b==="license-release"?t.keySystem===od.FAIRPLAY&&this.updateKeySession(t,Gke("acknowledged")).then(()=>this.removeSession(t)).catch(S=>this.handleError(S)):this.warn(`unhandled media key message type "${b}"`)},m=(v,w)=>{w.keyStatus=v;let b;v.startsWith("usable")?d.emit("resolved"):v==="internal-error"||v==="output-restricted"||v==="output-downscaled"?b=RHe(v,w.decryptdata):v==="expired"?b=new Error(`key expired (keyId: ${o})`):v==="released"?b=new Error("key released"):v==="status-pending"||this.warn(`unhandled key status change "${v}" (keyId: ${o})`),b&&(d.eventNames().length?d.emit("error",b):this.handleError(b))},x=t._onkeystatuseschange=v=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const b=this.getKeyStatuses(t);if(!Object.keys(b).some(A=>b[A]!=="status-pending"))return;if(b[o]==="expired"){this.log(`Expired key ${Ql(b)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let S=b[o];if(S)m(S,t);else{var T;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(T=t.keyStatusTimeouts)[o]||(T[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const I=this.getKeyStatus(t.decryptdata);if(I&&I!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${I} from other session.`),m(I,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),S="internal-error",m(S,t)},1e3)),this.log(`No status for keyId ${o} (${Ql(b)}).`)}};ff(t.mediaKeysSession,"message",h),ff(t.mediaKeysSession,"keystatuseschange",x);const y=new Promise((v,w)=>{d.on("error",w),d.on("resolved",v)});return t.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(v=>{throw new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_NO_SESSION,error:v,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${v}`)}).then(()=>y).catch(v=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw v}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const r={};return t.mediaKeysSession.keyStatuses.forEach((n,a)=>{if(typeof a=="string"&&typeof n=="object"){const o=a;a=n,n=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===od.PLAYREADY&&i.length===16){const o=qh(i);r[o]=n,agt(i)}const l=qh(i);n==="internal-error"&&(this.bannedKeyIds[l]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),r[l]=n}),r}fetchServerCertificate(t){const r=this.config,n=r.loader,a=new n(r),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=r.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(x,y,v,w)=>{l(x.data)},onError:(x,y,v,w)=>{o(new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:v,response:Sl({url:c.url,data:void 0},x)},`"${t}" certificate request failed (${i}). Status: ${x.code} (${x.text})`))},onTimeout:(x,y,v)=>{o(new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:v,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(x,y,v)=>{o(new Error("aborted"))}};a.load(c,h,m)})):Promise.resolve()}setMediaKeysServerCertificate(t,r,n){return new Promise((a,i)=>{t.setServerCertificate(n).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),a(t)}).catch(l=>{i(new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,r){return this.requestLicense(t,new Uint8Array(r)).then(n=>this.updateKeySession(t,new Uint8Array(n)).catch(a=>{throw new kp({type:La.KEY_SYSTEM_ERROR,details:ar.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const a=new DOMParser().parseFromString(n,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let h;for(let m=0,x=i.length;m in key message");return Gke(atob(d))}setupLicenseXHR(t,r,n,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,r,n,a)}).catch(l=>{if(!n.decryptdata)throw l;return t.open("POST",r,!0),i.call(this.hls,t,r,n,a)}).then(l=>(t.readyState||t.open("POST",r,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",r,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,r){const n=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(h){this.error(h)}a(c)}else{const c=n.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new kp({type:La.KEY_SYSTEM_ERROR,details:ar.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 h=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,r).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,r).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==od.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,ff(n,"encrypted",this.onMediaEncrypted),ff(n,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=n.mediaKeys}onMediaDetached(){const t=this.media;t&&(Wf(t,"encrypted",this.onMediaEncrypted),Wf(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,wj.clearKeyUriToKeyIdMap();const i=a.length;JA.CDMCleanupPromise=Promise.all(a.map(l=>this.removeSession(l)).concat((n==null||(t=n.setMediaKeys(null))==null?void 0:t.catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(ht.ERROR,{type:La.OTHER_ERROR,details:ar.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(ht.ERROR,{type:La.OTHER_ERROR,details:ar.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:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(t){const{mediaKeysSession:r,licenseXhr:n,decryptdata:a}=t;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${qh((a==null?void 0:a.keyId)||[])}`),t._onmessage&&(r.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.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(nFs(o)?new Promise((d,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(d).catch(h)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(ht.ERROR,{type:La.OTHER_ERROR,details:ar.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>r.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(ht.ERROR,{type:La.OTHER_ERROR,details:ar.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}JA.CDMCleanupPromise=void 0;function oU(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return qh(s.keyId)}function jzs(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 kp extends Error{constructor(t,r){super(r),this.data=void 0,t.error||(t.error=new Error(r)),this.data=t,t.err=t.error}}function RHe(s,t){const r=s==="output-restricted",n=r?ar.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ar.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new kp({type:La.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${s}"`)}class Nzs{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(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const a=r.media instanceof self.HTMLVideoElement?r.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),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,r,n){const a=performance.now();if(r){if(this.lastTime){const i=a-this.lastTime,l=n-this.lastDroppedFrames,o=r-this.lastDecodedFrames,c=1e3*l/i,d=this.hls;if(d.trigger(ht.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:n}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*o){let h=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=h)&&(h=h-1,d.trigger(ht.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const r=t.getVideoPlaybackQuality();this.checkFPS(t,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function Xgt(s,t){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=s,t.dispatchEvent(r)}function Qgt(s,t){const r=s.mode;if(r==="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(n){Al.debug(`[texttrack-utils]: ${n}`);try{const a=new self.TextTrackCue(t.startTime,t.endTime,t.text);a.id=t.id,s.addCue(a)}catch(a){Al.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}r==="disabled"&&(s.mode=r)}function eA(s,t){const r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues)for(let n=s.cues.length;n--;)t&&s.cues[n].removeEventListener("enter",t),s.removeCue(s.cues[n]);r==="disabled"&&(s.mode=r)}function tSe(s,t,r,n){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=Szs(s.cues,t,r);for(let l=0;ls[r].endTime)return-1;let n=0,a=r,i;for(;n<=a;)if(i=Math.floor((a+n)/2),ts[i].startTime&&n-1)for(let i=a,l=s.length;i=t&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}function Dce(s){const t=[];for(let r=0;rthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=Dce(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ht.LEVEL_LOADING,this.onLevelLoading,this),t.on(ht.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ht.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(ht.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ht.LEVEL_LOADING,this.onLevelLoading,this),t.off(ht.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ht.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(ht.ERROR,this.onError,this)}onMediaAttached(t,r){this.media=r.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,r){const n=this.media;if(!n)return;const a=!!r.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,a)return;Dce(n.textTracks).forEach(l=>{eA(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(t,r){const{id:n,groupId:a,details:i}=r,l=this.tracksInGroup[n];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${n} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=r.details,this.log(`Subtitle track ${n} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(t,r){this.switchLevel(r.level)}onLevelSwitching(t,r){this.switchLevel(r.level)}switchLevel(t){const r=this.hls.levels[t];if(!r)return;const n=r.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!n||(a==null?void 0:a.length)!==(n==null?void 0:n.length)||n!=null&&n.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(h=>!n||n.indexOf(h.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(h=>h.default)&&(this.selectDefaultTrack=!1),l.forEach((h,m)=>{h.id=m});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const h=Z0(o,l);if(h>-1)i=l[h];else{const m=Z0(o,this.tracks);i=this.tracks[m]}}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 "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(ht.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(t){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a),i}else{if(n)return null;{const i=Z0(t,r);if(i>-1)return r[i]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,r){super.loadingPlaylist(t,r);const n=t.id,a=t.groupId,i=this.getUrlWithDirectives(t.url,r),l=t.details,o=l==null?void 0:l.age;this.log(`Loading subtitle ${n} "${t.name}" lang:${t.lang} group:${a}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${i}`),this.hls.trigger(ht.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:a,deliveryDirectives:r||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const r=Dce(t.textTracks),n=this.currentTrack;let a;if(n&&(a=r.filter(i=>Xke(n,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).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 r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=r.length||!Zn(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,a=r[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(ht.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===n&&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:h}=a;this.hls.trigger(ht.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:h});const m=this.switchParams(a.url,n==null?void 0:n.details,a.details);this.loadPlaylist(m)}}function Tzs(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),r=t.toString();return URL.revokeObjectURL(t),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(a=="x"?i:i&3|8).toString(16)})}}}function BO(s){let t=5381,r=s.length;for(;r;)t=t*33^s.charCodeAt(--r);return(t>>>0).toString()}const eM=.025;let pme=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function Ezs(s,t,r){return`${s.identifier}-${r+1}-${BO(t)}`}class Azs{constructor(t,r){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=r,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 r;if(t>0&&t>=this.assetList.length)return!0;const n=this.playoutLimit;return t<=0||isNaN(n)?!1:n===0?!0:(((r=this.assetList[t])==null?void 0:r.startOffset)||0)>n}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 r=this.dateRange.tagAnchor;if(r)return Ybe(t,r)}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 r=this.dateRange.startTime,n=Ybe(r,t);return r-n<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,r=Zn(t)?t:this.duration;return this.cumulativeDuration+r}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const r=this.resumeAnchor;if(r)return Ybe(t,r)}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 Mzs(this)}}function Ybe(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function CE(s){const t=s.timelineStart,r=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}class Izs{constructor(t,r,n,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(ht.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(r);this.interstitial=n,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(ht.LEVEL_LOADED,l),i.once(ht.AUDIO_TRACK_LOADED,l),i.once(ht.SUBTITLE_TRACK_LOADED,l),i.on(ht.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(ht.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,i.trigger(ht.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 r=this.assetItem.uri;try{r=Jgt(r,t.config.primarySessionId||"").href}catch{}t.loadSource(r)}}bufferedInPlaceToEnd(t){var r;if(!this.appendInPlace)return!1;if((r=this.hls)!=null&&r.bufferedToEnd)return!0;if(!t)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset,i=Ai.bufferInfo(t,a,0);return this.getAssetTime(i.end)>=n-.02}reachedPlayout(t){const n=this.interstitial.playoutLimit;return this.startOffset+t>=n}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 r=Ai.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(r.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 r=this.interstitial.playoutLimit;if(r){const n=r-this.startOffset;if(n>0&&n1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const r=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,t-r),n)}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 r;this.loadSource(),(r=this.hls)==null||r.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 r=n=>delete n.details;t.levels.forEach(r),t.allAudioTracks.forEach(r),t.allSubtitleTracks.forEach(r),this.hasDetails=!1}}on(t,r,n){var a;(a=this.hls)==null||a.on(t,r)}once(t,r,n){var a;(a=this.hls)==null||a.once(t,r)}off(t,r,n){var a;(a=this.hls)==null||a.off(t,r)}toString(){var t;return`HlsAssetPlayer: ${CE(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const OHe=.033;class Lzs extends Sg{constructor(t,r){super("interstitials-sched",r),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,r){return this.events?this.events.reduce((n,a)=>t<=a.startOffset&&r>a.startOffset?(delete a.error,n+1):n,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,r){if(t.event)return this.findEventIndex(t.event.identifier);let n=-1;t.nextEvent?n=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(n=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[n]||(r===void 0&&(r=t.start),n=this.findItemIndexAtTime(r));n>=0&&(i=a[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(t,r){const n=this.items;if(n)for(let a=0;ai.start&&t1)for(let i=0;io&&(r!o.includes(d.identifier)):[];l.length&&l.sort((d,h)=>{const m=d.cue.pre,x=d.cue.post,y=h.cue.pre,v=h.cue.post;if(m&&!y)return-1;if(y&&!m||x&&!v)return 1;if(v&&!x)return-1;if(!m&&!y&&!x&&!v){const w=d.startTime,b=h.startTime;if(w!==b)return w-b}return d.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,r=[],n=!1){const a=this.events||[];if(a.length||r.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(n||r.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(r,i))}}parseDateRanges(t,r,n){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,r);let c=0,d=0;if(t.forEach((h,m)=>{const x=h.cue.pre,y=h.cue.post,v=t[m-1]||null,w=h.appendInPlace,b=y?i:h.startOffset,N=h.duration,S=h.timelineOccupancy===pme.Range?N:0,T=h.resumptionOffset,A=(v==null?void 0:v.startTime)===b,I=b+h.cumulativeDuration;let D=w?I+N:b+T;if(x||!y&&b<=0){const $=d;d+=S,h.timelineStart=I;const F=l;l+=N,n.push({event:h,start:I,end:D,playout:{start:F,end:l},integrated:{start:$,end:d}})}else if(b<=i){if(!A){const z=b-c;if(z>OHe){const Q=c,K=d;d+=z;const X=l;l+=z;const Z={previousEvent:t[m-1]||null,nextEvent:h,start:Q,end:Q+z,playout:{start:X,end:l},integrated:{start:K,end:d}};n.push(Z)}else z>0&&v&&(v.cumulativeDuration+=z,n[n.length-1].end=b)}y&&(D=I),h.timelineStart=I;const $=d;d+=S;const F=l;l+=N,n.push({event:h,start:I,end:D,playout:{start:F,end:l},integrated:{start:$,end:d}})}else return;const R=h.resumeTime;y||R>i?c=i:c=R}),c{const d=o.cue.pre,h=o.cue.post,m=d?0:h?a:o.startTime;this.updateAssetDurations(o),l===m?o.cumulativeDuration=i:(i=0,l=m),!h&&o.snapOptions.in&&(o.resumeAnchor=e5(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,r)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1eM?(this.log(`"${t.identifier}" resumption ${n} not aligned with estimated timeline end ${a}`),!1):!Object.keys(r).some(l=>{const o=r[l].details,c=o.edge;if(n>=c)return this.log(`"${t.identifier}" resumption ${n} past ${l} playlist end ${c}`),!1;const d=e5(null,o.fragments,n);if(!d)return this.log(`"${t.identifier}" resumption ${n} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=l==="audio"?.175:0;return Math.abs(d.start-n){const b=x.data,N=b==null?void 0:b.ASSETS;if(!Array.isArray(N)){const S=this.assignAssetListError(t,ar.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),v.url,y,w);this.hls.trigger(ht.ERROR,S);return}t.assetListResponse=b,this.hls.trigger(ht.ASSET_LIST_LOADED,{event:t,assetListResponse:b,networkDetails:w})},onError:(x,y,v,w)=>{const b=this.assignAssetListError(t,ar.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${x.code} ${x.text} (${y.url})`),y.url,w,v);this.hls.trigger(ht.ERROR,b)},onTimeout:(x,y,v)=>{const w=this.assignAssetListError(t,ar.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${y.url})`),y.url,x,v);this.hls.trigger(ht.ERROR,w)}};return o.load(c,h,m),this.hls.trigger(ht.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,r,n,a,i,l){return t.error=n,{type:La.NETWORK_ERROR,details:r,fatal:!1,interstitial:t,url:a,error:n,networkDetails:l,stats:i}}}function FHe(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function gE(s,t){return`[${s}] Advancing timeline position to ${t}`}class Dzs extends Sg{constructor(t,r){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 n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;const a=n-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=n,this.bufferedPos=n;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(n,n-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&n=o.end){var c;const y=this.findItemIndex(o);let v=this.schedule.findItemIndexAtTime(n);if(v===-1&&(v=y+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${n} (resolving from ${y} to ${v})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&v>y){const w=this.schedule.findJumpRestrictedIndex(y+1,v);if(w>y){this.setSchedulePosition(w);return}}this.setSchedulePosition(v);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const y=o.event.assetList[0];y&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,y))}return}const h=d.timelineStart,m=d.duration||0;if(l&&n=h+m){var x;(x=o.event)!=null&&x.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,d)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(n>=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);n>=l&&this.setScheduleToAssetAtTime(n,i)},this.onScheduleUpdate=(n,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,h=n.map(w=>w.identifier),m=!!(o.length||h.length);(m||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(w=>ey(w))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let x=null,y=null;l&&(x=this.updateItem(l,this.timelinePos),this.itemsMatch(l,x)?this.playingItem=x:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const v=this.bufferingItem;if(v&&(y=this.updateItem(v,this.bufferedPos),this.itemsMatch(v,y)?this.bufferingItem=y:v.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(v.event,null))),n.forEach(w=>{w.assetList.forEach(b=>{this.clearAssetPlayer(b.identifier,null)})}),this.playerQueue.forEach(w=>{if(w.interstitial.appendInPlace){const b=w.assetItem.timelineStart,N=w.timelineOffset-b;if(N)try{w.timelineOffset=b}catch(S){Math.abs(N)>eM&&this.warn(`${S} ("${w.assetId}" ${w.timelineOffset}->${b})`)}}}),m||a){if(this.hls.trigger(ht.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:h}),this.isInterstitial(l)&&h.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(x,l),v&&y!==x&&this.trimInPlace(y,v),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=r,this.assetListLoader=new Pzs(t),this.schedule=new Lzs(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ht.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ht.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(ht.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(ht.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(ht.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(ht.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(ht.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ht.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ht.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(ht.MEDIA_ENDED,this.onMediaEnded,this),t.on(ht.ERROR,this.onError,this),t.on(ht.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ht.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ht.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(ht.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(ht.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(ht.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(ht.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(ht.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ht.BUFFER_APPENDED,this.onBufferAppended,this),t.off(ht.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ht.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(ht.MEDIA_ENDED,this.onMediaEnded,this),t.off(ht.ERROR,this.onError,this),t.off(ht.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){Wf(t,"play",this.onPlay),Wf(t,"pause",this.onPause),Wf(t,"seeking",this.onSeeking),Wf(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,r){const n=this.media=r.media;ff(n,"seeking",this.onSeeking),ff(n,"timeupdate",this.onTimeupdate),ff(n,"play",this.onPlay),ff(n,"pause",this.onPause)}onMediaAttached(t,r){const n=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(n);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,r){const n=!!r.transferMedia,a=this.media;if(this.media=null,!n&&(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,r=()=>t.bufferingItem||t.waitingItem,n=m=>m&&t.getAssetPlayer(m.identifier),a=(m,x,y,v,w)=>{if(m){let b=m[x].start;const N=m.event;if(N){if(x==="playout"||N.timelineOccupancy!==pme.Point){const S=n(y);(S==null?void 0:S.interstitial)===N&&(b+=S.assetItem.startOffset+S[w])}}else{const S=v==="bufferedPos"?l():t[v];b+=S-m.start}return b}return 0},i=(m,x)=>{var y;if(m!==0&&x!=="primary"&&(y=t.schedule)!=null&&y.length){var v;const w=t.schedule.findItemIndexAtTime(m),b=(v=t.schedule.items)==null?void 0:v[w];if(b){const N=b[x].start-b.start;return m+N}}return m},l=()=>{const m=t.bufferedPos;return m===Number.MAX_VALUE?o("primary"):Math.max(m,0)},o=m=>{var x,y;return(x=t.primaryDetails)!=null&&x.live?t.primaryDetails.edge:((y=t.schedule)==null?void 0:y.durations[m])||0},c=(m,x)=>{var y,v;const w=t.effectivePlayingItem;if(w!=null&&(y=w.event)!=null&&y.restrictions.skip||!t.schedule)return;t.log(`seek to ${m} "${x}"`);const b=t.effectivePlayingItem,N=t.schedule.findItemIndexAtTime(m,x),S=(v=t.schedule.items)==null?void 0:v[N],T=t.getBufferingPlayer(),A=T==null?void 0:T.interstitial,I=A==null?void 0:A.appendInPlace,D=b&&t.itemsMatch(b,S);if(b&&(I||D)){const R=n(t.playingAsset),$=(R==null?void 0:R.media)||t.primaryMedia;if($){const F=x==="primary"?$.currentTime:a(b,x,t.playingAsset,"timelinePos","currentTime"),z=m-F,Q=(I?F:$.currentTime)+z;if(Q>=0&&(!R||I||Q<=R.duration)){$.currentTime=Q;return}}}if(S){let R=m;if(x!=="primary"){const F=S[x].start,z=m-F;R=S.start+z}const $=!t.isInterstitial(S);if((!t.isInterstitial(b)||b.event.appendInPlace)&&($||S.event.appendInPlace)){const F=t.media||(I?T==null?void 0:T.media:null);F&&(F.currentTime=R)}else if(b){const F=t.findItemIndex(b);if(N>F){const Q=t.schedule.findJumpRestrictedIndex(F+1,N);if(Q>F){t.setSchedulePosition(Q);return}}let z=0;if($)t.timelinePos=R,t.checkBuffer();else{const Q=S.event.assetList,K=m-(S[x]||S).start;for(let X=Q.length;X--;){const Z=Q[X];if(Z.duration&&K>=Z.startOffset&&K{const m=t.effectivePlayingItem;if(t.isInterstitial(m))return m;const x=r();return t.isInterstitial(x)?x:null},h={get bufferedEnd(){const m=r(),x=t.bufferingItem;if(x&&x===m){var y;return a(x,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-x.playout.start||((y=t.bufferingAsset)==null?void 0:y.startOffset)||0}return 0},get currentTime(){const m=d(),x=t.effectivePlayingItem;return x&&x===m?a(x,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-x.playout.start:0},set currentTime(m){const x=d(),y=t.effectivePlayingItem;y&&y===x&&c(m+y.playout.start,"playout")},get duration(){const m=d();return m?m.playout.end-m.playout.start:0},get assetPlayers(){var m;const x=(m=d())==null?void 0:m.event.assetList;return x?x.map(y=>t.getAssetPlayer(y.identifier)):[]},get playingIndex(){var m;const x=(m=d())==null?void 0:m.event;return x&&t.effectivePlayingAsset?x.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var m;return((m=t.schedule)==null||(m=m.events)==null?void 0:m.slice(0))||[]},get schedule(){var m;return((m=t.schedule)==null||(m=m.items)==null?void 0:m.slice(0))||[]},get interstitialPlayer(){return d()?h:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const m=r();return t.findItemIndex(m)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const m=t.effectivePlayingItem;return t.findItemIndex(m)},primary:{get bufferedEnd(){return l()},get currentTime(){const m=t.timelinePos;return m>0?m:0},set currentTime(m){c(m,"primary")},get duration(){return o("primary")},get seekableStart(){var m;return((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(r(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(m){c(m,"integrated")},get duration(){return o("integrated")},get seekableStart(){var m;return i(((m=t.primaryDetails)==null?void 0:m.fragmentStart)||0,"integrated")}},skip:()=>{const m=t.effectivePlayingItem,x=m==null?void 0:m.event;if(x&&!x.restrictions.skip){const y=t.findItemIndex(m);if(x.appendInPlace){const v=m.playout.start+m.event.duration;c(v+.001,"playout")}else t.advanceAfterAssetEnded(x,y,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const r=this.playingItem,n=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!r||!n?!1:this.findItemIndex(r)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,r;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(r=a)==null?void 0:r.currentTime;if(!(i===void 0||!Zn(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,r){const n=this.getAssetPlayer(t);n&&this.transferMediaFromPlayer(n,r)}transferMediaFromPlayer(t,r){const n=t.interstitial.appendInPlace,a=t.media;if(n&&a===this.primaryMedia){if(this.bufferingAsset=null,(!r||this.isInterstitial(r)&&!r.event.appendInPlace)&&r&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Ql(i)}`),this.detachedData=i}else r&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,r){var n,a;if(t.media===r)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(n=this.detachedData)==null?void 0:n.mediaSource;let h;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),h="Primary";else if(d){const v=this.getBufferingPlayer();v?(i=v.transferMedia(),h=`${v}`):h="detached MediaSource"}else h="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${Ql(i)}`);else if(!this.detachedData||l.media===r){const v=this.playerQueue;v.length>1&&v.forEach(w=>{if(o&&w.interstitial.appendInPlace!==c){const b=w.interstitial;this.clearInterstitial(w.interstitial,null),b.appendInPlace=!1,b.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${b}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const m=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",x=m&&i?i:r;this.log(`${m?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${h} (media.currentTime: ${r.currentTime})`);const y=this.schedule;if(x===i&&y){const v=o&&t.assetId===y.assetIdAtEnd;x.overrides={duration:y.duration,endOfStream:!o||v,cueRemoval:!o}}t.attachMedia(x)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,r=t==null?void 0:t.events;if(!r||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,a=this.effectivePlayingItem;if(n===-1){const i=this.hls.startPosition;if(this.timelinePos=i,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(gE("checkStart (preroll)",i));const l=t.findEventIndex(r[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(gE("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(gE("checkStart (playing item)",a.start));const i=t.findItemIndex(a);this.setSchedulePosition(i)}}advanceAssetBuffering(t,r){const n=t.event,a=n.findAssetIndex(r),i=Zbe(n,a);if(!n.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,r,n){const a=Zbe(t,n);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=r+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}, ${r} (${i&&ey(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const h=l.event,m=this.playingAsset,x=m==null?void 0:m.identifier,y=x?this.getAssetPlayer(x):null;if(y&&x&&(!this.eventItemsMatch(l,i)||r!==void 0&&x!==h.assetList[r].identifier)){var c;const v=h.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${v+1}/${h.assetList.length} ${CE(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(ht.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:v,event:h,schedule:a.slice(0),scheduleIndex:t,player:y}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),v);return}this.retreiveMediaSource(x,i),y.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&y.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${ey(l)}`),h.hasPlayed=!0,this.hls.trigger(ht.INTERSTITIAL_ENDED,{event:h,schedule:a.slice(0),scheduleIndex:t}),h.cue.once)){var d;this.updateSchedule();const v=(d=this.schedule)==null?void 0:d.items;if(i&&v){const w=this.findItemIndex(i);this.advanceSchedule(w,v,r,l,o)}return}}this.advanceSchedule(t,a,r,l,o)}advanceSchedule(t,r,n,a,i){const l=this.schedule;if(!l)return;const o=r[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(h=>{const m=h.interstitial,x=l.findEventIndex(m.identifier);(xt+1)&&this.clearInterstitial(m,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(n===void 0){n=l.findAssetIndex(h,this.timelinePos);const v=Zbe(h,n-1);if(h.isAssetPastPlayoutLimit(v)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,t,n);return}n=v}const m=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let x=this.preloadAssets(h,n);if(this.eventItemsMatch(o,m||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${ey(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(ht.INTERSTITIAL_STARTED,{event:h,schedule:r.slice(0),scheduleIndex:t})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const y=h.assetList[n];if(!y){this.advanceAfterAssetEnded(h,t,n||0);return}if(x||(x=this.getAssetPlayer(y.identifier)),x===null||x.destroyed){const v=h.assetList.length;this.warn(`asset ${n+1}/${v} player destroyed ${h}`),x=this.createAssetPlayer(h,y,n),x.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(y))return;this.startAssetPlayer(x,n,r,t,c),this.shouldPlay&&FHe(x.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&FHe(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,r,n){var a,i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${ey(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,r),this.log(gE("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,t)}if(!n)return;const l=(i=this.schedule)==null?void 0:i.items;l&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${ey(t)}`),this.hls.trigger(ht.INTERSTITIALS_PRIMARY_RESUMED,{schedule:l.slice(0),scheduleIndex:r}),this.checkBuffer())}getPrimaryResumption(t,r){const n=t.start;if(this.primaryLive){const a=this.primaryDetails;if(r===0)return this.hls.startPosition;if(a&&(na.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(t){const r=this.getAssetPlayer(t.identifier);return r!=null&&r.hls?r.hls.bufferedToEnd:Ai.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,r,n){r?this.setBufferingItem(r):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),n&&this.startLoadingPrimaryAt(t,n)),n||(this.log(gE("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,n))}startLoadingPrimaryAt(t,r){var n;const a=this.hls;!a.loadingEnabled||!a.media||Math.abs((((n=a.mainForwardBufferInfo)==null?void 0:n.start)||a.media.currentTime)-t)>.5?a.startLoad(t,r):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(ht.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ht.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,r){if(r.level===-1||!this.schedule)return;const n=this.hls.levels[r.level];if(!n.details)return;const a=Sl(Sl({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=a,this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,r){const n=this.hls.audioTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=Sl(Sl({},this.altSelection),{},{audio:n});return}const i=Sl(Sl({},a),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(t,r){const n=this.hls.subtitleTracks[r.id],a=this.mediaSelection;if(!a){this.altSelection=Sl(Sl({},this.altSelection),{},{subtitles:n});return}const i=Sl(Sl({},a),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(t,r){const n=WVe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(r)||a.setAudioOption(n)))}onSubtitleTrackSwitch(t,r){const n=WVe(r);this.playerQueue.forEach(({hls:a})=>a&&(a.setSubtitleOption(r)||r.id!==-1&&a.setSubtitleOption(n)))}onBufferCodecs(t,r){const n=r.tracks;n&&(this.requiredTracks=n)}onBufferAppended(t,r){this.checkBuffer()}onBufferFlushed(t,r){const n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){const a=this.timelinePos;this.bufferedPos=a,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const r=this.schedule.events;if(this.bufferedPos.25){t.event.assetList.forEach((i,l)=>{t.event.isAssetPastPlayoutLimit(l)&&this.clearAssetPlayer(i.identifier,null)});const n=t.end+.25,a=Ai.bufferInfo(this.primaryMedia,n,0);(a.end>n||(a.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${ey(t)} (was ${ey(r)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(t,r){return!!r&&(t===r||t.event&&r.event&&this.eventItemsMatch(t,r)||!t.event&&!r.event&&this.findItemIndex(t)===this.findItemIndex(r))}eventItemsMatch(t,r){var n;return!!r&&(t===r||t.event.identifier===((n=r.event)==null?void 0:n.identifier))}findItemIndex(t,r){return t&&this.schedule?this.schedule.findItemIndex(t,r):-1}updateSchedule(t=!1){var r;const n=this.mediaSelection;n&&((r=this.schedule)==null||r.updateSchedule(n,[],t))}checkBuffer(t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n)return;const a=Ai.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,n,t)}updateBufferedPos(t,r,n){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(r.length===1&&this.itemsMatch(r[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=x.event)!=null&&d.appendInPlace&&t+.01>=x.start)&&(c=m),this.isInterstitial(i)){const y=i.event;if(m-o>1&&y.appendInPlace===!1||y.assetList.length===0&&y.assetListLoader)return}if(this.bufferedPos=t,c>h&&c>o)this.bufferedToItem(x);else{const y=this.primaryDetails;this.primaryLive&&y&&t>y.edge-y.targetduration&&x.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(r))})}setBufferingItem(t){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(t,r)&&n){const{items:a,events:i}=n;if(!a||!i)return r;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:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${ey(t)}`+(r?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=n.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((h,m)=>{const x=this.getAssetPlayer(h.identifier);x&&(m===d&&x.loadSource(),x.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(ht.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 r}bufferedToItem(t,r=0){const n=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,r);else if(n!==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 r=this.findItemIndex(t),n=this.getPrimaryResumption(t,r);this.startLoadingPrimaryAt(n)}bufferedToEvent(t,r){const n=t.event,a=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(a||!i){const l=this.preloadAssets(n,r);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,r){const n=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 x=this.playingItem;!this.isInterstitial(x)&&(x==null||(o=x.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let d,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(t.cue.pre||t.cue.post)){const x=h-c;x>0&&(d=Math.round(x*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:a} ${t}${d?` live-start: ${h} start-offset: ${d}`:""}`),n)return this.createAsset(t,0,0,c,t.duration,n);const m=this.assetListLoader.loadAssetList(t,d);m&&(t.assetListLoader=m)}else if(!l&&a){for(let d=r;d{this.hls.trigger(ht.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const r=this.playerQueue;for(let n=0;n1){const I=r.duration;I&&A{if(A.live){var I;const $=new Error(`Interstitials MUST be VOD assets ${t}`),F={fatal:!0,type:La.OTHER_ERROR,details:ar.INTERSTITIAL_ASSET_ITEM_ERROR,error:$},z=((I=this.schedule)==null?void 0:I.findEventIndex(t.identifier))||-1;this.handleAssetItemError(F,t,z,n,$.message);return}const D=A.edge-A.fragmentStart,R=r.duration;(w||R===null||D>R)&&(w=!1,this.log(`Interstitial asset "${m}" duration change ${R} > ${D}`),r.duration=D,this.updateSchedule())};v.on(ht.LEVEL_UPDATED,(A,{details:I})=>b(I)),v.on(ht.LEVEL_PTS_UPDATED,(A,{details:I})=>b(I)),v.on(ht.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const N=(A,I)=>{const D=this.getAssetPlayer(m);if(D&&I.tracks){D.off(ht.BUFFER_CODECS,N),D.tracks=I.tracks;const R=this.primaryMedia;this.bufferingAsset===D.assetItem&&R&&!D.media&&this.bufferAssetPlayer(D,R)}};v.on(ht.BUFFER_CODECS,N);const S=()=>{var A;const I=this.getAssetPlayer(m);if(this.log(`buffered to end of asset ${I}`),!I||!this.schedule)return;const D=this.schedule.findEventIndex(t.identifier),R=(A=this.schedule.items)==null?void 0:A[D];this.isInterstitial(R)&&this.advanceAssetBuffering(R,r)};v.on(ht.BUFFERED_TO_END,S);const T=A=>()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,D,A)};return v.once(ht.MEDIA_ENDED,T(n)),v.once(ht.PLAYOUT_LIMIT_REACHED,T(1/0)),v.on(ht.ERROR,(A,I)=>{if(!this.schedule)return;const D=this.getAssetPlayer(m);if(I.details===ar.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(I,t,this.schedule.findEventIndex(t.identifier),n,`Asset player error ${I.error} ${t}`)}),v.on(ht.DESTROYING,()=>{if(!this.getAssetPlayer(m)||!this.schedule)return;const I=new Error(`Asset player destroyed unexpectedly ${m}`),D={fatal:!0,type:La.OTHER_ERROR,details:ar.INTERSTITIAL_ASSET_ITEM_ERROR,error:I};this.handleAssetItemError(D,t,this.schedule.findEventIndex(t.identifier),n,I.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${CE(r)}`),this.hls.trigger(ht.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:t,player:v}),v}clearInterstitial(t,r){this.clearAssetPlayers(t,r),t.reset()}clearAssetPlayers(t,r){t.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,r)})}resetAssetPlayer(t){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){this.log(`reset asset player "${t}" after error`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(t,r){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){const a=this.playerQueue[n];this.log(`clear ${a} toSegment: ${r&&ey(r)}`),this.transferMediaFromPlayer(a,r),this.playerQueue.splice(n,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,r,n,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,n[a]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${d} ${CE(o)}`),this.hls.trigger(ht.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:r,event:l,schedule:n.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,r){var n,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(n=this.schedule.items)==null?void 0:n[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const h=i.appendInPlace;if(h&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const m=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(h&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(m&&!Dxt(m,t.tracks)){const x=new Error(`Asset ${CE(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(m)}')`),y={fatal:!0,type:La.OTHER_ERROR,details:ar.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},v=i.findAssetIndex(l);this.handleAssetItemError(y,i,o,v,x.message);return}}this.transferMediaTo(t,r)}handleInPlaceStall(t){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const a=n.currentTime,i=r.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/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){const h=r.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,h,i)}}}}advanceInPlace(t){const r=this.primaryMedia;r&&r.currentTime!w.error))r.error=v;else for(let w=a;w{const N=parseFloat(w.DURATION);this.createAsset(i,b,h,c+h,N,w.URI),h+=N}),i.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${d}) ${i}`);const m=this.waitingItem,x=(m==null?void 0:m.event.identifier)===l;this.updateSchedule();const y=(a=this.bufferingItem)==null?void 0:a.event;if(x){var v;const w=this.schedule.findEventIndex(l),b=(v=this.schedule.items)==null?void 0:v[w];if(b){if(!this.playingItem&&this.timelinePos>b.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==w){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(b)}this.setSchedulePosition(w)}else if((y==null?void 0:y.identifier)===l){const w=i.assetList[0];if(w){const b=this.getAssetPlayer(w.identifier);if(y.appendInPlace){const N=this.primaryMedia;b&&N&&this.bufferAssetPlayer(b,N)}else b&&b.loadSource()}}}onError(t,r){if(this.schedule)switch(r.details){case ar.ASSET_LIST_PARSING_ERROR:case ar.ASSET_LIST_LOAD_ERROR:case ar.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case ar.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const BHe=500;class Rzs extends lAe{constructor(t,r,n){super(t,r,n,"subtitle-stream-controller",ua.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(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ht.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ht.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(ht.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(ht.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(ht.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ht.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(ht.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(ht.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(ht.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(ht.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,r){this.stopLoad(),this.state=Or.IDLE,this.setInterval(BHe),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,r){this.tracksBuffered=[],super.onMediaDetaching(t,r)}onLevelLoaded(t,r){this.mainDetails=r.details}onSubtitleFragProcessed(t,r){const{frag:n,success:a}=r;if(this.fragContextChanged(n)||(Yd(n)&&(this.fragPrevious=n),this.state=Or.IDLE),!a)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let l;const o=n.start;for(let d=0;d=i[d].start&&o<=i[d].end){l=i[d];break}const c=n.start+n.duration;l?l.end=c:(l={start:o,end:c},i.push(l)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(t,r){const{startOffset:n,endOffset:a}=r;if(n===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;r.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{for(let o=0;onew kF(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const a=new kF(n);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ua.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.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!==Or.STOPPED&&this.setInterval(BHe)}onSubtitleTrackLoaded(t,r){var n;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=r;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||(n=c.details)!=null&&n.live){if(l.deltaUpdateFailed)return;const m=this.mainDetails;if(!m){this.startFragRequested=!1;return}const x=m.fragments[0];if(!c.details)l.hasProgramDateTime&&m.hasProgramDateTime?(mme(l,m),d=l.fragmentStart):x&&(d=x.start,Kke(l,d));else{var h;d=this.alignPlaylists(l,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),d===0&&x&&(d=x.start,Kke(l,d))}m&&!this.startFragRequested&&this.setStartPosition(m,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(ht.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:r.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===Or.IDLE&&(e5(null,l.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:r,payload:n}=t,a=r.decryptdata,i=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&a!=null&&a.key&&a.iv&&QA(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,iAe(a.method)).catch(o=>{throw i.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const c=performance.now();i.trigger(ht.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Or.IDLE})}}doTick(){if(!this.media){this.state=Or.IDLE;return}if(this.state===Or.IDLE){const{currentTrackId:t,levels:r}=this,n=r==null?void 0:r[t];if(!n||!r.length||!n.details||this.waitForLive(n))return;const{config:a}=this,i=this.getLoadPosition(),l=Ai.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=n.details,h=this.hls.maxBufferLength+d.levelTargetDuration;if(c>h)return;const m=d.fragments,x=m.length,y=d.edge;let v=null;const w=this.fragPrevious;if(oy-S?0:S;v=e5(w,m,Math.max(m[0].start,o),T),!v&&w&&w.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][n]};this.buffered={get length(){return t.length},end(n){return r("end",n,t.length)},start(n){return r("start",n,t.length)}}}}const Fzs={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},eyt=s=>String.fromCharCode(Fzs[s]||s),ny=15,D1=100,Bzs={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},zzs={17:2,18:4,21:6,22:8,23:10,19:13,20:15},$zs={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Uzs={25:2,26:4,29:6,30:8,31:10,27:13,28:15},qzs=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Vzs{constructor(){this.time=null,this.verboseLevel=0}log(t,r){if(this.verboseLevel>=t){const n=typeof r=="function"?r():r;Al.log(`${this.time} [${t}] ${n}`)}}}const TN=function(t){const r=[];for(let n=0;nD1&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=D1)}moveCursor(t){const r=this.pos+t;if(t>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=eyt(t);if(this.pos>=D1){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(t){let r;for(r=t;r"pacData = "+Ql(t));let r=t.row-1;if(this.nrRollUpRows&&r"bkgData = "+Ql(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,r=this.rows.splice(t,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const r=[];let n="",a=-1;for(let i=0;i0&&(t?n="["+r.join(" | ")+"]":n=r.join(` `)),n}getTextAndFormat(){return this.rows}}class zHe{constructor(t,r,n){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=r,this.mode=null,this.verbose=0,this.displayedMemory=new Xbe(n),this.nonDisplayedMemory=new Xbe(n),this.lastOutputScreen=new Xbe(n),this.currRollUpRow=this.displayedMemory.rows[ny-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[ny-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 n=0;nr+": "+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 r={flash:!1};if(r.underline=t%2===1,r.italics=t>=46,r.italics)r.foreground="white";else{const n=Math.floor(t/2)-16,a=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=a[n]}this.logger.log(2,"MIDROW: "+Ql(r)),this.writeScreen.setPen(r)}outputDataUpdate(t=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),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 $He{constructor(t,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Kzs(),this.logger=void 0;const a=this.logger=new Vzs;this.channels=[null,new zHe(t,r,a),new zHe(t+1,n,a)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,r){this.channels[t].setHandler(r)}addData(t,r){this.logger.time=t;for(let n=0;n"["+TN([r[n],r[n+1]])+"] -> ("+TN([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(Wzs(a,i,c)){lU(null,null,c),this.logger.log(3,()=>"Repeated command ("+TN([a,i])+") is dropped");continue}lU(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 lU(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+TN([a,i])+" orig: "+TN([r[n],r[n+1]]))}}parseCmd(t,r){const n=(t===20||t===28||t===21||t===29)&&r>=32&&r<=47,a=(t===23||t===31)&&r>=33&&r<=35;if(!(n||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?r===32?l.ccRCL():r===33?l.ccBS():r===34?l.ccAOF():r===35?l.ccAON():r===36?l.ccDER():r===37?l.ccRU(2):r===38?l.ccRU(3):r===39?l.ccRU(4):r===40?l.ccFON():r===41?l.ccRDC():r===42?l.ccTR():r===43?l.ccRTD():r===44?l.ccEDM():r===45?l.ccCR():r===46?l.ccENM():r===47&&l.ccEOC():l.ccTO(r-32),this.currentChannel=i,!0}parseMidrow(t,r){let n=0;if((t===17||t===25)&&r>=32&&r<=47){if(t===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[n];return a?(a.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+TN([t,r])+")"),!0):!1}return!1}parsePAC(t,r){let n;const a=(t>=17&&t<=23||t>=25&&t<=31)&&r>=64&&r<=127,i=(t===16||t===24)&&r>=64&&r<=95;if(!(a||i))return!1;const l=t<=23?1:2;r>=64&&r<=95?n=l===1?Bzs[t]:$zs[t]:n=l===1?zzs[t]:Uzs[t];const o=this.channels[l];return o?(o.setPAC(this.interpretPAC(n,r)),this.currentChannel=l,!0):!1}interpretPAC(t,r){let n;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return r>95?n=r-96:n=r-64,a.underline=(n&1)===1,n<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((n-16)/2)*4,a}parseChars(t,r){let n,a=null,i=null;if(t>=25?(n=2,i=t-8):(n=1,i=t),i>=17&&i<=19){let l;i===17?l=r+80:i===18?l=r+112:l=r+144,this.logger.log(2,()=>"Special char '"+eyt(l)+"' in channel "+n),a=[l]}else t>=32&&t<=127&&(a=r===0?[t]:[t,r]);return a&&this.logger.log(3,()=>"Char codes = "+TN(a).join(",")),a}parseBackgroundAttributes(t,r){const n=(t===16||t===24)&&r>=32&&r<=47,a=(t===23||t===31)&&r>=45&&r<=47;if(!(n||a))return!1;let i;const l={};t===16||t===24?(i=Math.floor((r-32)/2),l.background=qzs[i],r%2===1&&(l.background=l.background+"_semi")):r===45?l.background="transparent":(l.foreground="black",r===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.");D=z,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",i({},m,{get:function(){return R},set:function(z){const Q=a(z);if(!Q)throw new SyntaxError("An invalid or illegal string was specified.");R=Q,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",i({},m,{get:function(){return $},set:function(z){if(z<0||z>100)throw new Error("Size must be between 0 and 100.");$=z,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",i({},m,{get:function(){return F},set:function(z){const Q=a(z);if(!Q)throw new SyntaxError("An invalid or illegal string was specified.");F=Q,this.hasBeenReset=!0}})),h.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class Yzs{decode(t,r){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function syt(s){function t(n,a,i,l){return(n|0)*3600+(a|0)*60+(i|0)+parseFloat(l||0)}const r=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}class Zzs{constructor(){this.values=Object.create(null)}set(t,r){!this.get(t)&&r!==""&&(this.values[t]=r)}get(t,r,n){return n?this.has(t)?this.values[t]:r[n]:this.has(t)?this.values[t]:r}has(t){return t in this.values}alt(t,r,n){for(let a=0;a=0&&n<=100)return this.set(t,n),!0}return!1}}function ryt(s,t,r,n){const a=n?s.split(n):[s];for(const i in a){if(typeof a[i]!="string")continue;const l=a[i].split(r);if(l.length!==2)continue;const o=l[0],c=l[1];t(o,c)}}const sSe=new bAe(0,0,""),cU=sSe.align==="middle"?"middle":"center";function Xzs(s,t,r){const n=s;function a(){const o=syt(s);if(o===null)throw new Error("Malformed timestamp: "+n);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,c){const d=new Zzs;ryt(o,function(x,y){let v;switch(x){case"region":for(let w=r.length-1;w>=0;w--)if(r[w].id===y){d.set(x,r[w].region);break}break;case"vertical":d.alt(x,y,["rl","lr"]);break;case"line":v=y.split(","),d.integer(x,v[0]),d.percent(x,v[0])&&d.set("snapToLines",!1),d.alt(x,v[0],["auto"]),v.length===2&&d.alt("lineAlign",v[1],["start",cU,"end"]);break;case"position":v=y.split(","),d.percent(x,v[0]),v.length===2&&d.alt("positionAlign",v[1],["start",cU,"end","line-left","line-right","auto"]);break;case"size":d.percent(x,y);break;case"align":d.alt(x,y,["start",cU,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let h=d.get("line","auto");h==="auto"&&sSe.line===-1&&(h=-1),c.line=h,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",cU);let m=d.get("position","auto");m==="auto"&&sSe.position===50&&(m=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=m}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 '-->'): "+n);s=s.slice(3),l(),t.endTime=a(),l(),i(s,t)}function nyt(s){return s.replace(//gi,` `)}class Qzs{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Yzs,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const r=this;t&&(r.buffer+=r.decoder.decode(t,{stream:!0}));function n(){let i=r.buffer,l=0;for(i=nyt(i);l")===-1){r.cue.id=i;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{Xzs(i,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` `),r.cue.text+=i}continue;case"BADCUE":i||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.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(r){t.onparsingerror&&t.onparsingerror(r)}return t.onflush&&t.onflush(),this}}const Jzs=/\r\n|\n\r|\n|\r/g,Qbe=function(t,r,n=0){return t.slice(n,n+r.length)===r},e7s=function(t){let r=parseInt(t.slice(-3));const n=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!Zn(r)||!Zn(n)||!Zn(a)||!Zn(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return r+=1e3*n,r+=60*1e3*a,r+=60*60*1e3*i,r};function _Ae(s,t,r){return BO(s.toString())+BO(t.toString())+BO(r)}const t7s=function(t,r,n){let a=t[r],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=n};function s7s(s,t,r,n,a,i,l){const o=new Qzs,c=ex(new Uint8Array(s)).trim().replace(Jzs,` `).split(` `),d=[],h=t?lBs(t.baseTime,t.timescale):0;let m="00:00.000",x=0,y=0,v,w=!0;o.oncue=function(b){const N=r[n];let S=r.ccOffset;const T=(x-h)/9e4;if(N!=null&&N.new&&(y!==void 0?S=r.ccOffset=N.start:t7s(r,n,T)),T){if(!t){v=new Error("Missing initPTS for VTT MPEGTS");return}S=T-r.presentationOffset}const A=b.endTime-b.startTime,I=Ep((b.startTime+S-y)*9e4,a*9e4)/9e4;b.startTime=Math.max(I,0),b.endTime=Math.max(I+A,0);const D=b.text.trim();b.text=decodeURIComponent(encodeURIComponent(D)),b.id||(b.id=_Ae(b.startTime,b.endTime,D)),b.endTime>0&&d.push(b)},o.onparsingerror=function(b){v=b},o.onflush=function(){if(v){l(v);return}i(d)},c.forEach(b=>{if(w)if(Qbe(b,"X-TIMESTAMP-MAP=")){w=!1,b.slice(16).split(",").forEach(N=>{Qbe(N,"LOCAL:")?m=N.slice(6):Qbe(N,"MPEGTS:")&&(x=parseInt(N.slice(7)))});try{y=e7s(m)/1e3}catch(N){v=N}return}else b===""&&(w=!1);o.parse(b+` `)}),o.flush()}const Jbe="stpp.ttml.im1t",ayt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,iyt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,r7s={left:"start",center:"center",right:"end",start:"start",end:"end"};function UHe(s,t,r,n){const a=so(new Uint8Array(s),["mdat"]);if(a.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>ex(o)),l=oBs(t.baseTime,1,t.timescale);try{i.forEach(o=>r(n7s(o,l)))}catch(o){n(o)}}function n7s(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((m,x)=>(m[x]=a.getAttribute(`ttp:${x}`)||i[x],m),{}),o=a.getAttribute("xml:space")!=="preserve",c=qHe(e_e(a,"styling","style")),d=qHe(e_e(a,"layout","region")),h=e_e(a,"body","[begin]");return[].map.call(h,m=>{const x=oyt(m,o);if(!x||!m.hasAttribute("begin"))return null;const y=s_e(m.getAttribute("begin"),l),v=s_e(m.getAttribute("dur"),l);let w=s_e(m.getAttribute("end"),l);if(y===null)throw VHe(m);if(w===null){if(v===null)throw VHe(m);w=y+v}const b=new bAe(y-t,w-t,x);b.id=_Ae(b.startTime,b.endTime,b.text);const N=d[m.getAttribute("region")],S=c[m.getAttribute("style")],T=a7s(N,S,c),{textAlign:A}=T;if(A){const I=r7s[A];I&&(b.lineAlign=I),b.align=A}return zl(b,T),b}).filter(m=>m!==null)}function e_e(s,t,r){const n=s.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function qHe(s){return s.reduce((t,r)=>{const n=r.getAttribute("xml:id");return n&&(t[n]=r),t},{})}function oyt(s,t){return[].slice.call(s.childNodes).reduce((r,n,a)=>{var i;return n.nodeName==="br"&&a?r+` `:(i=n.childNodes)!=null&&i.length?oyt(n,t):t?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function a7s(s,t,r){const n="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&&r.hasOwnProperty(l)&&(a=r[l]),i.reduce((o,c)=>{const d=t_e(t,n,c)||t_e(s,n,c)||t_e(a,n,c);return d&&(o[c]=d),o},{})}function t_e(s,t,r){return s&&s.hasAttributeNS(t,r)?s.getAttributeNS(t,r):null}function VHe(s){return new Error(`Could not parse ttml timestamp ${s}`)}function s_e(s,t){if(!s)return null;let r=syt(s);return r===null&&(ayt.test(s)?r=i7s(s,t):iyt.test(s)&&(r=o7s(s,t))),r}function i7s(s,t){const r=ayt.exec(s),n=(r[4]|0)+(r[5]|0)/t.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/t.frameRate}function o7s(s,t){const r=iyt.exec(s),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}class dU{constructor(t,r){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=r}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,r,n){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class l7s{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=GHe(),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(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ht.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ht.FRAG_LOADING,this.onFragLoading,this),t.on(ht.FRAG_LOADED,this.onFragLoaded,this),t.on(ht.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ht.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ht.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ht.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ht.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ht.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(ht.FRAG_LOADING,this.onFragLoading,this),t.off(ht.FRAG_LOADED,this.onFragLoaded,this),t.off(ht.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(ht.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(ht.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ht.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new dU(this,"textTrack1"),r=new dU(this,"textTrack2"),n=new dU(this,"textTrack3"),a=new dU(this,"textTrack4");this.cea608Parser1=new $He(1,t,r),this.cea608Parser2=new $He(3,n,a)}addCues(t,r,n,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=c7s(c[0],c[1],r,n);if(d>=0&&(c[0]=Math.min(c[0],r),c[1]=Math.max(c[1],n),l=!0,d/(n-r)>.5))return}if(l||i.push([r,n]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,r,n,a)}else{const o=this.Cues.newCue(null,r,n,a);this.hls.trigger(ht.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:r,id:n,initPTS:a,timescale:i,trackId:l}){const{unparsedVttFrags:o}=this;n===ua.MAIN&&(this.initPTS[r.cc]={baseTime:a,timescale:i,trackId:l}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(ht.FRAG_LOADED,c):this.hls.trigger(ht.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,r){const{media:n}=this;if(n)for(let a=0;a{eA(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=GHe(),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 r=t.textTracks;if(r)for(let n=0;ni.textCodec===Jbe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(Fgt(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const l=this.media,o=l?Dce(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let h;if(o){let m=null;for(let x=0;xd!==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(ht.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}onManifestLoaded(t,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const a=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=n.name,n.lang&&(l.languageCode=n.lang),l.media=n)})}closedCaptionsForLevel(t){const r=this.hls.levels[t.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,r){if(this.enabled&&r.frag.type===ua.MAIN){var n,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=r.frag,h=(n=(a=r.part)==null?void 0:a.index)!=null?n:-1;i&&l&&(d!==o+1||d===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=h}}onFragLoaded(t,r){const{frag:n,payload:a}=r;if(n.type===ua.SUBTITLE)if(a.byteLength){const i=n.decryptdata,l="stats"in r;if(i==null||!i.encrypted||l){const o=this.tracks[n.level],c=this.vttCCs;c[n.cc]||(c[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),o&&o.textCodec===Jbe?this._parseIMSC1(n,a):this._parseVTTs(r)}}else this.hls.trigger(ht.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,r){const n=this.hls;UHe(r,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),n.trigger(ht.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{n.logger.log(`Failed to parse IMSC1: ${a}`),n.trigger(ht.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:a})})}_parseVTTs(t){var r;const{frag:n,payload:a}=t,{initPTS:i,unparsedVttFrags:l}=this,o=i.length-1;if(!i[n.cc]&&o===-1){l.push(t);return}const c=this.hls,d=(r=n.initSegment)!=null&&r.data?gg(n.initSegment.data,new Uint8Array(a)).buffer:a;s7s(d,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,h=>{this._appendCues(h,n.level),c.trigger(ht.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},h=>{const m=h.message==="Missing initPTS for VTT MPEGTS";m?l.push(t):this._fallbackToIMSC1(n,a),c.logger.log(`Failed to parse VTT cue: ${h}`),!(m&&o>n.cc)&&c.trigger(ht.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:h})})}_fallbackToIMSC1(t,r){const n=this.tracks[t.level];n.textCodec||UHe(r,this.initPTS[t.cc],()=>{n.textCodec=Jbe,this._parseIMSC1(t,r)},()=>{n.textCodec="wvtt"})}_appendCues(t,r){const n=this.hls;if(this.config.renderTextTracksNatively){const a=this.textTracks[r];if(!a||a.mode==="disabled")return;t.forEach(i=>Qgt(a,i))}else{const a=this.tracks[r];if(!a)return;const i=a.default?"default":"subtitles"+r;n.trigger(ht.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,r){const{frag:n}=r;n.type===ua.SUBTITLE&&this.onFragLoaded(ht.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,r){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:n,samples:a}=r;if(!(n.type===ua.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let i=0;itSe(o[c],r,n))}if(this.config.renderTextTracksNatively&&r===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>tSe(o[c],r,a))}}}extractCea608Data(t){const r=[[],[]],n=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const y=nyt(d.trim()),v=_Ae(t,r,y);s!=null&&(m=s.cues)!=null&&m.getCueById(v)||(l=new h(t,r,y),l.id=v,l.line=x+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((x,y)=>x.line==="auto"||y.line==="auto"?0:x.line>8&&y.line>8?y.line-x.line:x.line-y.line),a.forEach(x=>Qgt(s,x))),a}};function h7s(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const m7s=/(\d+)-(\d+)\/(\d+)/;class WHe{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||g7s,this.controller=new self.AbortController,this.stats=new JEe}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,r,n){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=f7s(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=r.loadPolicy;this.context=t,this.config=r,this.callbacks=n,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),r.timeout=c&&Zn(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},r.timeout),(TF(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(m=>{var x;this.response=this.loader=m;const y=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(y-a.loading.start)),!m.ok){const{status:w,statusText:b}=m;throw new y7s(b||"fetch, bad network response",w,m)}a.loading.first=y,a.total=x7s(m.headers)||a.total;const v=(x=this.callbacks)==null?void 0:x.onProgress;return v&&Zn(r.highWaterMark)?this.loadProgressively(m,a,t,r.highWaterMark,v):l?m.arrayBuffer():t.responseType==="json"?m.json():m.text()}).then(m=>{var x,y;const v=this.response;if(!v)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const w=m[o];w&&(a.loaded=a.total=w);const b={url:v.url,data:m,code:v.status},N=(x=this.callbacks)==null?void 0:x.onProgress;N&&!Zn(r.highWaterMark)&&N(a,t,m,v),(y=this.callbacks)==null||y.onSuccess(b,a,t,v)}).catch(m=>{var x;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const y=m&&m.code||0,v=m?m.message:null;(x=this.callbacks)==null||x.onError({code:y,text:v},t,m?m.details:null,a)})}getCacheAge(){let t=null;if(this.response){const r=this.response.headers.get("age");t=r?parseFloat(r):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,r,n,a=0,i){const l=new ygt,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(r,n,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const h=d.value,m=h.length;return r.loaded+=m,m=a&&i(r,n,l.flush().buffer,t)):i(r,n,h.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function f7s(s,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(zl({},s.headers))};return s.rangeEnd&&r.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),r}function p7s(s){const t=m7s.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function x7s(s){const t=s.get("Content-Range");if(t){const n=p7s(t);if(Zn(n))return n}const r=s.get("Content-Length");if(r)return parseInt(r)}function g7s(s,t){return new self.Request(s.url,t)}class y7s extends Error{constructor(t,r,n){super(t),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const v7s=/^age:\s*[\d.]+\s*$/im;class cyt{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 JEe,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,r,n){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=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:t,context:r}=this;if(!t||!r)return;const n=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!==n||this.stats.aborted))return i(n,r.url)}).catch(l=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),i(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:n.status,text:l.message},r,n,a)}):this.openAndSendXhr(n,r,t)}openAndSendXhr(t,r,n){t.readyState||t.open("GET",r.url,!0);const a=r.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=n.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);r.rangeEnd&&t.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&Zn(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),t.send()}readystatechange(){const{context:t,loader:r,stats:n}=this;if(!t||!r)return;const a=r.readyState,i=this.config;if(!n.aborted&&a>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.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-(n.loading.first-n.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const d=r.status,h=r.responseType==="text"?r.responseText:null;if(d>=200&&d<300){const v=h??r.response;if(v!=null){var l,o;n.loading.end=Math.max(self.performance.now(),n.loading.first);const w=r.responseType==="arraybuffer"?v.byteLength:v.length;n.loaded=n.total=w,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const b=(l=this.callbacks)==null?void 0:l.onProgress;b&&b(n,t,v,r);const N={url:r.responseURL,data:v,code:d};(o=this.callbacks)==null||o.onSuccess(N,n,t,r);return}}const m=i.loadPolicy.errorRetry,x=n.retry,y={url:t.url,data:void 0,code:d};if(dme(m,x,!1,y))this.retry(m);else{var c;Al.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:r.statusText},t,r,n)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(dme(t,r,!0))this.retry(t);else{var n;Al.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:r,stats:n}=this;this.retryDelay=rAe(t,n.retry),n.retry++,Al.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.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 r=this.stats;r.loaded=t.loaded,t.lengthComputable&&(r.total=t.total)}getCacheAge(){let t=null;if(this.loader&&v7s.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");t=r?parseFloat(r):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 b7s={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},_7s=Sl(Sl({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:cyt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:L8s,bufferController:jBs,capLevelController:gAe,errorController:F8s,fpsController:Nzs,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:ogt,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:b7s},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},w7s()),{},{subtitleStreamController:Rzs,subtitleTrackController:Czs,timelineController:l7s,audioStreamController:vBs,audioTrackController:bBs,emeController:JA,cmcdController:bzs,contentSteeringController:wzs,interstitialsController:Dzs});function w7s(){return{cueHandler:u7s,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 j7s(s,t,r){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 n=rSe(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(h=>{const m=`${l}Loading${h}`,x=t[m];if(x!==void 0&&c){d.push(m);const y=n[o].default;switch(t[o]={default:y},h){case"TimeOut":y.maxLoadTimeMs=x,y.maxTimeToFirstByteMs=x;break;case"MaxRetry":y.errorRetry.maxNumRetry=x,y.timeoutRetry.maxNumRetry=x;break;case"RetryDelay":y.errorRetry.retryDelayMs=x,y.timeoutRetry.retryDelayMs=x;break;case"MaxRetryTimeout":y.errorRetry.maxRetryDelayMs=x,y.timeoutRetry.maxRetryDelayMs=x;break}}}),d.length&&r.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Ql(t[o])}`)}),Sl(Sl({},n),t)}function rSe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(rSe):Object.keys(s).reduce((t,r)=>(t[r]=rSe(s[r]),t),{}):s}function N7s(s,t){const r=s.loader;r!==WHe&&r!==cyt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):h7s()&&(s.loader=WHe,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const Rce=2,k7s=.1,S7s=.05,C7s=100;class T7s extends sgt{constructor(t,r){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 n;(n=this.media)!=null&&n.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(ht.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,r){this.setInterval(C7s),this.mediaSource=r.mediaSource;const n=this.media=r.media;ff(n,"playing",this.onMediaPlaying),ff(n,"waiting",this.onMediaWaiting),ff(n,"ended",this.onMediaEnded)}onMediaDetaching(t,r){this.clearInterval();const{media:n}=this;n&&(Wf(n,"playing",this.onMediaPlaying),Wf(n,"waiting",this.onMediaWaiting),Wf(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,r){this.buffered=r.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const r=this.media.currentTime;this.poll(r,this.lastCurrentTime),this.lastCurrentTime=r}poll(t,r){var n,a;const i=(n=this.hls)==null?void 0:n.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,h=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==r){r&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!h&&t>r&&this.nudgeOnVideoHole(t,r)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(h){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(ht.MEDIA_ENDED,{stalled:!1}));return}if(!Ai.getBuffered(l).length){this.nudgeRetry=0;return}const m=Ai.bufferInfo(l,t,0),x=m.nextStart||0,y=this.fragmentTracker;if(o&&y&&this.hls){const D=KHe(this.hls.inFlightFragments,t),R=m.len>Rce,$=!x||D||x-t>Rce&&!y.getPartialFragment(t);if(R||$)return;this.moved=!1}const v=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&y){if(!(m.len>0)&&!x)return;const R=Math.max(x,m.start||0)-t,F=!!(v!=null&&v.live)?v.targetduration*2:Rce,z=uU(t,y);if(R>0&&(R<=F||z)){l.paused||this._trySkipBufferHole(z);return}}const w=i.detectStallWithCurrentTimeMs,b=self.performance.now(),N=this.waiting;let S=this.stalled;if(S===null)if(N>0&&b-N=w||N)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(v!=null&&v.live)&&Math.abs(t-((v==null?void 0:v.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(ht.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(m),!this.media||!this.hls)return}const I=Ai.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(I,T,t)}stallResolved(t){const r=this.stalled;if(r&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-r;this.log(`playback not stuck anymore @${t}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(ht.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,r){var n;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&a&&a.length>1&&t>a.end(0)){const i=Ai.bufferedInfo(Ai.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&r>=i.start){const l=Ai.timeRangesToArray(a),o=Ai.bufferedInfo(l,r,0).bufferedIndex;if(o>-1&&oo)&&h-d<1&&t-d<2){const m=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${h} buffered index: ${c}`);this.warn(m.message),this.media.currentTime+=1e-6;let x=uU(t,this.fragmentTracker);x&&"fragment"in x?x=x.fragment:x||(x=void 0);const y=Ai.bufferInfo(this.media,t,0);this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,frag:x,buffer:y.len,bufferInfo:y})}}}}}_tryFixBufferStall(t,r,n){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,h=uU(n,l);if((h||d!=null&&d.live&&n1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-nc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,r){const n=this.fragmentTracker,a=t.nextStart;if(n&&a){const i=n.getFragAtPos(r,ua.MAIN),l=n.getFragAtPos(a,ua.MAIN);if(i&&l)return l.sn-i.sn<2}return!1}_reportStall(t){const{hls:r,media:n,stallReported:a,stalled:i}=this;if(!a&&i!==null&&n&&r){this.stallReported=!0;const l=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${Ql(t)})`);this.warn(l.message),r.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){var r;const{fragmentTracker:n,media:a}=this,i=(r=this.hls)==null?void 0:r.config;if(!a||!n||!i)return 0;const l=a.currentTime,o=Ai.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,x=c-l;if(x>0&&(h||m)){if(x>i.maxBufferHole){let v=!1;if(l===0){const w=n.getAppendedFrag(0,ua.MAIN);w&&c"u"))return self.VTTCue||self.TextTrackCue}function r_e(s,t,r,n,a){let i=new s(t,r,"");try{i.value=n,a&&(i.type=a)}catch{i=new s(t,r,Ql(a?Sl({type:a},n):n))}return i}const hU=(()=>{const s=nSe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class A7s{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(ht.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(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ht.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(ht.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(ht.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ht.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,r){var n;this.media=r.media,((n=r.overrides)==null?void 0:n.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const r=(t=this.hls)==null?void 0:t.latestLevelDetails;r&&this.updateDateRangeCues(r)}onMediaDetaching(t,r){this.media=null,!r.transferMedia&&(this.id3Track&&(this.removeCues&&eA(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const r=this.getID3Track(t.textTracks);return r.mode="hidden",r}getID3Track(t){if(this.media){for(let r=0;rhU&&(m=hU),m-h<=0&&(m=h+E7s);for(let y=0;yh.type===Rp.audioId3&&c:a==="video"?d=h=>h.type===Rp.emsg&&o:d=h=>h.type===Rp.audioId3&&c||h.type===Rp.emsg&&o,tSe(i,r,n,d)}}onLevelUpdated(t,{details:r}){this.updateDateRangeCues(r,!0)}onLevelPtsUpdated(t,r){Math.abs(r.drift)>.01&&this.updateDateRangeCues(r.details)}updateDateRangeCues(t,r){if(!this.hls||!this.media)return;const{assetPlayerId:n,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=nSe();if(n&&a&&!l){const{fragmentStart:w,fragmentEnd:b}=t;let N=this.assetCue;N?(N.startTime=w,N.endTime=b):o&&(N=this.assetCue=r_e(o,w,b,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),N&&(N.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(N),N.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,h=Object.keys(d);let m=this.dateRangeCuesAppended;if(c&&r){var x;if((x=c.cues)!=null&&x.length){const w=Object.keys(m).filter(b=>!h.includes(b));for(let b=w.length;b--;){var y;const N=w[b],S=(y=m[N])==null?void 0:y.cues;delete m[N],S&&Object.keys(S).forEach(T=>{const A=S[T];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else m=this.dateRangeCuesAppended={}}const v=t.fragments[t.fragments.length-1];if(!(h.length===0||!Zn(v==null?void 0:v.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let w=0;w{if(K!==N.id){const X=d[K];if(X.class===N.class&&X.startDate>N.startDate&&(!Q||N.startDate.01&&(K.startTime=S,K.endTime=D);else if(o){let X=N.attr[Q];Q8s(Q)&&(X=Rxt(X));const re=r_e(o,S,D,{key:Q,data:X},Rp.dateRange);re&&(re.id=b,this.id3Track.addCue(re),A[Q]=re,l&&(Q==="X-ASSET-LIST"||Q==="X-ASSET-URL")&&re.addEventListener("enter",this.onEventCueEnter))}}m[b]={cues:A,dateRange:N,durationKnown:I}}}}}class M7s{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:r}=this,n=this.levelDetails;if(!r||!n)return;this.currentTime=r.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!n.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+n.targetduration);if(c.05&&this.forwardBufferLength>1){const m=Math.min(2,Math.max(1,l)),x=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,y=Math.min(m,Math.max(1,x));this.changeMediaPlaybackRate(r,y)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,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 r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:r,partHoldBack:n,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&n||r;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const h=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),r=this.targetLatency;if(t===null||r===null)return null;const n=this.levelDetails;if(n===null)return null;const a=n.edge,i=t-r-this.edgeStalled,l=a-n.totalduration,o=a-(this.config.lowLatencyMode&&n.partTarget||n.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 r=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-r,0)}get forwardBufferLength(){const{media:t}=this,r=this.levelDetails;if(!t||!r)return 0;const n=t.buffered.length;return(n?t.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ht.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ht.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ht.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ht.ERROR,this.onError,this))}onMediaAttached(t,r){this.media=r.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:r}){r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,r){var n;r.details===ar.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,r){var n,a;t.playbackRate!==r&&((n=this.hls)==null||n.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 ${r}`),t.playbackRate=r)}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 I7s extends xAe{constructor(t,r){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=r,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ht.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ht.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ht.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ht.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.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,r){this.resetLevels()}onManifestLoaded(t,r){const n=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;r.levels.forEach(h=>{const m=h.attrs;let{audioCodec:x,videoCodec:y}=h;x&&(h.audioCodec=x=ime(x,n)||void 0),y&&(y=h.videoCodec=f8s(y));const{width:v,height:w,unknownCodecs:b}=h,N=(b==null?void 0:b.length)||0;if(o||(o=!!(v&&w)),c||(c=!!y),d||(d=!!x),N||x&&!this.isAudioSupported(x)||y&&!this.isVideoSupported(y)){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}const{CODECS:S,"FRAME-RATE":T,"HDCP-LEVEL":A,"PATHWAY-ID":I,RESOLUTION:D,"VIDEO-RANGE":R}=m,F=`${`${I||"."}-`}${h.bitrate}-${D}-${T}-${S}-${R}-${A}`;if(i[F])if(i[F].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const z=l[F]+=1;h.attrs["PATHWAY-ID"]=new Array(z+1).join(".");const Q=this.createLevel(h);i[F]=Q,a.push(Q)}else i[F].addGroupId("audio",m.AUDIO),i[F].addGroupId("text",m.SUBTITLES);else{const z=this.createLevel(h);i[F]=z,l[F]=1,a.push(z)}}),this.filterAndSortMediaOptions(a,r,o,c,d)}createLevel(t){const r=new kF(t),n=t.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(a.message),r.supportedResult=Kxt(a,[])}return r}isAudioSupported(t){return jF(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return jF(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,r,n,a,i){var l;let o=[],c=[],d=t;const h=((l=r.stats)==null?void 0:l.parsing)||{};if((n||a)&&i&&(d=d.filter(({videoCodec:S,videoRange:T,width:A,height:I})=>(!!S||!!(A&&I))&&N8s(T))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let S="no level with compatible codecs found in manifest",T=S;r.levels.length&&(T=`one or more CODECS in variant not supported: ${Ql(r.levels.map(I=>I.attrs.CODECS).filter((I,D,R)=>R.indexOf(I)===D))}`,this.warn(T),S+=` (${T})`);const A=new Error(S);this.hls.trigger(ht.ERROR,{type:La.MEDIA_ERROR,details:ar.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:A,reason:T})}}),h.end=performance.now();return}r.audioTracks&&(o=r.audioTracks.filter(S=>!S.audioCodec||this.isAudioSupported(S.audioCodec)),ZHe(o)),r.subtitles&&(c=r.subtitles,ZHe(c));const m=d.slice(0);d.sort((S,T)=>{if(S.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(S.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&S.height!==T.height)return S.height-T.height;if(S.frameRate!==T.frameRate)return S.frameRate-T.frameRate;if(S.videoRange!==T.videoRange)return ome.indexOf(S.videoRange)-ome.indexOf(T.videoRange);if(S.videoCodec!==T.videoCodec){const A=$Ve(S.videoCodec),I=$Ve(T.videoCodec);if(A!==I)return I-A}if(S.uri===T.uri&&S.codecSet!==T.codecSet){const A=ame(S.codecSet),I=ame(T.codecSet);if(A!==I)return I-A}return S.averageBitrate!==T.averageBitrate?S.averageBitrate-T.averageBitrate:0});let x=m[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==m.length)){for(let S=0;SA&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=I)}break}const v=i&&!a,w=this.hls.config,b=!!(w.audioStreamController&&w.audioTrackController),N={levels:d,audioTracks:o,subtitleTracks:c,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:i,video:a,altAudio:b&&!v&&o.some(S=>!!S.url)};h.end=performance.now(),this.hls.trigger(ht.MANIFEST_PARSED,N)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const r=this._levels;if(r.length===0)return;if(t<0||t>=r.length){const h=new Error("invalid level idx"),m=t<0;if(this.hls.trigger(ht.ERROR,{type:La.OTHER_ERROR,details:ar.LEVEL_SWITCH_ERROR,level:t,fatal:m,error:h,reason:h.message}),m)return;t=Math.min(t,r.length-1)}const n=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=r[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,n===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 ${n}${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(ht.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const h=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(h)}}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 r=this.steering.pathways(),n=t.filter(a=>r.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${r}`);return}this.steering.pathwayPriority=n}}onError(t,r){r.fatal||!r.context||r.context.type===ao.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(t,{frag:r}){if(r!==void 0&&r.type===ua.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(i=>!!n[i]))return;const a=this._levels[r.level];a!=null&&a.loadError&&(this.log(`Resetting level error count of ${a.loadError} on frag buffered`),a.loadError=0)}}onLevelLoaded(t,r){var n;const{level:a,details:i}=r,l=r.levelInfo;if(!l){var o;this.warn(`Invalid level index ${a}`),(o=r.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(l===this.currentLevel||r.withoutMultiVariant){l.fragmentError===0&&(l.loadError=0);let c=l.details;c===r.details&&c.advanced&&(c=void 0),this.playlistLoaded(a,r,c)}else(n=r.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,r){super.loadingPlaylist(t,r);const n=this.getUrlWithDirectives(t.uri,r),a=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],l=t.details,o=l==null?void 0:l.age;this.log(`Loading level index ${a}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${i?" Pathway "+i:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${n}`),this.hls.trigger(ht.LEVEL_LOADING,{url:n,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||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 r;if(this._levels.length===1)return;const n=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));pgt(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const a=n.length-1;this._firstLevel=Math.min(this._firstLevel,a),this._startLevel&&(this._startLevel=Math.min(this._startLevel,a)),this.hls.trigger(ht.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(t,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(ht.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function ZHe(s){const t={};s.forEach(r=>{const n=r.groupId||"";r.id=t[n]=t[n]||0,t[n]++})}function dyt(){return self.SourceBuffer||self.WebKitSourceBuffer}function uyt(){if(!zj())return!1;const t=dyt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function L7s(){if(!uyt())return!1;const s=zj();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(NF(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(NF(t,"audio"))))}function P7s(){var s;const t=dyt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const D7s=100;class R7s extends lAe{constructor(t,r,n){super(t,r,n,"stream-controller",ua.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||!Zn(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,ua.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(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ht.LEVEL_LOADING,this.onLevelLoading,this),t.on(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ht.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(ht.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ht.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(ht.BUFFER_CREATED,this.onBufferCreated,this),t.on(ht.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ht.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(ht.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ht.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ht.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(ht.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ht.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(ht.BUFFER_CREATED,this.onBufferCreated,this),t.off(ht.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ht.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ht.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,r){if(this.levels){const{lastCurrentTime:n,hls:a}=this;if(this.stopLoad(),this.setInterval(D7s),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=!!r}n>0&&t===-1&&!r&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),t=n),this.state=Or.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=r?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Or.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Or.WAITING_LEVEL:{const{levels:t,level:r}=this,n=t==null?void 0:t[r],a=n==null?void 0:n.details;if(a&&(!a.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(a))break;this.state=Or.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Or.IDLE;break}break}case Or.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Or.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:r,levels:n,media:a}=this;if(r===null||!a&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(n!=null&&n[i]))return;const l=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const w={};this.altAudio===2&&(w.type="video"),this.hls.trigger(ht.BUFFER_EOS,w),this.state=Or.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===Or.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=Or.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,m=this.getMaxBufferLength(l.maxBitrate);if(h>=m)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const x=this.backtrackFragment?this.backtrackFragment.start:o.end;let y=this.getNextFragment(x,d);if(this.couldBacktrack&&!this.fragPrevious&&y&&Yd(y)&&this.fragmentTracker.getState(y)!==Ou.OK){var v;const b=((v=this.backtrackFragment)!=null?v:y).sn-d.startSN,N=d.fragments[b-1];N&&y.cc===N.cc&&(y=N,this.fragmentTracker.removeFragment(N))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(y&&this.isLoopLoading(y,x)){if(!y.gap){const b=this.audioOnly&&!this.altAudio?Hl.AUDIO:Hl.VIDEO,N=(b===Hl.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;N&&this.afterBufferFlushed(N,b,ua.MAIN)}y=this.getNextFragmentLoopLoading(y,d,o,ua.MAIN,m)}y&&(this.exceedsMaxBuffer(o,m,y)||(y.initSegment&&!y.initSegment.data&&!this.bitrateTest&&(y=y.initSegment),this.loadFragment(y,l,x)))}loadFragment(t,r,n){const a=this.fragmentTracker.getState(t);a===Ou.NOT_LOADED||a===Ou.PARTIAL?Yd(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,r)):super.loadFragment(t,r,n):this._loadInitSegment(t,r):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,ua.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:r}=this;if(r!=null&&r.readyState){let n;const a=this.getAppendedFrag(r.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-r.maxFragLookUpTolerance&&i<=o;if(a!==null&&n.duration>a&&(i{this.hls&&this.hls.trigger(ht.AUDIO_TRACK_SWITCHED,r)}),n.trigger(ht.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(ht.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(t,r){const n=lme(r.url,this.hls);if(n){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=n?2:0,this.tick()}onBufferCreated(t,r){const n=r.tracks;let a,i,l=!1;for(const o in n){const c=n[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=n[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,r){const{frag:n,part:a}=r,i=n.type===ua.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${a?" p: "+a.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Or.PARSED&&(this.state=Or.IDLE);return}const o=a?a.stats:n.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Yd(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,a)}const l=this.media;l&&(!this._hasEnoughToStart&&Ai.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,r){var n;if(r.fatal){this.state=Or.ERROR;return}switch(r.details){case ar.FRAG_GAP:case ar.FRAG_PARSING_ERROR:case ar.FRAG_DECRYPT_ERROR:case ar.FRAG_LOAD_ERROR:case ar.FRAG_LOAD_TIMEOUT:case ar.KEY_LOAD_ERROR:case ar.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ua.MAIN,r);break;case ar.LEVEL_LOAD_ERROR:case ar.LEVEL_LOAD_TIMEOUT:case ar.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Or.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===ao.LEVEL&&(this.state=Or.IDLE);break;case ar.BUFFER_ADD_CODEC_ERROR:case ar.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case ar.BUFFER_FULL_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ar.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=Or.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:r}){if(r!==Hl.AUDIO||!this.altAudio){const n=(r===Hl.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,ua.MAIN),this.tick())}}onLevelsUpdated(t,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const r=t.currentTime;let n=this.startPosition;if(n>=0&&r0&&(c{const{hls:a}=this,i=n==null?void 0:n.frag;if(!i||this.fragContextChanged(i))return;r.fragmentError=0,this.state=Or.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(ht.FRAG_LOADED,n),i.bitrateTest=!1}).catch(n=>{this.state===Or.STOPPED||this.state===Or.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const r=this.playlistType,{hls:n}=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:h,text:m,id3:x,initSegment:y}=a,{details:v}=d,w=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Or.PARSING,y){const b=y.tracks;if(b){const A=o.initSegment||o;if(this.unhandledEncryptionError(y,o))return;this._bufferInitSegment(d,b,A,i),n.trigger(ht.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:r,tracks:b})}const N=y.initPTS,S=y.timescale,T=this.initPTS[o.cc];if(Zn(N)&&(!T||T.baseTime!==N||T.timescale!==S)){const A=y.trackId;this.initPTS[o.cc]={baseTime:N,timescale:S,trackId:A},n.trigger(ht.INIT_PTS_FOUND,{frag:o,id:r,initPTS:N,timescale:S,trackId:A})}}if(h&&v){w&&h.type==="audiovideo"&&this.logMuxedErr(o);const b=v.fragments[o.sn-1-v.startSN],N=o.sn===v.startSN,S=!b||o.cc>b.cc;if(a.independent!==!1){const{startPTS:T,endPTS:A,startDTS:I,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:T,endPTS:A,startDTS:I,endDTS:D};else if(h.firstKeyFrame&&h.independent&&i.id===1&&!S&&(this.couldBacktrack=!0),h.dropped&&h.independent){const R=this.getMainFwdBufferInfo(),$=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,F=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!N&&$Rce&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,A,I,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,i,N||S)}else if(N||S)o.gap=!0;else{this.backtrack(o);return}}if(w){const{startPTS:b,endPTS:N,startDTS:S,endDTS:T}=w;c&&(c.elementaryStreams[Hl.AUDIO]={startPTS:b,endPTS:N,startDTS:S,endDTS:T}),o.setElementaryStreamInfo(Hl.AUDIO,b,N,S,T),this.bufferFragmentData(w,o,c,i)}if(v&&x!=null&&x.samples.length){const b={id:r,frag:o,details:v,samples:x.samples};n.trigger(ht.FRAG_PARSING_METADATA,b)}if(v&&m){const b={id:r,frag:o,details:v,samples:m.samples};n.trigger(ht.FRAG_PARSING_USERDATA,b)}}logMuxedErr(t){this.warn(`${Yd(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,r,n,a){if(this.state!==Or.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:i,video:l,audiovideo:o}=r;if(i){const d=t.audioCodec;let h=Ece(i.codec,d);h==="mp4a"&&(h="mp4a.40.5");const m=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const x=i.metadata;x&&"channelCount"in x&&(x.channelCount||1)!==1&&m.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&m.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),d&&d!==h&&this.log(`Swapping manifest audio codec "${d}" for "${h}"`),i.levelCodec=h,i.id=ua.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${h||""}/${d||""}/${i.codec}]`),delete r.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=ua.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 r.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete r.video,delete r.audio);const c=Object.keys(r);if(c.length){if(this.hls.trigger(ht.BUFFER_CODECS,r),!this.hls)return;c.forEach(d=>{const m=r[d].initSegment;m!=null&&m.byteLength&&this.hls.trigger(ht.BUFFER_APPENDING,{type:d,data:m,frag:n,part:null,chunkMeta:a,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,ua.MAIN)}get maxBufferLength(){const{levels:t,level:r}=this,n=t==null?void 0:t[r];return n?this.getMaxBufferLength(n.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=Or.IDLE}checkFragmentChanged(){const t=this.media;let r=null;if(t&&t.readyState>1&&t.seeking===!1){const n=t.currentTime;if(Ai.isBuffered(t,n)?r=this.getAppendedFrag(n):Ai.isBuffered(t,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const a=this.fragPlaying,i=r.level;(!a||r.sn!==a.sn||a.level!==i)&&(this.fragPlaying=r,this.hls.trigger(ht.FRAG_CHANGED,{frag:r}),(!a||a.level!==i)&&this.hls.trigger(ht.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 r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return Zn(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var t;const r=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Zn(r)){const n=this.getLevelDetails(),a=this.currentFrag||(n?e5(null,n.fragments,r):null);if(a){const i=a.programDateTime;if(i!==null){const l=i+(r-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 O7s extends Sg{constructor(t,r){super("key-loader",r),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const n in this.keyIdToKeyInfo){const a=this.keyIdToKeyInfo[n].loader;if(a){var r;if(t&&t!==((r=a.context)==null?void 0:r.frag.type))return;a.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[t];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[t].loader;r&&r.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,r=ar.KEY_LOAD_ERROR,n,a,i){return new q1({type:La.NETWORK_ERROR,details:r,fatal:!1,frag:t,response:i,error:n,networkDetails:a})}loadClear(t,r,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(r.length)for(let a=0,i=r.length;a{if(!this.emeController)return;l.setKeyFormat(o);const c=Mce(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=UD(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(r=>this.loadInternal(t,r)):this.loadInternal(t)}loadInternal(t,r){var n,a;r&&t.setKeyFormat(r);const i=t.decryptdata;if(!i){const d=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,ar.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,ar.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=n_e(i);let c=this.keyIdToKeyInfo[o];if((n=c)!=null&&n.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(h=>{const{keyInfo:m}=h;return i.key=m.decryptdata.key,{frag:t,keyInfo:m}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+qh(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,ar.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,r){const n={frag:r,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var a;if(!t.decryptdata.keyId&&(a=r.initSegment)!=null&&a.data){const l=s8s(r.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${qh(o)}`),wj.setKeyIdForUri(t.decryptdata.uri,o)):(o=wj.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${qh(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Yd(r))return Promise.resolve(n);const i=this.emeController.loadKey(n);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,n))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=r),l})}return Promise.resolve(n)}loadKeyHTTP(t,r){const n=this.config,a=n.loader,i=new a(n);return r.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:r,responseType:"arraybuffer",url:t.decryptdata.uri},d=n.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},m={onSuccess:(x,y,v,w)=>{const{frag:b,keyInfo:N}=v,S=n_e(N.decryptdata);if(!b.decryptdata||N!==this.keyIdToKeyInfo[S])return o(this.createKeyLoadError(b,ar.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),w));N.decryptdata.key=b.decryptdata.key=new Uint8Array(x.data),b.keyLoader=null,N.loader=null,l({frag:b,keyInfo:N})},onError:(x,y,v,w)=>{this.resetLoader(y),o(this.createKeyLoadError(r,ar.KEY_LOAD_ERROR,new Error(`HTTP Error ${x.code} loading key ${x.text}`),v,Sl({url:c.url,data:void 0},x)))},onTimeout:(x,y,v)=>{this.resetLoader(y),o(this.createKeyLoadError(r,ar.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(x,y,v)=>{this.resetLoader(y),o(this.createKeyLoadError(r,ar.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};i.load(c,h,m)})}resetLoader(t){const{frag:r,keyInfo:n,url:a}=t,i=n.loader;r.keyLoader===i&&(r.keyLoader=null,n.loader=null);const l=n_e(n.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function n_e(s){if(s.keyFormat!==Gh.FAIRPLAY){const t=s.keyId;if(t)return qh(t)}return s.uri}function XHe(s){const{type:t}=s;switch(t){case ao.AUDIO_TRACK:return ua.AUDIO;case ao.SUBTITLE_TRACK:return ua.SUBTITLE;default:return ua.MAIN}}function a_e(s,t){let r=s.url;return(r===void 0||r.indexOf("data:")===0)&&(r=t.url),r}class F7s{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(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ht.LEVEL_LOADING,this.onLevelLoading,this),t.on(ht.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(ht.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(ht.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(ht.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ht.LEVEL_LOADING,this.onLevelLoading,this),t.off(ht.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(ht.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(ht.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const r=this.hls.config,n=r.pLoader,a=r.loader,i=n||a,l=new i(r);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 r=this.loaders[t];r&&r.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ao.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,r){const{id:n,level:a,pathwayId:i,url:l,deliveryDirectives:o,levelInfo:c}=r;this.load({id:n,level:a,pathwayId:i,responseType:"text",type:ao.LEVEL,url:l,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(t,r){const{id:n,groupId:a,url:i,deliveryDirectives:l,track:o}=r;this.load({id:n,groupId:a,level:null,responseType:"text",type:ao.AUDIO_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onSubtitleTrackLoading(t,r){const{id:n,groupId:a,url:i,deliveryDirectives:l,track:o}=r;this.load({id:n,groupId:a,level:null,responseType:"text",type:ao.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,r){const n=this.loaders[ao.LEVEL];if(n){const a=n.context;a&&!r.levels.some(i=>i===a.levelOrTrack)&&(n.abort(),delete this.loaders[ao.LEVEL])}}load(t){var r;const n=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,h=a.context;if(h&&h.levelOrTrack===t.levelOrTrack&&(h.url===t.url||h.deliveryDirectives&&!t.deliveryDirectives)){h.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${h.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===ao.MANIFEST?i=n.manifestLoadPolicy.default:i=zl({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Zn((r=t.deliveryDirectives)==null?void 0:r.part)){let d;if(t.type===ao.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===ao.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===ao.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const h=d.partTarget,m=d.targetduration;if(h&&m){const x=Math.max(h*3,m*.8)*1e3;i=zl({},i,{maxTimeToFirstByteMs:Math.min(x,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(x,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,h,m,x)=>{const y=this.getInternalLoader(m);this.resetInternalLoader(m.type);const v=d.data;h.parsing.start=performance.now(),X0.isMediaPlaylist(v)||m.type!==ao.MANIFEST?this.handleTrackOrLevelPlaylist(d,h,m,x||null,y):this.handleMasterPlaylist(d,h,m,x)},onError:(d,h,m,x)=>{this.handleNetworkError(h,m,!1,d,x)},onTimeout:(d,h,m)=>{this.handleNetworkError(h,m,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:r},forceStartLoad:n}=this.hls;(t||n)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${r}`),this.hls.startLoad(r))}handleMasterPlaylist(t,r,n,a){const i=this.hls,l=t.data,o=a_e(t,n),c=X0.parseMasterPlaylist(l,o);if(c.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(t,n,c.playlistParsingError,a,r);return}const{contentSteering:d,levels:h,sessionData:m,sessionKeys:x,startTimeOffset:y,variableList:v}=c;this.variableList=v,h.forEach(S=>{const{unknownCodecs:T}=S;if(T){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:I,videoCodec:D}=S;for(let R=T.length;R--;){const $=T[R];jF($,"audio",A)?(S.audioCodec=I=I?`${I},${$}`:$,kI.audio[I.substring(0,4)]=2,T.splice(R,1)):jF($,"video",A)&&(S.videoCodec=D=D?`${D},${$}`:$,kI.video[D.substring(0,4)]=2,T.splice(R,1))}}});const{AUDIO:w=[],SUBTITLES:b,"CLOSED-CAPTIONS":N}=X0.parseMasterPlaylistMedia(l,o,c);w.length&&!w.some(T=>!T.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),w.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ed({}),bitrate:0,url:""})),i.trigger(ht.MANIFEST_LOADED,{levels:h,audioTracks:w,subtitles:b,captions:N,contentSteering:d,url:o,stats:r,networkDetails:a,sessionData:m,sessionKeys:x,startTimeOffset:y,variableList:v})}handleTrackOrLevelPlaylist(t,r,n,a,i){const l=this.hls,{id:o,level:c,type:d}=n,h=a_e(t,n),m=Zn(c)?c:Zn(o)?o:0,x=XHe(n),y=X0.parseLevelPlaylist(t.data,h,m,x,0,this.variableList);if(d===ao.MANIFEST){const v={attrs:new ed({}),bitrate:0,details:y,name:"",url:h};y.requestScheduled=r.loading.start+hgt(y,0),l.trigger(ht.MANIFEST_LOADED,{levels:[v],audioTracks:[],url:h,stats:r,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=y,this.handlePlaylistLoaded(y,t,r,n,a,i)}handleManifestParsingError(t,r,n,a,i){this.hls.trigger(ht.ERROR,{type:La.NETWORK_ERROR,details:ar.MANIFEST_PARSING_ERROR,fatal:r.type===ao.MANIFEST,url:t.url,err:n,error:n,reason:n.message,response:t,context:r,networkDetails:a,stats:i})}handleNetworkError(t,r,n=!1,a,i){let l=`A network ${n?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===ao.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===ao.AUDIO_TRACK||t.type===ao.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=ar.UNKNOWN,d=!1;const h=this.getInternalLoader(t);switch(t.type){case ao.MANIFEST:c=n?ar.MANIFEST_LOAD_TIMEOUT:ar.MANIFEST_LOAD_ERROR,d=!0;break;case ao.LEVEL:c=n?ar.LEVEL_LOAD_TIMEOUT:ar.LEVEL_LOAD_ERROR,d=!1;break;case ao.AUDIO_TRACK:c=n?ar.AUDIO_TRACK_LOAD_TIMEOUT:ar.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case ao.SUBTITLE_TRACK:c=n?ar.SUBTITLE_TRACK_LOAD_TIMEOUT:ar.SUBTITLE_LOAD_ERROR,d=!1;break}h&&this.resetInternalLoader(t.type);const m={type:La.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:h,context:t,error:o,networkDetails:r,stats:i};if(a){const x=(r==null?void 0:r.url)||t.url;m.response=Sl({url:x,data:void 0},a)}this.hls.trigger(ht.ERROR,m)}handlePlaylistLoaded(t,r,n,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:h,id:m,groupId:x,deliveryDirectives:y}=a,v=a_e(r,a),w=XHe(a);let b=typeof a.level=="number"&&w===ua.MAIN?d:void 0;const N=t.playlistParsingError;if(N){if(this.hls.logger.warn(`${N} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(ht.ERROR,{type:La.NETWORK_ERROR,details:ar.LEVEL_PARSING_ERROR,fatal:!1,url:v,error:N,reason:N.message,response:r,context:a,level:b,parent:w,networkDetails:i,stats:n});return}t.playlistParsingError=null}if(!t.fragments.length){const S=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(ht.ERROR,{type:La.NETWORK_ERROR,details:ar.LEVEL_EMPTY_ERROR,fatal:!1,url:v,error:S,reason:S.message,response:r,context:a,level:b,parent:w,networkDetails:i,stats:n});return}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),c){case ao.MANIFEST:case ao.LEVEL:if(b){if(!h)b=0;else if(h!==o.levels[b]){const S=o.levels.indexOf(h);S>-1&&(b=S)}}o.trigger(ht.LEVEL_LOADED,{details:t,levelInfo:h||o.levels[0],level:b||0,id:m||0,stats:n,networkDetails:i,deliveryDirectives:y,withoutMultiVariant:c===ao.MANIFEST});break;case ao.AUDIO_TRACK:o.trigger(ht.AUDIO_TRACK_LOADED,{details:t,track:h,id:m||0,groupId:x||"",stats:n,networkDetails:i,deliveryDirectives:y});break;case ao.SUBTITLE_TRACK:o.trigger(ht.SUBTITLE_TRACK_LOADED,{details:t,track:h,id:m||0,groupId:x||"",stats:n,networkDetails:i,deliveryDirectives:y});break}}}class q0{static get version(){return SF}static isMSESupported(){return uyt()}static isSupported(){return L7s()}static getMediaSource(){return zj()}static get Events(){return ht}static get MetadataSchema(){return Rp}static get ErrorTypes(){return La}static get ErrorDetails(){return ar}static get DefaultConfig(){return q0.defaultConfig?q0.defaultConfig:_7s}static set DefaultConfig(t){q0.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 cAe,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 r=this.logger=VOs(t.debug||!1,"Hls instance",t.assetPlayerId),n=this.config=j7s(q0.DefaultConfig,t,r);this.userConfig=t,n.progressive&&N7s(n,r);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=n,d=new o(this),h=this.abrController=new a(this),m=new B8s(this),x=n.interstitialsController,y=x?this.interstitialsController=new x(this,q0):null,v=this.bufferController=new i(this,m),w=this.capLevelController=new l(this),b=new c(this),N=new F7s(this),S=n.contentSteeringController,T=S?new S(this):null,A=this.levelController=new I7s(this,T),I=new A7s(this),D=new O7s(this.config,this.logger),R=this.streamController=new R7s(this,m,D),$=this.gapController=new T7s(this,m);w.setStreamController(R),b.setStreamController(R);const F=[N,A,R];y&&F.splice(1,0,y),T&&F.splice(1,0,T),this.networkControllers=F;const z=[h,v,$,w,b,I,m];this.audioTrackController=this.createController(n.audioTrackController,F);const Q=n.audioStreamController;Q&&F.push(this.audioStreamController=new Q(this,m,D)),this.subtitleTrackController=this.createController(n.subtitleTrackController,F);const K=n.subtitleStreamController;K&&F.push(this.subtititleStreamController=new K(this,m,D)),this.createController(n.timelineController,z),D.emeController=this.emeController=this.createController(n.emeController,z),this.cmcdController=this.createController(n.cmcdController,z),this.latencyController=this.createController(M7s,z),this.coreComponents=z,F.push(d);const X=d.onErrorOut;typeof X=="function"&&this.on(ht.ERROR,X,d),this.on(ht.MANIFEST_LOADED,N.onManifestLoaded,N)}createController(t,r){if(t){const n=new t(this);return r&&r.push(n),n}return null}on(t,r,n=this){this._emitter.on(t,r,n)}once(t,r,n=this){this._emitter.once(t,r,n)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,r,n=this,a){this._emitter.off(t,r,n,a)}listeners(t){return this._emitter.listeners(t)}emit(t,r,n){return this._emitter.emit(t,r,n)}trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const a=t===ht.ERROR;this.trigger(ht.ERROR,{type:La.OTHER_ERROR,details:ar.INTERNAL_EXCEPTION,fatal:a,event:t,error:n}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(ht.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.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(ht.ERROR,{type:La.OTHER_ERROR,details:ar.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 r="media"in t,n=r?t.media:t,a=r?t:{media:n};this._media=n,this.trigger(ht.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(ht.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(ht.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const r=this.media,n=this._url,a=this._url=QEe.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),r&&n&&(n!==a||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(ht.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,r){this.logger.log(`startLoad(${t+(r?", ":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[ua.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[ua.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[ua.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,r=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),r&&this.startLoad(r))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=Tzs()),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 r=!!t;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}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){j8s(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:r}}=this;if(!t)return 0;const n=t.length;for(let a=0;a=r)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:r,maxHdcpLevel:n}=this;let a;if(r===-1&&t!=null&&t.length?a=t.length-1:a=r,n)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=n)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 r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(t))||null}setSubtitleOption(t){var r;return((r=this.subtitleTrackController)==null?void 0:r.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 r=this.audioTrackController;r&&(r.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 r=this.subtitleTrackController;r&&(r.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const r=this.subtitleTrackController;r&&(r.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,r=this.allAudioTracks){const n=Xxt(r);return Yxt(t,n,navigator.mediaCapabilities)}}q0.defaultConfig=void 0;const B7s=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function tA(s){return!!s&&B7s.test(s)&&!/\.mp4($|\?)/i.test(s)}function z7s(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function $7s(s,t){if(!s)return null;const r=z7s(s);if(r){const n=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/${r.libraryId}/${r.videoId}?${n.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 U7s(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const aSe=k.forwardRef(function({sourceUrl:t,thumbnailUrl:r,autoPlay:n,muted:a,loop:i,playsInline:l=!0,...o},c){const d=k.useRef(null),[h,m]=k.useState(null),x=k.useMemo(()=>$7s(t,{autoplay:!!n,muted:!!a,loop:!!i}),[t,n,a,i]);k.useEffect(()=>{let v=!1;if(!t){m(null);return}if(!tA(t)){m(t);return}if(!x){m(null);return}return m(null),fetch(x).then(async w=>{if(!w.ok)throw new Error(`Failed to load Bunny embed (${w.status})`);const b=await w.text();return U7s(b)}).then(w=>{v||m(w)}).catch(()=>{v||m(null)}),()=>{v=!0}},[x,t]),k.useEffect(()=>{const v=d.current;if(!v||!h)return;let w=null;const b=()=>{if(!n)return;const S=v.play();S&&S.catch(()=>{})};if(v.muted=!!a,v.loop=!!i,h.endsWith(".m3u8")){if(v.canPlayType("application/vnd.apple.mpegurl")){v.src=h;const S=()=>b();return v.addEventListener("loadedmetadata",S),()=>{v.removeEventListener("loadedmetadata",S),v.removeAttribute("src"),v.load()}}return q0.isSupported()?(w=new q0({enableWorker:!0,lowLatencyMode:!0}),w.loadSource(h),w.attachMedia(v),w.on(q0.Events.MANIFEST_PARSED,b),()=>{w==null||w.destroy(),v.removeAttribute("src"),v.load()}):void 0}v.src=h;const N=()=>b();return v.addEventListener("loadedmetadata",N),()=>{v.removeEventListener("loadedmetadata",N),v.removeAttribute("src"),v.load()}},[n,i,a,h]),k.useEffect(()=>{const v=d.current;if(v){if(v.muted=!!a,v.loop=!!i,n&&h){const w=v.play();w&&w.catch(()=>{});return}v.pause()}},[n,i,a,h]);const y=v=>{if(d.current=v,typeof c=="function"){c(v);return}c&&(c.current=v)};return e.jsx("video",{ref:y,poster:r||void 0,autoPlay:n,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),q7s={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 V7s(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function QHe(s,t){return!s||s.length===0?!1:s.some(r=>r?r===t?!0:r.endsWith("*")?t.startsWith(r.slice(0,-1)):t.startsWith(r):!1)}function wAe({config:s,appSlug:t="video_greeter",preview:r=!1,embedded:n=!1}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[h,m]=k.useState(!1),[x,y]=k.useState("portrait"),[v,w]=k.useState(!1),[b,N]=k.useState(!1),[S,T]=k.useState({name:"",email:"",phone:""}),[A,I]=k.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),D=k.useRef(null),R=k.useRef(null),$=k.useRef(!1),F=async(Oe,Ye)=>{if(!r)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Oe,visitor_token:V7s(),page_url:typeof window<"u"?window.location.href:null,metadata:Ye||{}})}catch{}};k.useEffect(()=>{if(h)return;const Oe=typeof window<"u"?window.location.pathname:"/",Ye=s.targeting||{mode:"all"};if(Ye.mode==="include"&&!QHe(Ye.include,Oe)||Ye.mode==="exclude"&&QHe(Ye.exclude,Oe))return;const We=s.trigger||{type:"immediate"};if(We.type==="immediate"||r){i(!0);return}if(We.type==="delay"){const _e=(We.value||3)*1e3,Re=setTimeout(()=>i(!0),_e);return()=>clearTimeout(Re)}if(We.type==="scroll"){const _e=(We.value||25)/100,Re=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=_e&&(i(!0),window.removeEventListener("scroll",Re))};return window.addEventListener("scroll",Re,{passive:!0}),()=>window.removeEventListener("scroll",Re)}if(We.type==="exit_intent"){const _e=Re=>{Re.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",_e),()=>document.removeEventListener("mouseleave",_e)}},[h,s.targeting,s.trigger,r]),k.useEffect(()=>{a&&!$.current&&($.current=!0,F("impression"))},[a]),k.useEffect(()=>{if(l&&R.current&&!tA(s.video_url)){R.current.currentTime=0,R.current.muted=!1,d(!1);const Oe=R.current.play();Oe&&Oe.catch(()=>{})}else l&&tA(s.video_url)&&d(!1)},[l,s.video_url]),k.useEffect(()=>{if(!s.thumbnail_url)return;let Oe=!1;const Ye=new Image;return Ye.onload=()=>{Oe||y(Ye.naturalWidth>Ye.naturalHeight?"landscape":"portrait")},Ye.src=s.thumbnail_url,()=>{Oe=!0}},[s.thumbnail_url]),k.useEffect(()=>{const Oe=()=>{I({width:window.innerWidth,height:window.innerHeight})};return Oe(),window.addEventListener("resize",Oe),()=>window.removeEventListener("resize",Oe)},[]);const z=()=>{o(!0),F("expand")},Q=Oe=>{Oe.stopPropagation(),m(!0),o(!1)},K=Oe=>{F("cta_click",{cta_id:Oe.id,label:Oe.label,url:Oe.url})},X=async Oe=>{if(Oe.preventDefault(),r){w(!0);return}if(!(!S.email||!S.name)){N(!0);try{const{error:Ye}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:S.name,email:S.email,phone:S.phone||void 0,page_url:window.location.href}});if(Ye)throw Ye;F("lead_capture",{email:S.email}),w(!0)}catch(Ye){console.error("lead submit failed",Ye)}finally{N(!1)}}};if(!a||h||!s.video_url&&!s.video_embed_url)return null;const Z=q7s[x][s.size||"md"],re=n?"absolute left-2 bottom-2":r?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",le=s.shape==="circle"?"rounded-full":"rounded-2xl",oe=r?x==="landscape"?"w-[280px]":"w-[220px]":x==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ne=x==="landscape"?"aspect-video":"aspect-[9/16]",ie=s.agent||{},ye=s.lead_form_fields||["name","email","phone"],ce=!!(s.show_socials&&(ie.instagram_url||ie.facebook_url||ie.linkedin_url)),ve=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!v?72+ye.length*42:0)+(v?40:0)+(ce?34:0),be=Math.max(300,A.height-32),Ue=Math.max(220,A.width-32),Be=Math.max(150,be-ve),De=Math.floor(x==="landscape"?Be*(16/9):Be*(9/16)),Ae=x==="landscape"?Math.max(220,Math.min(420,Ue,De)):Math.max(180,Math.min(340,Ue,De)),He=n?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${oe} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Le=n?{width:`${Ae}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Ie=n?"p-3 space-y-2.5":"p-4 space-y-3",Te=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",xe=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",et=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",fe=n?"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=n?"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:`${re} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:He,style:Le,children:[e.jsxs("div",{className:`relative bg-black ${ne}`,children:[tA(s.video_url)?e.jsx(aSe,{ref:R,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Oe=>{const{videoWidth:Ye,videoHeight:We}=Oe.currentTarget;Ye&&We&&y(Ye>We?"landscape":"portrait")},onEnded:()=>F("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:R,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:Oe=>{const{videoWidth:Ye,videoHeight:We}=Oe.currentTarget;Ye&&We&&y(Ye>We?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{R.current&&(R.current.muted=!R.current.muted,d(R.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(ZR,{className:"w-4 h-4"}):e.jsx(YR,{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(vr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Ie,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ie.avatar_url&&e.jsx("img",{src:ie.avatar_url,alt:ie.name||"",className:Te}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:xe,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:et,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Oe=>{var Ye;return e.jsxs("a",{href:Oe.url,target:(Ye=Oe.url)!=null&&Ye.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>K(Oe),className:`flex items-center justify-between gap-2 ${n?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Oe.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:Oe.label}),e.jsx(Qr,{className:"w-3.5 h-3.5 opacity-60"})]},Oe.id)})}),s.lead_form_enabled&&!v&&e.jsxs("form",{onSubmit:X,className:"space-y-2 pt-1",children:[ye.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:S.name,onChange:Oe=>T({...S,name:Oe.target.value}),className:fe}),ye.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:S.email,onChange:Oe=>T({...S,email:Oe.target.value}),className:fe}),ye.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:S.phone,onChange:Oe=>T({...S,phone:Oe.target.value}),className:fe}),e.jsxs("button",{type:"submit",disabled:b,className:it,children:[e.jsx(en,{className:"w-3.5 h-3.5"}),b?"Sending...":"Send"]})]}),v&&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&&(ie.instagram_url||ie.facebook_url||ie.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ie.instagram_url&&e.jsx("a",{href:ie.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"instagram"}),children:e.jsx(Jd,{className:"w-4 h-4"})}),ie.facebook_url&&e.jsx("a",{href:ie.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"facebook"}),children:e.jsx(yu,{className:"w-4 h-4"})}),ie.linkedin_url&&e.jsx("a",{href:ie.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"linkedin"}),children:e.jsx(Jh,{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 ${le} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:Z.w,height:Z.h},"aria-label":"Play video greeting",children:[tA(s.video_url)?e.jsx(aSe,{ref:D,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:Oe=>{const{videoWidth:Ye,videoHeight:We}=Oe.currentTarget;Ye&&We&&y(Ye>We?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:D,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:Oe=>{const{videoWidth:Ye,videoHeight:We}=Oe.currentTarget;Ye&&We&&y(Ye>We?"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:Q,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(vr,{className:"w-3.5 h-3.5"})})]})})}function jAe({slug:s}){const[t,r]=k.useState(null);return k.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_video_greeter_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(wAe,{config:t}):null}const hyt="eip_last_shown",JHe="eip_visitor_token";function H7s(){try{let s=localStorage.getItem(JHe);return s||(s=crypto.randomUUID(),localStorage.setItem(JHe,s)),s}catch{return}}function G7s(s){try{const t=Number(localStorage.getItem(hyt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function W7s(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,n=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?n:!n}function myt({config:s,preview:t=!1,forceOpen:r=!1}){const[n,a]=k.useState(r),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState({name:"",email:"",phone:""}),m=k.useRef(!1),x=k.useRef(!1),y=async(D,R={})=>{if(!t)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:D,visitor_token:H7s(),page_url:window.location.href,metadata:R})}catch{}};k.useEffect(()=>{if(t||!W7s(s.targeting)||!G7s(s.frequency_days))return;const D=/Mobi|Android/i.test(navigator.userAgent),R={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,$=K=>{if(!m.current){m.current=!0,a(!0);try{localStorage.setItem(hyt,String(Date.now()))}catch{}y("impression",{reason:K})}},F=K=>{K.clientY<=R&&$("mouse_leave")},z=()=>{s.enable_mobile_back&&D&&$("back_button")};if(s.enable_mobile_back&&D){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",z)}else document.addEventListener("mouseleave",F);let Q;return s.enable_time_fallback&&(Q=window.setTimeout(()=>$("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",F),window.removeEventListener("popstate",z),Q&&window.clearTimeout(Q)}},[s,t]),k.useEffect(()=>{n&&!x.current&&!t&&!m.current&&(x.current=!0)},[n,t]);const v=()=>{a(!1),t||y("close")},w=async D=>{if(D.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:R}=await V.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(R)throw R;y("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(R){console.error("exit intent submit failed",R)}finally{c(!1)}}};if(!n)return null;const b=s.form_fields||["name","email"],N=s.agent||{},S=[N.first_name,N.last_name].filter(Boolean).join(" "),T=s.use_agent_photo&&N.avatar_url||s.image_url,A=s.theme_color||"#f97316",I=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:I,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:D=>D.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${A}, ${i_e(A,-25)})`}}),e.jsx("button",{onClick:v,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(vr,{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:[T&&e.jsx("img",{src:T,alt:S||"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(jr,{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:w,className:"space-y-2.5",children:[b.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:D=>h({...d,name:D.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}),b.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:D=>h({...d,email:D.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}),b.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:D=>h({...d,phone:D.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}, ${i_e(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:()=>y("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}, ${i_e(A,-20)})`},children:s.cta_label}),S&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",S]})]})]})})}function i_e(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,h=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+h).toString(16).slice(1)}catch{return s}}function NAe({slug:s}){const[t,r]=k.useState(null);return k.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_exit_intent_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(myt,{config:t}):null}const eGe="lm_dismissed",tGe="lm_visitor_token";function K7s(){try{let s=localStorage.getItem(tGe);return s||(s=crypto.randomUUID(),localStorage.setItem(tGe,s)),s}catch{return}}function Y7s(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,n=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?n:!n}function kAe({config:s,preview:t=!1}){const[r,n]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState({name:"",email:"",phone:""}),x=k.useRef(!1),y=async(T,A={})=>{if(!t)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:T,visitor_token:K7s(),page_url:window.location.href,metadata:A})}catch{}};k.useEffect(()=>{if(t){n(!0);return}if(!Y7s(s.targeting))return;try{if(sessionStorage.getItem(eGe))return}catch{}const T=()=>{x.current||(x.current=!0,n(!0),y("impression"))};if(s.trigger_type==="immediate")T();else if(s.trigger_type==="delay"){const A=window.setTimeout(T,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)&&T()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const v=()=>{n(!1);try{sessionStorage.setItem(eGe,"1")}catch{}t||y("close")},w=async T=>{if(T.preventDefault(),t){o(!0);return}if(!(!h.email||!h.name)){d(!0);try{const{error:A}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:h.name,email:h.email,phone:h.phone||void 0,page_url:window.location.href}});if(A)throw A;y("lead_capture",{email:h.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const I=document.createElement("a");I.href=s.download_url,I.target="_blank",I.rel="noopener",I.download="",document.body.appendChild(I),I.click(),I.remove()},600)}catch(A){console.error("lead magnet submit failed",A)}finally{d(!1)}}};if(!r)return null;const b=s.theme_color||"#2563eb",N=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, ${b}, ${wD(b,-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(ii,{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),y("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:b},children:s.download_label}),e.jsx("button",{onClick:v,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(vr,{className:"w-4 h-4"})})]})}),a&&S()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),y("expand")},className:`${N} 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, ${b}, ${wD(b,-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(bh,{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:T=>{T.stopPropagation(),v()},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(vr,{className:"w-3 h-3"})})]}),a&&S()]});return S();function S(){const T=s.form_fields||["name","email"],A=s.agent||{},I=[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:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${b}, ${wD(b,-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(ln,{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:b},children:[e.jsx(ii,{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(vr,{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:`${b}10`},children:[e.jsx(Ya,{className:"w-8 h-8 mx-auto",style:{color:b}}),e.jsx("p",{className:"text-sm font-medium",style:{color:b},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:b},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:w,className:"space-y-2.5",children:[T.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:h.name,onChange:D=>m({...h,name:D.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":b},required:!0}),T.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:h.email,onChange:D=>m({...h,email:D.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":b},required:!0}),T.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:h.phone,onChange:D=>m({...h,phone:D.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":b}}),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, ${b}, ${wD(b,-20)})`},children:[e.jsx(Ya,{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:()=>y("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, ${b}, ${wD(b,-20)})`},children:s.download_label}),I&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",I]})]})]})})}}function wD(s,t){try{const r=parseInt(s.slice(1),16),n=t<0?0:255,a=Math.abs(t)/100,i=r>>16,l=r>>8&255,o=r&255,c=Math.round((n-i)*a)+i,d=Math.round((n-l)*a)+l,h=Math.round((n-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+h).toString(16).slice(1)}catch{return s}}function SAe({slug:s}){const[t,r]=k.useState(null);return k.useEffect(()=>{if(!s)return;let n=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_lead_magnet_config",{_slug:s});!n&&!i&&a&&r(a)})(),()=>{n=!0}},[s]),t?e.jsx(kAe,{config:t}):null}function Z7s({children:s,siteConfig:t}){var ce,ve,be,Ue,Be,De,Ae,He,Le,Ie;const r=ec(),n=br(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState([]),[x,y]=k.useState([]),[v,w]=k.useState(null),b=k.useRef(null),N=k.useRef(null),{user:S,profile:T,signOut:A}=Kxe();ZEe(t,S==null?void 0:S.id),XEe(t,S==null?void 0:S.id);const I=((ce=t.agent)==null?void 0:ce.full_name)||"Agent",D=t.siteTitle||`${I} Real Estate`,R=r.pathname==="/search",$=r.pathname==="/",F=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{(async()=>{const{data:xe}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});m(xe||[])})()},[t.id]),k.useEffect(()=>{(async()=>{const{data:xe}=await V.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});y(xe||[])})()},[t.id]),k.useEffect(()=>{const Te=xe=>{b.current&&!b.current.contains(xe.target)&&d(!1),N.current&&!N.current.contains(xe.target)&&w(null)};return document.addEventListener("mousedown",Te),()=>document.removeEventListener("mousedown",Te)},[]);const z=((ve=t==null?void 0:t.themeConfig)==null?void 0:ve.referralMode)===!0||!t.mlsProviderId,Q=x.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"}],X=Q?[]:K,Z=x.filter(Te=>!Te.parent_id),re=Te=>x.filter(xe=>xe.parent_id===Te),le=$?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",oe=t.siteTitle||`${I} - Real Estate`,ne=t.siteTagline||`Browse homes and listings with ${I}`,ie=t.ogImageUrl||((be=t.agent)==null?void 0:be.avatar_url)||"",ye=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${R?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(KEe,{siteConfig:t,pagePath:r.pathname}),e.jsx(YEe,{siteConfig:t}),e.jsxs(nl,{children:[e.jsx("title",{children:oe}),e.jsx("meta",{name:"description",content:ne}),e.jsx("meta",{property:"og:title",content:oe}),e.jsx("meta",{property:"og:description",content:ne}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ye+r.pathname}),ie&&e.jsx("meta",{property:"og:image",content:ie}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:oe}),e.jsx("meta",{name:"twitter:description",content:ne}),ie&&e.jsx("meta",{name:"twitter:image",content:ie}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ye}${r.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${$?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${le}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsxs(Yn,{to:"/",className:"flex items-center gap-3",children:[((Ue=t.agent)==null?void 0:Ue.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:I,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:D})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[X.map(Te=>e.jsx(Yn,{to:Te.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===Te.to?$?"bg-white/15 text-white":"bg-gray-100 text-gray-900":$?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Te.label},Te.to)),Q&&Z.map(Te=>{if(Te.item_type==="dropdown"){const xe=re(Te.id);return e.jsxs("div",{ref:N,className:"relative",children:[e.jsxs("button",{onClick:()=>w(v===Te.id?null:Te.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${$?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Te.label," ",e.jsx(Wi,{className:`h-3.5 w-3.5 transition-transform ${v===Te.id?"rotate-180":""}`})]}),v===Te.id&&xe.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:xe.map(et=>e.jsx(mU,{item:et,onClick:()=>w(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"},et.id))})]},Te.id)}return e.jsx(mU,{item:Te,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${$?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Te.id)}),h.length>0&&e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname.startsWith("/homes-for-sale-in-")?$?"bg-white/15 text-white":"bg-gray-100 text-gray-900":$?"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(Wi,{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:h.map(Te=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Te.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:Te.city_name},Te.city_slug))})]}),S?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Yn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${$?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(ci,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Yn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${$?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Di,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Be=T==null?void 0:T.name)==null?void 0:Be.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 ${$?"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 ${$?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(vr,{className:"h-5 w-5"}):e.jsx(G4,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${$?"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:[X.map(Te=>e.jsx(Yn,{to:Te.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===Te.to?$?"bg-white/15 text-white":"bg-gray-100 text-gray-900":$?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Te.label},Te.to)),Q&&Z.map(Te=>{if(Te.item_type==="dropdown"){const xe=re(Te.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 ${$?"text-white/40":"text-gray-400"}`,children:Te.label}),xe.map(et=>e.jsx(mU,{item:et,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${$?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},et.id))]},Te.id)}return e.jsx(mU,{item:Te,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${$?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Te.id)}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${$?"text-white/40":"text-gray-400"}`,children:"Cities"}),h.map(Te=>e.jsx(Yn,{to:`/homes-for-sale-in-${Te.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${Te.city_slug}`?$?"bg-white/15 text-white":"bg-gray-100 text-gray-900":$?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Te.city_name},Te.city_slug))]}),S?e.jsxs(e.Fragment,{children:[e.jsx(Yn,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${$?"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 ${$?"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 ${$?"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}),!R&&e.jsx("footer",{className:"bg-gray-950 text-gray-400",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((De=t.agent)==null?void 0:De.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:I,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:I}),e.jsx("p",{className:"text-sm text-gray-500",children:((Ae=t.agent)==null?void 0:Ae.title)||"Real Estate Professional"})]})]}),((He=t.agent)==null?void 0:He.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(Cn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Le=t.agent)==null?void 0:Le.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.jsx("ul",{className:"space-y-3 text-sm",children:X.map(Te=>e.jsx("li",{children:e.jsx(Yn,{to:Te.to,className:"hover:text-white transition-colors",children:Te.label})},Te.to))})]}),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:"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(Yn,{to:"/contact",className:"inline-block px-5 py-2.5 bg-white text-gray-900 text-sm font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-12 w-auto object-contain"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-500 mb-3",children:[e.jsxs("span",{children:[I," · ",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()," ",I,". Powered by LevelUp."]})]})]})]})}),!R&&((Ie=t.agent)==null?void 0:Ie.avatar_url)&&e.jsx(X7s,{agent:t.agent}),l&&e.jsx(WEe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(jAe,{slug:t.subdomainSlug}),e.jsx(NAe,{slug:t.subdomainSlug}),e.jsx(SAe,{slug:t.subdomainSlug})]})}function X7s({agent:s}){var a;const[t,r]=k.useState(!1),n=br();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:t?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(Cn,{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),n("/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:"Send a Message"})]})]}),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(vr,{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:(a=s.full_name)==null?void 0:a.split(" ")[0]}),e.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function mU({item:s,className:t,onClick:r}){const n=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:t,onClick:r,children:s.label}):e.jsx(Yn,{to:n,className:t,onClick:r,children:s.label})}function Q7s({children:s,siteConfig:t}){var ie,ye,ce,ve,be,Ue,Be;const r=ec(),n=br(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[h,m]=k.useState([]),[x,y]=k.useState(!1),v=k.useRef(null),{user:w,profile:b,signOut:N}=Kxe();ZEe(t,w==null?void 0:w.id),XEe(t,w==null?void 0:w.id);const S=((ie=t.agent)==null?void 0:ie.full_name)||"Agent",T=t.siteTitle||`${S} Real Estate`,A=t.brokerageLegalName?`${S} | ${t.brokerageLegalName}`:S,I=De=>{if(!De)return De;const Ae=S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),He=new RegExp(`^\\s*${Ae}\\s*[|\\-–—:]\\s*`,"i");return De.replace(He,"").trim()},D=T&&T!==`${S} Real Estate`?T:null,R=D?I(D):null,$=R&&R.toLowerCase()!==S.toLowerCase()?R:null,F=r.pathname==="/search",z=r.pathname==="/",Q=t.leadRegistrationMode!=="disabled",K="#c9a96e";k.useEffect(()=>{const De=()=>y(window.scrollY>80);return window.addEventListener("scroll",De,{passive:!0}),()=>window.removeEventListener("scroll",De)},[]),k.useEffect(()=>{(async()=>{const{data:Ae}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});m(Ae||[])})()},[t.id]),k.useEffect(()=>{const De=Ae=>{v.current&&!v.current.contains(Ae.target)&&d(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[]);const X=[{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"}],Z=t.siteTitle||`${S} - Real Estate`,re=t.siteTagline||`Browse homes and listings with ${S}`,le=t.ogImageUrl||((ye=t.agent)==null?void 0:ye.avatar_url)||"",oe=`https://${t.subdomainSlug||""}.thelocalmove.com`,ne=z?x?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${F?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(KEe,{siteConfig:t,pagePath:r.pathname}),e.jsx(YEe,{siteConfig:t}),e.jsxs(nl,{children:[e.jsx("title",{children:Z}),e.jsx("meta",{name:"description",content:re}),e.jsx("meta",{property:"og:title",content:Z}),e.jsx("meta",{property:"og:description",content:re}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:oe+r.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:Z}),e.jsx("meta",{name:"twitter:description",content:re}),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:`${oe}${r.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:`${z?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${ne}`,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(Yn,{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:A}),$&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:$})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[X.map(De=>e.jsx(Yn,{to:De.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===De.to?"text-white":"text-white/40 hover:text-white"}`,children:De.label},De.to)),h.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 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(Wi,{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:h.map(De=>e.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${De.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:De.city_name},De.city_slug))})]}),w?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Yn,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Yn,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(Di,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((ce=b==null?void 0:b.name)==null?void 0:ce.split(" ")[0])||"Account"})]})]}):Q?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]}),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(vr,{className:"h-5 w-5"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-6 h-px bg-current"}),e.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),e.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),e.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),a&&e.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:e.jsxs("div",{className:"px-6 py-4 space-y-1",children:[X.map(De=>e.jsx(Yn,{to:De.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===De.to?"text-white":"text-white/40 hover:text-white"}`,children:De.label},De.to)),h.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"}),h.map(De=>e.jsx(Yn,{to:`/homes-for-sale-in-${De.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:De.city_name},De.city_slug))]}),w?e.jsxs(e.Fragment,{children:[e.jsx(Yn,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await N(),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"})]}):Q?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}),!F&&e.jsx("footer",{className:"bg-[#0a0908] text-white/30 border-t border-white/5",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-6",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:S}),e.jsx("p",{className:"text-white/20 text-xs tracking-[0.15em] uppercase mb-6",children:((ve=t.agent)==null?void 0:ve.title)||"Real Estate Professional"}),((be=t.agent)==null?void 0:be.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/30 hover:text-white transition-colors mb-3",children:[e.jsx(Cn,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Ue=t.agent)==null?void 0:Ue.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-3 text-sm text-white/30 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",style:{color:K},children:"Quick Links"}),e.jsx("ul",{className:"space-y-3",children:X.map(De=>e.jsx("li",{children:e.jsx(Yn,{to:De.to,className:"text-xs tracking-wider uppercase text-white/30 hover:text-white transition-colors",children:De.label})},De.to))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6",style:{color:K},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/20 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsx(Yn,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/15 text-white/50 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/5",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-40"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[10px] text-white/15 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[S," · ",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-6 w-auto flex-shrink-0 mt-0.5 opacity-30"}),e.jsx("p",{className:"text-[10px] text-white/15 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-white/15 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()," ",S,". Powered by LevelUp."]})]})]})]})}),!F&&((Be=t.agent)==null?void 0:Be.avatar_url)&&e.jsx(J7s,{agent:t.agent,accentColor:K}),l&&e.jsx(WEe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:K}),e.jsx(jAe,{slug:t.subdomainSlug}),e.jsx(NAe,{slug:t.subdomainSlug}),e.jsx(SAe,{slug:t.subdomainSlug})]})}function J7s({agent:s,accentColor:t}){var i;const[r,n]=k.useState(!1),a=br();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:r?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/30 text-[10px] tracking-[0.1em] uppercase",children:s.title||"Real Estate Professional"})]})]}),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/50 hover:text-white transition-colors tracking-wider",children:[e.jsx(Cn,{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/50 hover:text-white transition-colors tracking-wider",children:[e.jsx(Vs,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{n(!1),a("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:t},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>n(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx(vr,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>n(!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:(i=s.full_name)==null?void 0:i.split(" ")[0]}),e.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:t},children:"Let's connect →"})]})]})}):null}const jD="#2c1810",w0="#b8860b";function e9s({children:s,siteConfig:t}){var $,F,z;const r=ec();br();const[n,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,h]=k.useState([]),[m,x]=k.useState(!1),y=k.useRef(null),{user:v,profile:w,signOut:b}=Kxe();ZEe(t,v==null?void 0:v.id),XEe(t,v==null?void 0:v.id);const N=(($=t.agent)==null?void 0:$.full_name)||"Agent",S=t.siteTitle||`${N} Land & Ranch`,T=r.pathname==="/",A=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{const Q=()=>x(window.scrollY>80);return window.addEventListener("scroll",Q,{passive:!0}),()=>window.removeEventListener("scroll",Q)},[]),k.useEffect(()=>{(async()=>{const{data:K}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");K&&h(K)})()},[t.id]),k.useEffect(()=>{const Q=K=>{y.current&&!y.current.contains(K.target)&&c(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[]);const I=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],D=m||!T?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",R=m||!T?jD:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(nl,{children:[e.jsx("title",{children:S}),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(KEe,{siteConfig:t}),e.jsx(YEe,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${D}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(Yn,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(hA,{className:"w-7 h-7",style:{color:w0}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:R,fontFamily:"'Playfair Display', Georgia, serif"},children:S})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[I.map(Q=>e.jsx(Yn,{to:Q.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===Q.path?w0:R},children:Q.label},Q.path)),d.length>0&&e.jsxs("div",{ref:y,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:R},children:["Areas ",e.jsx(Wi,{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(Q=>e.jsx(Yn,{to:`/homes-for-sale-in-${Q.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:jD},onClick:()=>c(!1),children:Q.city_name},Q.city_slug))})]}),v?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Yn,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:w0,color:R},children:[e.jsx(Di,{className:"w-4 h-4 inline mr-1.5"}),(w==null?void 0:w.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:w0},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!n),className:"md:hidden p-2",style:{color:R},children:n?e.jsx(vr,{className:"w-6 h-6"}):e.jsx(G4,{className:"w-6 h-6"})})]})}),n&&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:[I.map(Q=>e.jsx(Yn,{to:Q.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===Q.path?w0:jD},onClick:()=>a(!1),children:Q.label},Q.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(Q=>e.jsx(Yn,{to:`/homes-for-sale-in-${Q.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:jD},onClick:()=>a(!1),children:Q.city_name},Q.city_slug))]}),!v&&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:w0},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:jD},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(hA,{className:"w-6 h-6",style:{color:w0}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:S})]}),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:I.map(Q=>e.jsx(Yn,{to:Q.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:Q.label},Q.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(Cn,{className:"w-4 h-4",style:{color:w0}}),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:w0}}),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()," ",S,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:w0}})]})]})}),i&&e.jsx(WEe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(jAe,{slug:t.subdomainSlug}),e.jsx(NAe,{slug:t.subdomainSlug}),e.jsx(SAe,{slug:t.subdomainSlug})]})}const t9s=k.lazy(()=>ti(()=>import("./LeadSiteHome-ec3qAj_Q.js"),__vite__mapDeps([0,1,2,3]))),s9s=k.lazy(()=>ti(()=>import("./LeadSiteLuxuryHome-DrnzzQEg.js"),__vite__mapDeps([4,2,3]))),r9s=k.lazy(()=>ti(()=>import("./LeadSiteLandRanchHome-7jEZ9ezW.js"),__vite__mapDeps([5,1,2,3]))),n9s=k.lazy(()=>ti(()=>import("./LeadSiteSearch-CrwVeaPd.js"),__vite__mapDeps([6,1,7,3,8]))),a9s=k.lazy(()=>ti(()=>import("./LeadSiteLuxurySearch-7Ea0kAGE.js"),__vite__mapDeps([9,1,7,3,8]))),i9s=k.lazy(()=>ti(()=>import("./LeadSiteListingDetail-Dz9FwDP1.js"),__vite__mapDeps([10,11,3,12]))),o9s=k.lazy(()=>ti(()=>import("./LeadSiteLuxuryListingDetail-LpgCCRWo.js"),__vite__mapDeps([13,11,3,12]))),l9s=k.lazy(()=>ti(()=>import("./LeadSiteAbout-CyKHYlwe.js"),[])),c9s=k.lazy(()=>ti(()=>import("./LeadSiteLuxuryAbout-CF41-_kj.js"),[])),d9s=k.lazy(()=>ti(()=>import("./LeadSiteContact-B6GX3b-y.js"),[])),u9s=k.lazy(()=>ti(()=>import("./LeadSiteLuxuryContact-hfRPw5jg.js"),[])),h9s=k.lazy(()=>ti(()=>import("./LeadSiteConsumerDashboard-XxirV81j.js"),[])),sGe=k.lazy(()=>ti(()=>import("./LeadSiteBlog-BnrX_9j8.js"),[])),m9s=k.lazy(()=>ti(()=>import("./LeadSiteCommunity-2DUJ861B.js"),[])),f9s=k.lazy(()=>ti(()=>import("./LeadSiteSellers-Cmj0J3Xu.js"),[])),p9s=k.lazy(()=>ti(()=>import("./LeadSiteCityPage-C1Ttrb3-.js"),__vite__mapDeps([14,3,8]))),x9s=k.lazy(()=>ti(()=>import("./LeadSiteSubdivisionPage-7VxqiHOy.js"),__vite__mapDeps([15,3]))),g9s=k.lazy(()=>ti(()=>import("./LeadSiteCustomPage-C-zf6-sG.js"),[]));function y9s(){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 v9s(){const{siteConfig:s,themeConfig:t,isLoading:r,error:n}=kOs();if(r)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(n||!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?e9s:a?Q7s:Z7s,o=i?e.jsx(r9s,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(s9s,{siteConfig:s,themeConfig:t??void 0}):e.jsx(t9s,{siteConfig:s,themeConfig:t??void 0});return e.jsx(COs,{siteConfig:s,children:e.jsx(l,{siteConfig:s,children:e.jsx(k.Suspense,{fallback:e.jsx(y9s,{}),children:e.jsxs(xde,{children:[e.jsx(ds,{path:"/",element:o}),e.jsx(ds,{path:"/search",element:a?e.jsx(a9s,{siteConfig:s}):e.jsx(n9s,{siteConfig:s})}),e.jsx(ds,{path:"/listing/:mlsNumber",element:a?e.jsx(o9s,{siteConfig:s}):e.jsx(i9s,{siteConfig:s})}),e.jsx(ds,{path:"/about",element:a?e.jsx(c9s,{siteConfig:s}):e.jsx(l9s,{siteConfig:s})}),e.jsx(ds,{path:"/contact",element:a?e.jsx(u9s,{siteConfig:s}):e.jsx(d9s,{siteConfig:s})}),e.jsx(ds,{path:"/account",element:e.jsx(h9s,{siteConfig:s})}),e.jsx(ds,{path:"/blog",element:e.jsx(sGe,{siteConfig:s,isLuxury:a})}),e.jsx(ds,{path:"/blog/:slug",element:e.jsx(sGe,{siteConfig:s,isLuxury:a})}),e.jsx(ds,{path:"/sell",element:e.jsx(f9s,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(ds,{path:"/community",element:e.jsx(m9s,{siteConfig:s,isLuxury:a})}),e.jsx(ds,{path:"/p/:pageSlug",element:e.jsx(g9s,{siteConfig:s})}),e.jsx(ds,{path:"/*",element:e.jsx(b9s,{siteConfig:s,referralMode:(t==null?void 0:t.referralMode)===!0||!s.mlsProviderId})})]})})})})}function b9s({siteConfig:s,referralMode:t}){const r=ec(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return e.jsx(x9s,{siteConfig:s,subdivisionSlug:n[1]});const a=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(p9s,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}const _9s=({team:s,onSelect:t})=>{const{data:r}=mt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:n}=await V.from("team_members").select("user_id, role").eq("team_id",s.id),a=(n==null?void 0:n.length)||0,i=n==null?void 0:n.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await V.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(ke,{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(Dt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Nr,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Ge,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),(r==null?void 0:r.count)??"…"]})]})}),e.jsxs(Pe,{className:"space-y-3",children:[(r==null?void 0:r.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Nn,{className:"h-6 w-6",children:[e.jsx(ya,{src:r.leaderProfile.avatar_url||""}),e.jsx(kn,{className:"text-xs",children:(r.leaderProfile.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Zh,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),r.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(Wu,{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(Ge,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Ge,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Ge,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},w9s=()=>{const{user:s,isAdmin:t,isBrokerageManager:r,brokerageId:n,managedBrokerages:a,selectedBrokerageId:i}=js(),l=i||(a.length>0?a[0].id:n),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:h,updateTeam:m,deleteTeam:x,addMember:y,removeMember:v,updateMemberRole:w}=l5(o),[b,N]=k.useState(!1),[S,T]=k.useState(null),{data:A}=mt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:R,error:$}=await V.from("brokerages").select("id, name").order("name");if($)throw $;return R||[]},enabled:t}),{data:I}=mt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:R,error:$}=await V.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if($)throw $;return R||[]},enabled:!!l}),D=async R=>{const $=R.brokerage_id||l||null,F=await h.mutateAsync({name:R.name,brokerage_id:$,description:R.description});if(R.leaderId&&R.leaderId!=="none"&&await y.mutateAsync({team_id:F.id,user_id:R.leaderId,role:"team_leader"}),R.memberIds)for(const z of R.memberIds)await y.mutateAsync({team_id:F.id,user_id:z,role:"team_member"});N(!1)};return!r&&!t?e.jsx(ws,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pr,{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(ws,{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(G,{onClick:()=>N(!0),children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(Wot,{open:b,onOpenChange:N,onCreateTeam:D,isCreating:h.isPending,brokerageAgents:I||[],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(R=>e.jsx(ke,{children:e.jsxs(Pe,{className:"p-6",children:[e.jsx(Fs,{className:"h-5 w-32 mb-3"}),e.jsx(Fs,{className:"h-4 w-48 mb-4"}),e.jsx(Fs,{className:"h-8 w-full"})]})},R))}),!d&&c.length===0&&!S&&e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pr,{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(G,{onClick:()=>N(!0),children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!S&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(R=>e.jsx(_9s,{team:R,onSelect:()=>T(R)},R.id))}),S&&e.jsx(Got,{team:S,brokerageAgents:I||[],onBack:()=>T(null),onUpdate:R=>m.mutateAsync({id:S.id,...R}).then($=>T($)),onAddMember:(R,$)=>y.mutateAsync({team_id:S.id,user_id:R,role:$}),onRemoveMember:R=>v.mutateAsync({team_id:S.id,member_id:R}),onUpdateRole:(R,$)=>w.mutateAsync({team_id:S.id,member_id:R,role:$}),onDeleteTeam:()=>x.mutate(S.id),isUpdating:m.isPending,isAddingMember:y.isPending})]})})},j9s=()=>{const{data:s,isLoading:t}=yg(),{useTeamMembers:r}=l5(),{data:n=[],isLoading:a}=r((s==null?void 0:s.teamId)||"");if(t)return e.jsx(ws,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fs,{className:"h-8 w-48"}),e.jsx(Fs,{className:"h-40 w-full"})]})});if(!s)return e.jsx(ws,{title:"My Team",description:"Your team",children:e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pr,{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(ws,{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(Ge,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(Zh,{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(On,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Rn,{className:"flex-wrap",children:[e.jsx(Kt,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(Kt,{value:"contacts",children:[e.jsx(R4,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(Kt,{value:"lead-pond",children:[e.jsx(ky,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(Kt,{value:"shared-assets",children:[e.jsx(Qh,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(ts,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(Fs,{className:"h-16 w-full"},l))}):n.map(l=>{var o,c,d,h;return e.jsx(ke,{children:e.jsxs(Pe,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Nn,{className:"h-10 w-10",children:[e.jsx(ya,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(kn,{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:(h=l.profile)==null?void 0:h.email})]}),l.role==="team_leader"?e.jsxs(Ge,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(Zh,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Ge,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(ts,{value:"contacts",className:"space-y-4",children:e.jsx(m5e,{})}),i.lead_pond_enabled&&e.jsx(ts,{value:"lead-pond",className:"space-y-4",children:e.jsx(f5e,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(ts,{value:"shared-assets",className:"space-y-4",children:e.jsx(Hot,{teamId:s.teamId})})]})]})})};function N9s(){const{user:s}=js(),t=Xt(),r=mt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await V.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(N)throw N;return b},enabled:!!s}),n=mt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await V.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(N)throw N;return b},enabled:!!s}),a=mt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await V.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(N)throw N;return b},enabled:!!s}),i=mt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await V.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(N)throw N;return b},enabled:!!s}),l=mt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:N}=await V.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(N)throw N;return b},enabled:!!s}),o=Ct({mutationFn:async()=>{const{data:b,error:N}=await V.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(N)throw N;const S=[{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:T}=await V.from("agent_booking_types").insert(S.map(D=>({...D,user_id:s.id})));if(T)throw T;const A=[1,2,3,4,5].map(D=>({user_id:s.id,day_of_week:D,start_time:"09:00",end_time:"17:00"})),{error:I}=await V.from("agent_availability_slots").insert(A);if(I)throw I;return b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ue.success("Scheduler set up successfully!")},onError:b=>ue.error(b.message)}),c=Ct({mutationFn:async b=>{const{error:N}=await V.from("agent_booking_settings").update(b).eq("user_id",s.id);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ue.success("Settings updated")},onError:b=>ue.error(b.message)}),d=Ct({mutationFn:async b=>{const N={...b,user_id:s.id};if(b.id){const{error:S}=await V.from("agent_booking_types").update(N).eq("id",b.id);if(S)throw S}else{const{error:S}=await V.from("agent_booking_types").insert(N);if(S)throw S}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ue.success("Booking type saved")},onError:b=>ue.error(b.message)}),h=Ct({mutationFn:async b=>{const{error:N}=await V.from("agent_booking_types").delete().eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ue.success("Booking type deleted")},onError:b=>ue.error(b.message)}),m=Ct({mutationFn:async b=>{const N={...b,user_id:s.id};if(b.id){const{error:S}=await V.from("agent_availability_slots").update(N).eq("id",b.id);if(S)throw S}else{const{error:S}=await V.from("agent_availability_slots").insert(N);if(S)throw S}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>ue.error(b.message)}),x=Ct({mutationFn:async b=>{const{error:N}=await V.from("agent_availability_slots").delete().eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:b=>ue.error(b.message)}),y=Ct({mutationFn:async b=>{const{error:N}=await V.from("agent_blocked_dates").insert({...b,user_id:s.id});if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ue.success("Date blocked")},onError:b=>ue.error(b.message)}),v=Ct({mutationFn:async b=>{const{error:N}=await V.from("agent_blocked_dates").delete().eq("id",b);if(N)throw N},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:b=>ue.error(b.message)}),w=Ct({mutationFn:async({id:b,reason:N})=>{const{error:S}=await V.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:N}).eq("id",b);if(S)throw S},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ue.success("Booking cancelled")},onError:b=>ue.error(b.message)});return{settings:r.data,bookingTypes:n.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:r.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:h,upsertAvailability:m,deleteAvailability:x,addBlockedDate:y,removeBlockedDate:v,cancelBooking:w}}const rGe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function k9s({types:s,onSave:t,onDelete:r}){const[n,a]=k.useState(null),[i,l]=k.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=h=>{a({...h}),l(!0)},d=()=>{n!=null&&n.name&&(t(n),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Dt,{children:"Booking Types"}),e.jsx(Nr,{children:"The meeting types prospects can book with you"})]}),e.jsxs(G,{onClick:o,size:"sm",children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Pe,{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(h=>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:h.color+"20"},children:rGe[h.icon]||"📅"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:h.name}),!h.is_active&&e.jsx(Ge,{variant:"secondary",className:"text-xs",children:"Inactive"}),h.qualification_enabled&&e.jsxs(Ge,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(TR,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fn,{className:"h-3 w-3"}),h.duration_minutes," min",h.description&&e.jsxs("span",{children:["· ",h.description.slice(0,60),h.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>c(h),children:e.jsx(Ea,{className:"h-4 w-4"})}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>r(h.id),className:"text-destructive hover:text-destructive",children:e.jsx(yr,{className:"h-4 w-4"})})]})]},h.id))})})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsxs(gs,{children:[n!=null&&n.id?"Edit":"New"," Booking Type"]})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Name"}),e.jsx(Ne,{value:n.name||"",onChange:h=>a({...n,name:h.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:n.description||"",onChange:h=>a({...n,description:h.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(he,{children:"Duration (minutes)"}),e.jsx(Ne,{type:"number",min:15,max:180,step:15,value:n.duration_minutes||30,onChange:h=>a({...n,duration_minutes:parseInt(h.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:n.color||"#3B82F6",onChange:h=>a({...n,color:h.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(Ne,{value:n.color||"#3B82F6",onChange:h=>a({...n,color:h.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(rGe).map(([h,m])=>e.jsx("button",{onClick:()=>a({...n,icon:h}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${n.icon===h?"border-primary bg-primary/10":"hover:bg-muted"}`,children:m},h))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Meeting Link Override (optional)"}),e.jsx(Ne,{value:n.meeting_link_override||"",onChange:h=>a({...n,meeting_link_override:h.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(he,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(_r,{checked:n.qualification_enabled||!1,onCheckedChange:h=>a({...n,qualification_enabled:h})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(he,{children:"Active"}),e.jsx(_r,{checked:n.is_active??!0,onCheckedChange:h=>a({...n,is_active:h})})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:d,children:"Save"})]})]})})]})}const nGe=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function S9s({slots:s,onSave:t,onDelete:r}){const[n,a]=k.useState(null),[i,l]=k.useState("09:00"),[o,c]=k.useState("17:00"),d=nGe.map((m,x)=>s.filter(y=>y.day_of_week===x)),h=()=>{n!==null&&(t({day_of_week:n,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(fn,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Nr,{children:"Set your available hours for each day"})]}),e.jsx(Pe,{className:"space-y-2",children:nGe.map((m,x)=>{const y=d[x];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:m})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):y.map(v=>{var w,b;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(w=v.start_time)==null?void 0:w.slice(0,5),onBlur:N=>t({id:v.id,start_time:N.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(b=v.end_time)==null?void 0:b.slice(0,5),onBlur:N=>t({id:v.id,end_time:N.target.value})}),e.jsx(_r,{checked:v.is_active,onCheckedChange:N=>t({id:v.id,is_active:N})}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>r(v.id),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},v.id)}),n===x?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:v=>l(v.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(Ne,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:v=>c(v.target.value)}),e.jsx(G,{size:"sm",className:"h-8",onClick:h,children:"Add"}),e.jsx(G,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(G,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(x),children:[e.jsx($s,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},m)})})]})}const C9s={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 T9s({bookings:s,onCancel:t}){const r=s.filter(i=>i.status==="confirmed"&&new Date(i.booking_date)>=new Date(new Date().toDateString())),n=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(Di,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Ge,{className:`text-xs ${C9s[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(hd,{className:"h-3.5 w-3.5"}),_s(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fn,{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(Cn,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(Ge,{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(G,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Sc,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsx(Dt,{children:"Upcoming Bookings"}),e.jsxs(Nr,{children:[r.length," upcoming appointment",r.length!==1?"s":""]})]}),e.jsx(Pe,{children:r.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:r.map(i=>a(i,!0))})})]}),n.length>0&&e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{children:"Past & Cancelled"})}),e.jsx(Pe,{children:e.jsx("div",{className:"space-y-3",children:n.slice(0,20).map(i=>a(i))})})]})]})}function E9s({blockedDates:s,onAdd:t,onRemove:r}){const[n,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(ke,{children:[e.jsxs(Mt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(dR,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Nr,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Pe,{children:[n&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(Ne,{type:"date",value:i,onChange:h=>l(h.target.value),className:"w-40"}),e.jsx(Ne,{placeholder:"Reason (optional)",value:o,onChange:h=>c(h.target.value),className:"flex-1"}),e.jsx(G,{size:"sm",onClick:d,children:"Add"}),e.jsx(G,{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(h=>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:_s(new Date(h.blocked_date+"T00:00:00"),"MMM d, yyyy")}),h.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",h.reason,")"]}),e.jsx("button",{onClick:()=>r(h.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(vr,{className:"h-3.5 w-3.5"})})]},h.id))})]})]})}function A9s(){const{settings:s,bookingTypes:t,availability:r,blockedDates:n,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:h,deleteAvailability:m,addBlockedDate:x,removeBlockedDate:y,cancelBooking:v}=N9s(),[w,b]=k.useState("");k.useState(15),w||s!=null&&s.meeting_link;const N=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(ws,{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(ws,{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(hd,{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:[N&&e.jsxs(e.Fragment,{children:[e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(N),ue.success("Booking link copied!")},children:[e.jsx(Ra,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(G,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:N,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(_r,{id:"scheduler-active",checked:s.is_active,onCheckedChange:S=>o.mutate({is_active:S})})]})]})]}),e.jsxs(On,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Rn,{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(S=>S.status==="confirmed").length>0&&e.jsx(Ge,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(S=>S.status==="confirmed").length})]})]}),e.jsx(ts,{value:"types",children:e.jsx(k9s,{types:t,onSave:S=>c.mutate(S),onDelete:S=>d.mutate(S)})}),e.jsx(ts,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(S9s,{slots:r,onSave:S=>h.mutate(S),onDelete:S=>m.mutate(S)}),e.jsx(E9s,{blockedDates:n,onAdd:S=>x.mutate(S),onRemove:S=>y.mutate(S)})]})}),e.jsx(ts,{value:"settings",children:e.jsxs(ke,{children:[e.jsxs(Mt,{children:[e.jsxs(Dt,{className:"flex items-center gap-2",children:[e.jsx(zR,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Nr,{children:"Configure your booking page defaults"})]}),e.jsxs(Pe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(G,{variant:"outline",size:"sm",onClick:()=>{N&&(navigator.clipboard.writeText(N),ue.success("Copied!"))},children:e.jsx(Ra,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(he,{htmlFor:"meeting-link",children:[e.jsx(tl,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(Ne,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:S=>o.mutate({meeting_link:S.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(he,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:S=>o.mutate({buffer_minutes:parseInt(S.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:S=>o.mutate({min_notice_hours:parseInt(S.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(he,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:S=>o.mutate({max_advance_days:parseInt(S.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(ts,{value:"bookings",children:e.jsx(T9s,{bookings:a,onCancel:S=>v.mutate({id:S})})})]})]})}):e.jsx(ws,{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(hd,{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(ke,{children:e.jsxs(Pe,{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(S=>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:S.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:S.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:S.desc})]})]},S.title))}),e.jsx(fo,{}),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(G,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(jr,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const aGe=[{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 M9s(){const{user:s}=js(),t=sa(),{toast:r}=Ma(),n=br(),a=Xt(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,h]=k.useState(null),[m,x]=k.useState({title:"",description:"",page_type:"lead_capture"}),{data:y=[],isLoading:v}=mt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:S,error:T}=await V.from("landing_pages").select("*").eq("user_id",t).order("created_at",{ascending:!1});if(T)throw T;return S},enabled:!!t}),w=Ct({mutationFn:async()=>{const S=m.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:T}=await V.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=m.page_type==="just_listed"||m.page_type==="just_sold",{data:I,error:D}=await V.from("landing_pages").insert({user_id:t,title:m.title,description:m.description||null,page_type:m.page_type,slug:S,hero_headline:A?m.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":m.page_type==="lead_magnet"?"📥 Free Download":m.title,agent_name:(T==null?void 0:T.name)||null,agent_phone:(T==null?void 0:T.phone)||null,agent_email:(T==null?void 0:T.email)||s.email||null,agent_photo_url:(T==null?void 0:T.avatar_url)||null,property_status:A?m.page_type.replace("just_",""):null}).select().single();if(D)throw D;const R=I9s(m.page_type);if(R.length>0){const{error:$}=await V.from("landing_page_fields").insert(R.map((F,z)=>({...F,page_id:I.id,sort_order:z})));if($)throw $}return I},onSuccess:S=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),x({title:"",description:"",page_type:"lead_capture"}),r({title:"Landing page created!"}),n(`/mission-control/landing-pages/${S.id}`)},onError:S=>r({title:"Error",description:S.message,variant:"destructive"})}),b=Ct({mutationFn:async S=>{const{error:T}=await V.from("landing_pages").delete().eq("id",S);if(T)throw T},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),r({title:"Landing page deleted"})}}),N=S=>`https://pages.relevelup.com/${S}`;return e.jsxs(ws,{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(G,{onClick:()=>l(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," New Page"]})]}),v?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"})}):y.length===0?e.jsx(ke,{children:e.jsxs(Pe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ln,{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(G,{onClick:()=>l(!0),children:[e.jsx($s,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:y.map(S=>{var T;return e.jsx(ke,{className:"hover:shadow-md transition-shadow",children:e.jsx(Pe,{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:()=>n(`/mission-control/landing-pages/${S.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:S.title}),e.jsx(Ge,{variant:S.is_published?"default":"secondary",className:"text-[10px]",children:S.is_published?"Published":"Draft"}),e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:((T=aGe.find(A=>A.id===S.page_type))==null?void 0:T.label)||S.page_type})]}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:S.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(bn,{className:"h-3 w-3"})," ",S.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ln,{className:"h-3 w-3"})," ",S.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[S.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>h(N(S.slug)),children:e.jsx(ov,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(N(S.slug)),r({title:"Link copied!"})},children:e.jsx(Ra,{className:"h-3.5 w-3.5"})}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:N(S.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Qr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Fd,{children:[e.jsx(Bd,{asChild:!0,children:e.jsx(G,{size:"sm",variant:"ghost",children:e.jsx(Yx,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(Pa,{onClick:()=>n(`/mission-control/landing-pages/${S.id}`),children:[e.jsx(Ea,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Pa,{onClick:()=>c(S.id),className:"text-destructive",children:[e.jsx(yr,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},S.id)})})]}),e.jsx(fs,{open:i,onOpenChange:l,children:e.jsxs(ms,{children:[e.jsx(ys,{children:e.jsx(gs,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Page Title"}),e.jsx(Ne,{value:m.title,onChange:S=>x(T=>({...T,title:S.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description (optional)"}),e.jsx(or,{value:m.description,onChange:S=>x(T=>({...T,description:S.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Page Template"}),e.jsxs(Is,{value:m.page_type,onValueChange:S=>x(T=>({...T,page_type:S})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:aGe.map(S=>e.jsx(ct,{value:S.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:S.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.description})]})},S.id))})]})]})]}),e.jsxs(an,{children:[e.jsx(G,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{onClick:()=>w.mutate(),disabled:!m.title.trim()||w.isPending,children:w.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Ko,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Do,{children:[e.jsxs(Ro,{children:[e.jsx(Fo,{children:"Delete Landing Page?"}),e.jsx(Bo,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Oo,{children:[e.jsx(zo,{children:"Cancel"}),e.jsx(Co,{onClick:()=>o&&b.mutate(o),children:"Delete"})]})]})}),e.jsx(fs,{open:!!d,onOpenChange:()=>h(null),children:e.jsxs(ms,{className:"max-w-sm",children:[e.jsx(ys,{children:e.jsx(gs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(GB,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),r({title:"URL copied!"}))},children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function I9s(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}]}}const L9s=[{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 P9s=0;const iGe=()=>`f_${Date.now()}_${++P9s}`;function D9s({field:s,index:t,updateField:r,removeField:n}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=jpe({id:s.clientId}),h={transform:Oj.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(ke,{ref:l,style:h,children:e.jsx(Pe,{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(vu,{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(he,{className:"text-xs",children:"Field Type"}),e.jsxs(Is,{value:s.field_type,onValueChange:m=>r(t,{field_type:m}),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsx(Ms,{children:L9s.map(m=>e.jsx(ct,{value:m.value,children:m.label},m.value))})]})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Label"}),e.jsx(Ne,{value:s.label,onChange:m=>r(t,{label:m.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Placeholder"}),e.jsx(Ne,{value:s.placeholder||"",onChange:m=>r(t,{placeholder:m.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(he,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(Ne,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:m=>r(t,{options:JSON.stringify(m.target.value.split(",").map(x=>x.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_r,{checked:s.is_required,onCheckedChange:m=>r(t,{is_required:m})}),e.jsx(he,{className:"text-xs",children:"Required"})]})]}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>n(t),children:e.jsx(yr,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function R9s(){const{pageId:s}=Ki(),t=br(),{user:r}=js(),n=sa(),{toast:a}=Ma(),i=Xt(),[l,o]=k.useState(null),[c,d]=k.useState(!1),{data:h,isLoading:m}=mt({queryKey:["landing-page",s],queryFn:async()=>{const{data:ne,error:ie}=await V.from("landing_pages").select("*").eq("id",s).single();if(ie)throw ie;return ne},enabled:!!s}),{data:x=[],isLoading:y}=mt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:ne,error:ie}=await V.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ie)throw ie;return ne},enabled:!!s}),{data:v=[]}=mt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:ne,error:ie}=await V.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ie)throw ie;return ne},enabled:!!s}),{data:w=[]}=mt({queryKey:["my-listings-for-pages",n],queryFn:async()=>{const{data:ne,error:ie}=await V.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",n).order("created_at",{ascending:!1});if(ie)throw ie;return ne},enabled:!!r&&((h==null?void 0:h.page_type)==="just_listed"||(h==null?void 0:h.page_type)==="just_sold")}),[b,N]=k.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"]}),[S,T]=k.useState([]);k.useEffect(()=>{h&&N({title:h.title,hero_headline:h.hero_headline,hero_subtext:h.hero_subtext||"",hero_image_url:h.hero_image_url,logo_url:h.logo_url,primary_color:h.primary_color,accent_color:h.accent_color,agent_name:h.agent_name||"",agent_phone:h.agent_phone||"",agent_email:h.agent_email||"",agent_photo_url:h.agent_photo_url,success_message:h.success_message||"Thank you! We'll be in touch soon.",is_published:h.is_published,description:h.description||"",lead_magnet_file_url:h.lead_magnet_file_url||null,lead_magnet_file_name:h.lead_magnet_file_name||null,lead_magnet_external_url:h.lead_magnet_external_url||null,listing_id:h.listing_id||null,property_address:h.property_address||"",property_price:h.property_price||"",property_beds:h.property_beds||"",property_baths:h.property_baths||"",property_sqft:h.property_sqft||"",property_description:h.property_description||"",property_photos:Array.isArray(h.property_photos)?h.property_photos:[],property_status:h.property_status||"just_listed",theme_style:h.theme_style||"premium",eyebrow:h.eyebrow||"",headline_accent:h.headline_accent||"",heading_font:h.heading_font||"playfair",trust_pills:Array.isArray(h.trust_pills)?h.trust_pills:["No obligation","100% free","60 seconds or less"]})},[h]),k.useEffect(()=>{x.length>0&&T(x.map(ne=>({id:ne.id,clientId:ne.id||iGe(),field_type:ne.field_type,label:ne.label,placeholder:ne.placeholder,is_required:ne.is_required,options:typeof ne.options=="string"?ne.options:ne.options?JSON.stringify(ne.options):null,sort_order:ne.sort_order})))},[x]);const A=Ct({mutationFn:async()=>{const{error:ne}=await V.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,updated_at:new Date().toISOString()}).eq("id",s);if(ne)throw ne;if(await V.from("landing_page_fields").delete().eq("page_id",s),S.length>0){const{error:ie}=await V.from("landing_page_fields").insert(S.map((ye,ce)=>({page_id:s,field_type:ye.field_type,label:ye.label,placeholder:ye.placeholder||null,is_required:ye.is_required,options:ye.options?JSON.parse(ye.options):null,sort_order:ce})));if(ie)throw ie}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:ne=>a({title:"Error",description:ne.message,variant:"destructive"})}),I=async(ne,ie)=>{const ye=ne.name.split(".").pop(),ce=`landing-pages/${r.id}/${ie}-${Date.now()}.${ye}`,{error:ve}=await V.storage.from("recruit-landing").upload(ce,ne);if(ve)throw ve;const{data:{publicUrl:be}}=V.storage.from("recruit-landing").getPublicUrl(ce);return be},D=async(ne,ie)=>{var ce;const ye=(ce=ne.target.files)==null?void 0:ce[0];if(ye){o(ie);try{const ve=await I(ye,ie);N(be=>({...be,[ie]:ve})),a({title:"Image uploaded!"})}catch(ve){a({title:"Upload failed",description:ve.message,variant:"destructive"})}finally{o(null)}}},R=async ne=>{var ye;const ie=(ye=ne.target.files)==null?void 0:ye[0];if(ie){o("lead_magnet");try{const ce=await I(ie,"lead-magnet");N(ve=>({...ve,lead_magnet_file_url:ce,lead_magnet_file_name:ie.name})),a({title:"File uploaded!"})}catch(ce){a({title:"Upload failed",description:ce.message,variant:"destructive"})}finally{o(null)}}},$=async ne=>{const ie=ne.target.files;if(!(!ie||ie.length===0)){o("property_photos");try{const ye=[];for(const ce of Array.from(ie)){const ve=await I(ce,"property-photo");ye.push(ve)}N(ce=>({...ce,property_photos:[...ce.property_photos,...ye]})),a({title:`${ye.length} photo(s) uploaded!`})}catch(ye){a({title:"Upload failed",description:ye.message,variant:"destructive"})}finally{o(null)}}},F=async ne=>{const ie=w.find(ce=>ce.id===ne);if(!ie)return;const{data:ye}=await V.from("listing_photos").select("photo_url").eq("listing_id",ne).order("sort_order");N(ce=>({...ce,listing_id:ne,property_address:ie.property_address||`${ie.city}, ${ie.state}`,property_price:ie.price?`$${ie.price.toLocaleString()}`:"",property_beds:ie.bedrooms?String(ie.bedrooms):"",property_baths:ie.bathrooms?String(ie.bathrooms):"",property_sqft:ie.square_footage?ie.square_footage.toLocaleString():"",property_description:ie.description||"",property_photos:(ye==null?void 0:ye.map(ve=>ve.photo_url))||ce.property_photos})),a({title:"Listing data imported!"})},z=()=>{T(ne=>[...ne,{clientId:iGe(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:ne.length}])},Q=(ne,ie)=>{T(ye=>ye.map((ce,ve)=>ve===ne?{...ce,...ie}:ce))},K=ne=>{T(ie=>ie.filter((ye,ce)=>ce!==ne))},X=fpe($M(tL,{activationConstraint:{distance:6}}),$M(gpe,{coordinateGetter:xlt})),Z=ne=>{const{active:ie,over:ye}=ne;!ye||ie.id===ye.id||T(ce=>{const ve=ce.findIndex(Ue=>Ue.clientId===ie.id),be=ce.findIndex(Ue=>Ue.clientId===ye.id);return ve<0||be<0?ce:_pe(ce,ve,be).map((Ue,Be)=>({...Ue,sort_order:Be}))})},re=h?`https://pages.relevelup.com/${h.slug}`:"",le=(h==null?void 0:h.page_type)==="lead_magnet",oe=(h==null?void 0:h.page_type)==="just_listed"||(h==null?void 0:h.page_type)==="just_sold";return m||y?e.jsx(ws,{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"})})}):h?e.jsxs(ws,{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(G,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:b.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Ge,{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(bn,{className:"h-3 w-3"})," ",h.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"})," ",v.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(G,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(ov,{className:"h-3.5 w-3.5"})}),e.jsxs(G,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(re),a({title:"Link copied!"})},children:[e.jsx(Ra,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(G,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:re,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Qr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(G,{onClick:()=>A.mutate(),disabled:A.isPending,children:[e.jsx(Bl,{className:"h-4 w-4 mr-2"}),A.isPending?"Saving...":"Save"]})]})]}),e.jsxs(On,{defaultValue:"design",children:[e.jsxs(Rn,{children:[e.jsx(Kt,{value:"design",children:"Design"}),le&&e.jsx(Kt,{value:"lead_magnet",children:"Lead Magnet"}),oe&&e.jsx(Kt,{value:"property",children:"Property Details"}),e.jsxs(Kt,{value:"fields",children:["Form Fields (",S.length,")"]}),e.jsxs(Kt,{value:"submissions",children:["Submissions (",v.length,")"]}),e.jsx(Kt,{value:"settings",children:"Settings"})]}),e.jsxs(ts,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Page Details"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Page Title (internal)"}),e.jsx(Ne,{value:b.title,onChange:ne=>N(ie=>({...ie,title:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description (internal)"}),e.jsx(Ne,{value:b.description,onChange:ne=>N(ie=>({...ie,description:ne.target.value}))})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Ge,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Pe,{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(he,{children:"Theme Style"}),e.jsxs(Is,{value:b.theme_style,onValueChange:ne=>N(ie=>({...ie,theme_style:ne})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(ct,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Headline Font"}),e.jsxs(Is,{value:b.heading_font,onValueChange:ne=>N(ie=>({...ie,heading_font:ne})),children:[e.jsx(As,{children:e.jsx(Ls,{})}),e.jsxs(Ms,{children:[e.jsx(ct,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(ct,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(ct,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(ct,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(Ne,{value:b.trust_pills.join(", "),onChange:ne=>N(ie=>({...ie,trust_pills:ne.target.value.split(",").map(ye=>ye.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(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Pe,{className:"space-y-4",children:[b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(he,{children:"Eyebrow (small label above headline)"}),e.jsx(Ne,{value:b.eyebrow,onChange:ne=>N(ie=>({...ie,eyebrow:ne.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Headline"}),e.jsx(Ne,{value:b.hero_headline,onChange:ne=>N(ie=>({...ie,hero_headline:ne.target.value})),placeholder:"What Is Your Home"})]}),b.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(he,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(Ne,{value:b.headline_accent,onChange:ne=>N(ie=>({...ie,headline_accent:ne.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Subtext"}),e.jsx(or,{value:b.hero_subtext,onChange:ne=>N(ie=>({...ie,hero_subtext:ne.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(he,{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(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),l==="hero_image_url"?"Uploading...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>D(ne,"hero_image_url")})]}),b.hero_image_url&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>N(ne=>({...ne,hero_image_url:null})),children:e.jsx(yr,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Branding"})}),e.jsxs(Pe,{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(he,{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(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>D(ne,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(he,{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(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>D(ne,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{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:ne=>N(ie=>({...ie,primary_color:ne.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:b.primary_color,onChange:ne=>N(ie=>({...ie,primary_color:ne.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(he,{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:ne=>N(ie=>({...ie,accent_color:ne.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(Ne,{value:b.accent_color,onChange:ne=>N(ie=>({...ie,accent_color:ne.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Pe,{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(he,{children:"Name"}),e.jsx(Ne,{value:b.agent_name,onChange:ne=>N(ie=>({...ie,agent_name:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Phone"}),e.jsx(Ne,{value:b.agent_phone,onChange:ne=>N(ie=>({...ie,agent_phone:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Email"}),e.jsx(Ne,{value:b.agent_email,onChange:ne=>N(ie=>({...ie,agent_email:ne.target.value}))})]})]})})]})]}),le&&e.jsx(ts,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ya,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Pe,{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(he,{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(Ge,{variant:"outline",className:"gap-1",children:[e.jsx(Ya,{className:"h-3 w-3"})," ",b.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:R})]}),b.lead_magnet_file_url&&e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>N(ne=>({...ne,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(yr,{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(he,{className:"flex items-center gap-1",children:[e.jsx(tl,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(Ne,{value:b.lead_magnet_external_url||"",onChange:ne=>N(ie=>({...ie,lead_magnet_external_url:ne.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),oe&&e.jsxs(ts,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsxs(Dt,{className:"text-base flex items-center gap-2",children:[e.jsx(En,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(Is,{value:b.listing_id||"",onValueChange:ne=>F(ne),children:[e.jsx(As,{children:e.jsx(Ls,{placeholder:"Select a listing to import..."})}),e.jsx(Ms,{children:w.map(ne=>{var ie;return e.jsxs(ct,{value:ne.id,children:[ne.property_address||`${ne.city}, ${ne.state}`," — $",(ie=ne.price)==null?void 0:ie.toLocaleString()]},ne.id)})})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Property Information"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Property Address"}),e.jsx(Ne,{value:b.property_address,onChange:ne=>N(ie=>({...ie,property_address:ne.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Price"}),e.jsx(Ne,{value:b.property_price,onChange:ne=>N(ie=>({...ie,property_price:ne.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Beds"}),e.jsx(Ne,{value:b.property_beds,onChange:ne=>N(ie=>({...ie,property_beds:ne.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Baths"}),e.jsx(Ne,{value:b.property_baths,onChange:ne=>N(ie=>({...ie,property_baths:ne.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Sq Ft"}),e.jsx(Ne,{value:b.property_sqft,onChange:ne=>N(ie=>({...ie,property_sqft:ne.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(he,{children:"Description"}),e.jsx(or,{value:b.property_description,onChange:ne=>N(ie=>({...ie,property_description:ne.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Property Photos"})}),e.jsxs(Pe,{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((ne,ie)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ne,alt:`Property ${ie+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(G,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>N(ye=>({...ye,property_photos:ye.property_photos.filter((ce,ve)=>ve!==ie)})),children:e.jsx(yr,{className:"h-3 w-3"})})]},ie))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(G,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(da,{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:$})]})]})]})]}),e.jsxs(ts,{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(G,{size:"sm",onClick:z,children:[e.jsx($s,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),S.length===0?e.jsx(ke,{children:e.jsx(Pe,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(bpe,{sensors:X,collisionDetection:ppe,onDragEnd:Z,children:e.jsx(wpe,{items:S.map(ne=>ne.clientId),strategy:Ots,children:e.jsx("div",{className:"space-y-3",children:S.map((ne,ie)=>e.jsx(D9s,{field:ne,index:ie,updateField:Q,removeField:K},ne.clientId))})})})]}),e.jsx(ts,{value:"submissions",className:"mt-4",children:v.length===0?e.jsx(ke,{children:e.jsx(Pe,{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:v.map(ne=>e.jsx(ke,{children:e.jsx(Pe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:ne.contact_name||"Anonymous"}),ne.synced_to_crm&&e.jsx(Ge,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[ne.contact_email&&e.jsx("span",{className:"mr-3",children:ne.contact_email}),ne.contact_phone&&e.jsx("span",{children:ne.contact_phone})]}),ne.answers&&typeof ne.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(ne.answers).map(([ie,ye])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ie,":"]})," ",e.jsx("span",{children:String(ye)})]},ie))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(ne.created_at).toLocaleDateString()})]})})},ne.id))})}),e.jsxs(ts,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Publishing"})}),e.jsxs(Pe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(he,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(_r,{checked:b.is_published,onCheckedChange:ne=>N(ie=>({...ie,is_published:ne}))})]}),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:re})]})]})]}),e.jsxs(ke,{children:[e.jsx(Mt,{children:e.jsx(Dt,{className:"text-base",children:"Thank You Message"})}),e.jsx(Pe,{children:e.jsx(or,{value:b.success_message,onChange:ne=>N(ie=>({...ie,success_message:ne.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(fs,{open:c,onOpenChange:d,children:e.jsxs(ms,{className:"max-w-sm",children:[e.jsx(ys,{children:e.jsx(gs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(GB,{value:re,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:re})]})]})})]}):e.jsx(ws,{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(G,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}function O9s(){return mt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await V.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function Qxe(){const{user:s}=js();return mt({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:r}=await V.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(r)throw r;return t||[]},enabled:!!(s!=null&&s.id)})}function Jxe(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async({app_slug:r,enabled:n})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await V.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:r,enabled:n},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),ue.success(n.enabled?"App installed":"App turned off")},onError:r=>ue.error(r.message||"Failed to update app")})}const F9s={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"}},B9s={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 z9s(){const s=br(),{data:t=[],isLoading:r}=O9s(),{data:n=[]}=Qxe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=_g(),o=Jxe(),[c,d]=k.useState(!1),h=x=>{var y;return((y=n.find(v=>v.app_slug===x))==null?void 0:y.enabled)??!1},m=x=>n.some(y=>y.app_slug===x);return e.jsxs(ws,{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(Ku,{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(jr,{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(G,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(rf,{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(ke,{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(fc,{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(Ge,{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(Qr,{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(Qr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(ke,{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(W1,{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.'})]})]})})]}),r?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(x=>{const y=Pme[x.icon||"Sparkles"]||jr,v=h(x.slug),w=m(x.slug),b=x.status==="coming_soon",N=F9s[x.slug]||B9s;return e.jsxs(ke,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${N.ring} hover:ring-2 transition-all hover:shadow-xl ${b?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${N.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 ${N.iconBg} ${N.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(y,{className:"w-7 h-7"})}),b?e.jsx(Ge,{variant:"secondary",children:"Coming soon"}):v?e.jsxs(Ge,{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"]}):w?e.jsx(Ge,{variant:"outline",children:"Paused"}):e.jsx(Ge,{className:N.chip+" hover:"+N.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:x.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x.description})]}),!b&&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(_r,{checked:v,onCheckedChange:S=>o.mutate({app_slug:x.slug,enabled:S})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:v?"On":"Off"})]}),e.jsxs(G,{size:"sm",className:`bg-gradient-to-r ${N.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${x.slug}`),children:[e.jsx(oo,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(Ha,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},x.id)})})]}),e.jsx(fs,{open:c,onOpenChange:d,children:e.jsxs(ms,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(ys,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(gs,{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 o_e={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 $9s(){const{user:s}=js();return mt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return o_e;const{data:t,error:r}=await V.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return t?{...o_e,...t}:o_e},enabled:!!(s!=null&&s.id)})}function U9s(){const{user:s}=js(),t=Xt();return Ct({mutationFn:async r=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:n}=await V.from("video_greeter_configs").upsert({user_id:s.id,...r},{onConflict:"user_id"});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ue.success("Saved")},onError:r=>ue.error(r.message||"Failed to save")})}function q9s({label:s,value:t,onChange:r,thumbnailUrl:n,placeholder:a="https://...",hint:i}){const l=k.useRef(null),[o,c]=k.useState(!1),d=async h=>{var x;const m=(x=h.target.files)==null?void 0:x[0];if(m){if(!m.type.startsWith("video/")){ue.error("Please select a video file");return}if(m.size>50*1024*1024){ue.error("Video must be under 50MB");return}c(!0);try{const y=m.name.split(".").pop()||"mp4",v=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${y}`,{error:w}=await V.storage.from("agent-uploads").upload(v,m,{upsert:!0});if(w)throw w;const{data:{publicUrl:b}}=V.storage.from("agent-uploads").getPublicUrl(v);r(b),ue.success("Video uploaded!")}catch(y){ue.error(y.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(he,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{value:t,onChange:h=>r(h.target.value),placeholder:a,className:"flex-1"}),e.jsxs(G,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var h;return(h=l.current)==null?void 0:h.click()},disabled:o,children:[o?e.jsx(es,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(da,{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&&e.jsxs("div",{className:"relative group mt-2",children:[e.jsx("div",{className:"rounded-lg border border-border overflow-hidden bg-black w-full max-w-sm aspect-[9/16] mx-auto",children:tA(t)?e.jsx(aSe,{sourceUrl:t,thumbnailUrl:n,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",muted:!0,preload:"metadata"})}),e.jsx(G,{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:()=>r(""),children:e.jsx(vr,{className:"h-3 w-3"})})]})]})}const V9s=[{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 H9s({onVideoReady:s}){const[t,r]=k.useState(!1),[n,a]=k.useState("script"),[i,l]=k.useState(""),[o,c]=k.useState(!0),[d,h]=k.useState(!1),[m,x]=k.useState(0),[y,v]=k.useState(0),w=Yb(),b=()=>{a("script"),l(""),x(0),v(0),c(!0)},N=T=>{!T&&(n==="uploading"||n==="processing")||(r(T),T||b())},S=k.useCallback(async(T,A)=>{a("uploading");try{const I="Video Greeter",{videoId:D,libraryId:R}=await h5(I),{uploadUrl:$,apiKey:F}=await m5(D),z=new XMLHttpRequest;z.upload.onprogress=ie=>{ie.lengthComputable&&x(ie.loaded/ie.total*100)},await new Promise((ie,ye)=>{z.onload=()=>z.status>=200&&z.status<300?ie():ye(new Error("Upload failed")),z.onerror=()=>ye(new Error("Upload failed")),z.open("PUT",$),z.setRequestHeader("AccessKey",F),z.send(T)}),a("processing");let Q=0;const K=Date.now(),X=9e4,Z=`https://iframe.mediadelivery.net/embed/${R}/${D}`,re=`https://iframe.mediadelivery.net/play/${R}/${D}`;for(;Q<4;){if(await new Promise(ye=>setTimeout(ye,3e3)),Date.now()-K>X){const ye=T.size/1048576,ce=await w.mutateAsync({bunny_video_id:D,playback_url:re,file_size_mb:ye,title:I,status:"processing",touch_type:"video"});s({videoId:(ce==null?void 0:ce.id)||D,playbackUrl:Z,thumbnailUrl:null}),ue.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{r(!1),b()},1500);return}const ie=await Ev(D);if(Q=ie.status,v(ie.encodeProgress||0),Q===5||Q===6)throw new Error("Video processing failed")}const le=await Ev(D),oe=(le.storageSize||T.size)/(1024*1024),ne=await w.mutateAsync({bunny_video_id:D,playback_url:le.directPlayUrl||Z,thumbnail_url:le.thumbnailUrl,preview_url:le.previewUrl||null,duration_seconds:le.length||A,file_size_mb:oe,title:I,status:"ready",touch_type:"video"});s({videoId:(ne==null?void 0:ne.id)||D,playbackUrl:le.directPlayUrl||Z,thumbnailUrl:le.thumbnailUrl||null}),ue.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{r(!1),b()},1500)}catch(I){console.error(I),ue.error("Failed to process video. Please try again."),a("record")}},[w,s]);return e.jsxs(fs,{open:t,onOpenChange:N,children:[e.jsx(vi,{asChild:!0,children:e.jsxs(G,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(ms,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(ys,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(jr,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),n==="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(Qa,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:V9s.map(T=>e.jsxs(ke,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(T.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:T.title}),e.jsx(Ge,{variant:"outline",className:"text-[10px] shrink-0",children:T.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:T.description})]},T.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(or,{rows:5,value:i,onChange:T=>l(T.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(G,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(G,{onClick:()=>a("record"),children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),n==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(IL,{maxDurationSeconds:60,onRecordingComplete:S,onRecordingStateChange:h,onError:T=>ue.error(T),teleprompterContent:o&&i?e.jsx(DEe,{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(G,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(G,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(ln,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),n==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(es,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ei,{value:m,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(m),"%"]})]}),n==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(es,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ei,{value:y,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(y),"%"]})]}),n==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(di,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function G9s(){var A;const s=br(),{user:t}=js(),{leadSite:r}=_g(),{data:n}=$9s(),a=U9s(),{data:i=[]}=Qxe(),l=Jxe(),[o,c]=k.useState(null),[d,h]=k.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(k.useEffect(()=>{n&&!o&&c(n)},[n,o]),k.useEffect(()=>{t!=null&&t.id&&V.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:I})=>{const D=I||[];h({impressions:D.filter(R=>R.event_type==="impression").length,expands:D.filter(R=>R.event_type==="expand").length,ctaClicks:D.filter(R=>R.event_type==="cta_click").length,leads:D.filter(R=>R.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(ws,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const m=((A=i.find(I=>I.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,x=I=>c({...o,...I}),y=I=>x({ctas:I}),v=()=>y([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),w=I=>y((o.ctas||[]).filter(D=>D.id!==I)),b=(I,D)=>y((o.ctas||[]).map(R=>R.id===I?{...R,...D}:R)),N=()=>a.mutate(o),S=(r==null?void 0:r.subdomain_slug)||(t==null?void 0:t.id)||"",T=`